'''
Simple class to learn a Brill's Tagger
'''

import sys
import time

def train(corpus):
    '''
    learns rules as per Brill's tagger from the taggerd input corpora
    '''
    _, word_tag, corpus_tags, corpus_words = process_corpus(corpus)
    applicable_tags = set()
    for a_tag in word_tag.values():
        if len(a_tag) > 1:
            for k in a_tag.keys():
                applicable_tags.add(k)
    applicable_tags = filter_tags(applicable_tags)
    # get the most probable tag for a word
    word_most_probable_tag = {k : max(val, key=val.get) for k, val in word_tag.items()}
    # save unigram model of model probable tags in a file
    with open('word_best_tag.txt', 'w') as file:
        for k, val in word_most_probable_tag.items():
            file.write('%s\t%s\n' % (k, val))
    transform_queue = tbl(corpus_words, corpus_tags, word_most_probable_tag, applicable_tags)
    return transform_queue

def filter_tags(tags):
    '''
    removes those tags which are not applicable for rules
    '''
    to_remove = ('$', '#', '\'', '\'\'', '\"', '(', ')', ',', '.', ':', 'TO', 'SYM')
    return tags.difference(to_remove)

def tbl(corpus_words, corpus, word_most_probable_tag, tags):
    '''
    finds the best transformation rules for the corpus
    '''
    queue = []
    retagged_corpus = retag_best_tags(corpus_words, word_most_probable_tag)
    itr = 0
    for _ in range(20):
        itr += 1
        print('iteration', itr)
        # best_transform = get_best_transform(corpus, retagged_corpus, tags)
        best_transform = get_best_transform(corpus, retagged_corpus, tags)
        apply_transform(best_transform[1:], retagged_corpus)
        queue.append(best_transform)
    queue.sort(key=lambda x: x[0], reverse=True)
    # print(queue)
    # save the rules in a file
    with open('rules.txt', 'w') as file:
        file.write('%s\t%s\t%s\t%s\n' % ('From', 'To', 'Prev', 'Score'))
        for rule in queue:
            file.write('%s\t%s\t%s\t%d\n' % (rule[1], rule[2], rule[3], rule[0]))

    return queue

def apply_transform(transform, corpus_tags):
    '''
    retag the corpus with the best rule
    '''
    for pos in range(1, len(corpus_tags)):
        if corpus_tags[pos] == transform[0] and corpus_tags[pos-1] == transform[2]:
            corpus_tags[pos] = transform[1]

def get_best_transform(correct_tag, current_tag, tags):
    '''
    get the best rule
    '''
    score = 0
    best_rule = None
    for from_tag in tags:
        for to_tag in tags:
            transforms = {}
            if from_tag == to_tag:
                continue
            # for correct_line, current_line in zip(corpus, retagged_corpus):
            # for correct_line, current_line in correct_current:
            #     correct_words = correct_line.split()
            #     current_words = current_line.split()
            for pos in range(1, len(correct_tag)):
                # _, correct_tag = correct_words[pos].split('_')
                # _, current_tag = current_words[pos].split('_')
                # _, prev_tag = current_words[pos-1].split('_')
                if correct_tag[pos] == to_tag and current_tag[pos] == from_tag:
                    transforms[current_tag[pos-1]] = transforms.get(current_tag[pos-1], 0) + 1
                elif correct_tag[pos] == from_tag and current_tag[pos] == from_tag:
                    transforms[current_tag[pos-1]] = transforms.get(current_tag[pos-1], 0) - 1
            if transforms:
                best_z = max(transforms, key=transforms.get)
                best_instance = (transforms[best_z], from_tag, to_tag, best_z)
                if best_instance[0] > score:
                    best_rule = best_instance
                    score = best_instance[0]
    return best_rule

def retag_best_tags(corpus, word_most_probable_tag):
    '''
    retag the corpus with the most probable tags
    '''
    retagged_corpus = []
    for tagged_word in corpus:
        word, _ = tagged_word.split('_')
        retagged_corpus.append(word_most_probable_tag.get(word))
    return retagged_corpus

def process_corpus(file):
    '''
    reads the corpus file and finds the most probable tags
    '''
    tags = set()
    word_tag = {}
    corpus_tags = []
    corpus_words = []
    with open(file, 'r') as corpus:
        lines = corpus.read().splitlines()
    for line in lines:
        # corpus_sentences.append(line)
        for tagged_word in line.split():
            corpus_words.append(tagged_word)
            word, tag = tagged_word.split('_')
            corpus_tags.append(tag)
            tags.add(tag)
            if word in word_tag:
                temp = word_tag.get(word)
                if tag in temp:
                    temp[tag] = temp.get(tag) + 1
                else:
                    temp[tag] = 1
            else:
                word_tag[word] = {tag: 1}
    return tags, word_tag, corpus_tags, corpus_words

def main():
    '''
    accepts the corpus as a runtime argument
    '''
    corpus = sys.argv[1]
    start = time.time()
    train(corpus)
    print('time', time.time() - start)

if __name__ == '__main__':
    main()


import tkinter

map_data = [
    [0,1,1,1,1,0,0,1,1,1,1,0],
    [0,2,3,3,2,1,1,2,3,3,2,0],
    [0,3,0,0,3,3,3,3,0,0,3,0],
    [0,3,1,1,3,0,0,3,1,1,3,0],
    [0,3,2,2,3,0,0,3,2,2,3,0],
    [0,3,0,0,3,1,1,3,0,0,3,0],
    [0,3,1,1,3,3,3,3,1,1,3,0],
    [0,2,3,3,2,0,0,2,3,3,2,0],
    [0,0,0,0,0,0,0,0,0,0,0,0]
]

def draw_screen(): #open game monitor
    for y in range(9):
        for x in range(12):
            canvas.create_image(x*60+30, y*60+30, image=img_bg[map_data[y][x]])

root = tkinter.Tk()
root.title("HARAHARA penguin rabilince")
root.resizable(False,False)
canvas = tkinter.Canvas(width=720,height=540)
canvas.pack()
img_bg = [
    tkinter.PhotoImage(file = "/home/pi/Downloads/py2_samples/Chapter3/image_penpen/chip00.png"),
    tkinter.PhotoImage(file = "/home/pi/Downloads/py2_samples/Chapter3/image_penpen/chip01.png"),
    tkinter.PhotoImage(file = "/home/pi/Downloads/py2_samples/Chapter3/image_penpen/chip02.png"),
    tkinter.PhotoImage(file = "/home/pi/Downloads/py2_samples/Chapter3/image_penpen/chip03.png")
]
draw_screen()
root.mainloop()


class Titandex:
    def __init__(self, nm, he, st, ws):
        self.name = nm
        self.height = he
        self.strength = st
        self.win_streak = ws

    def TitanvsScout(self, name_scout, strength_scout):

        if self.strength > strength_scout:
            self.win_streak += 1
            print(f"{self.name} wins over {name_scout}")
        elif self.strength < strength_scout:
            print(f"{name_scout} wins over {self.name}")
        else:
            print(f"Match is a Draw")

    def TitanvsTitan(self, titan2):

        if self.strength > titan2.strength:
            self.win_streak += 1
            print(f"{self.name} wins over {titan2.name}")
        elif self.strength < titan2.strength:
            print(f"{titan2.name} wins over {self.name}")
            titan2.win_streak += 1
        elif self.name == titan2.name:
            print(f"{titan2.name} cannot fight itself")
        else:
            print(f"Match is a Draw")

Founding_Titan = Titandex('Founding_Titan', 13, 350, 0)
Attack_Titan = Titandex('Attack_Titan', 15, 275, 0)
Armored_Titan = Titandex('Armored_Titan', 15, 250, 0)
Collosal_Titan = Titandex('Collosal_Titan', 60, 300, 0)

Founding_Titan.TitanvsScout("Levi",300)
Founding_Titan.TitanvsScout("Mikasa",275)
print(Founding_Titan.win_streak)

Armored_Titan.TitanvsScout("Levi",300)
Armored_Titan.TitanvsScout("Mikasa",275)
Armored_Titan.TitanvsScout("Connie",180)
print(Armored_Titan.win_streak)


import sqlite3
import datetime
#from appJar import gui
from config import baseDir, users
from os import path

import sqlalchemy
from sqlalchemy import create_engine

def insertBon(c, total, shop, buyer, date=None):
	if date is None:
		date = datetime.datetime.now().strftime("%Y-%m-%d")
	c.execute("INSERT INTO bons(Total, Shop, Buyer, Date) VALUES(?,?,?,?)", (total, shop, buyer, date))
	c.execute("select last_insert_rowid()")
	return c.fetchone()

def enterBon(c):
	name = ''
	while name not in users:
		name = input("name: ")
	shop = input("shop: ")
	total = float(input("total: "))
	date = input("date (YYYY-MM-DD): ")
	if date == "":
		date = None

	purchaseId = insertBon(c, total, shop, name, date)
	print(purchaseId)

def setup():
	print(path.join(baseDir, 'resources', 'purchases'))
	conn = sqlite3.connect(path.join(baseDir, 'resources', 'purchases'))
	return conn

def close(conn):
	conn.commit()
	conn.close()

def enterBonData(total, shop, buyer, date):
	conn = setup()
	c = conn.cursor()
	#check inputs
	purchaseId = insertBon(c, total, shop, buyer, date)
	close(conn)
	return purchaseId

def enterItem(purchaseId, productName, price, amount):
	conn = setup()
	c = conn.cursor()
	c.execute("select shop from bons where purchaseId = ?", (purchaseId,))
	shop = c.fetchone()[0]
	print(shop)

	c.execute("select exists (select ProductId from products where productName = ? and Shop = ?)", (productName, shop))
	if c.fetchone()[0] == 0:
		c.execute("insert into products(productName, Price, Shop) VALUES (?, ?, ?)", (productName, price, shop) )
		c.execute("select last_insert_rowid()")

		productId = c.fetchone()[0]
	else:
		c.execute("select ProductId from products where productName = ? and Shop = ? LIMIT 1", (productName, shop))
		productId = c.fetchone()[0]

	c.execute("select exists (select purchaseId from items where purchaseId = ? and ItemId = ?)", (purchaseId, productId))
	if c.fetchone()[0] == 1:
		c.execute("select amount from items where purchaseId = ? and ItemId = ?", (purchaseId, productId))
		oldAmount = c.fetchone()[0]
		c.execute("Update items set amount=? where purchaseId = ? and ItemId = ?", (oldAmount+amount, purchaseId, productId))
	else:
		c.execute("insert into items(purchaseId, ItemId, Price, Amount) VALUES (?,?,?,?)", (purchaseId, productId, price, amount))
	close(conn)
	return purchaseId

def getList():
	conn = setup()
	c = conn.cursor()
	c.execute("select * from bons")
	bons = c.fetchall()
	close(conn)
	bons.sort(key=lambda bon: bon[4], reverse=True)
	return bons

def getItems(purchaseId):
	conn = setup()
	c = conn.cursor()
	c.execute("select products.productName, items.Price, items.amount, items.ItemId from items inner join products on items.ItemId = products.productId where items.purchaseId = ?", (purchaseId, ))
	items = c.fetchall()
	close(conn)
	return items

def deleteItem(purchaseId, itemId):
	conn = setup()
	c = conn.cursor()
	c.execute("delete from items where purchaseId=? and itemId=?", (purchaseId, itemId))
	close(conn)

def getBon(purchaseId):
	conn = setup()
	c = conn.cursor()
	c.execute("select * from bons where purchaseId = ?", (purchaseId,))
	bon = c.fetchall()
	close(conn)
	return bon[0]

if __name__ == '__main__':
	print(getList())


import boto3
import json
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

html_template1 = """

{{content}}

点击这里 批准申请.

点击这里 拒绝申请.

"""

text_template1 = """
{{content}}\r\n
点击这里批准申请:\r\n
{{link1}}
点击这里拒绝申请:\r\n
{{link2}}
"""

html_template2 = """

{{content}}

"""

text_template2 = """
{{content}}\r\n
"""

ses = boto3.client('ses')

response = ses.create_template(

        Template={
            "TemplateName": "approve_workflow_result",
            "SubjectPart": "{{subject}}!",
            "HtmlPart": html_template2,
            "TextPart": text_template2
        }

)
print(response)


import math

class IntrathoracicPressure:
    def __init__(self, model, **args):
        # initialize the super class
        super().__init__()

        # initialize a dictionary holding the targets
        self.targets = {}

        # set the independent properties
        for key, value in args.items():
            setattr(self, key, value)

        # define the dependent properties
        self.pres = 0

        # store a reference to the rest of the model
        self.model = model

        # get the modeling stepsize from the model
        self.t = model.modeling_stepsize

    # this method is called by the model engine in every model step
    def model_step (self):
        # during every model step the transmural pressure is calculates
        if self.is_enabled:
            self.calculate()

    def calculate (self):
        # calculate the intrathoracic pressure
        cum_pres = 0
        counter = 0

        for source in self.sources:
            cum_pres += self.model.components[source].pres
            counter +=1

        self.pres = cum_pres / counter

        # apply the mean intrathoracic pressure to the targets
        for target, value in self.targets.items():
            self.model.components[target].pres_itp = (value * self.pres)


from SeleniumLibrary import BrowserManagementKeywords
from SeleniumLibrary.base import LibraryComponent, keyword

class Plugin(LibraryComponent):

    def __init__(self, ctx):
        LibraryComponent.__init__(self, ctx)

    @keyword
    def open_browser(self, location):
        """Overwrite existing keyword."""
        self.info(location)
        return location

    @keyword
    def open_real_browser(self):
        bm = BrowserManagementKeywords(self.ctx)
        bm.open_browser('http://localhost:7000/html', 'chrome')

    @keyword
    def do_something(self):
        element = self.find_element('xpath://title')
        self.info('One element %s' % element)
        elements = self.find_elements('xpath://*')
        self.info('List of elements %s' % elements)
        self.info('Currently active driver here: %s ' % self.driver)


from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras. layers import Conv2D, MaxPooling2D
from keras import backend as K

import tensorflow  as tf
from keras.layers import *
from keras.callbacks import ReduceLROnPlateau

import matplotlib.pyplot as plt

"""## Veri Setinin İndirilmesi
 0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣
"""

(x_train, y_train), (x_test, y_test) = mnist.load_data()

"""### Yapılandırma Ayarları
Küme boyutu, sınıf sayısı, eğitim epoch sayısı gibi parametreleri tüm optimizasyon denemeleri için aynı şekilde ayarlıyoruz!
"""

batch_size = 128 # Küme Boyutu
num_classes = 10 # Sınıf Sayısı
epochs = 20 # Eğitimin epoch sayısı
w_l2 = 1e-5 # Başlangıç

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=1e-5)

img_rows, img_cols = 28, 28

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# sınıf vektörlerini ikili sınıf matrislerine dönüştürmek
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

from keras import optimizers

"""### Tüm optimizasyon yöntemlerini eğiteceğimiz evrişimli sinir ağı modelinin oluşturulması"""

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),  kernel_regularizer=regularizers.l2(w_l2),
                 input_shape=input_shape))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3),  kernel_regularizer=regularizers.l2(w_l2)))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, kernel_regularizer=regularizers.l2(w_l2)))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

"""### STOKASTİK GRADYAN/BAYIR İNİŞ OPTİMİZASYONU

Tüm örneklerden geçmek yerine, Stokastik Degrade İniş (SGD), her bir örnekte $(x ^ i, y ^ i)$  parametrelerin güncellenmesini gerçekleştirir. Bu nedenle, öğrenme her örnekte gerçekleşir:

$w = w− α∇wJ(x^i,y^i;w,b)$

```
for i in range(num_epochs):
    np.random.shuffle(data)
    for example in data:
        grad = compute_gradient(example, params)
        params = params - learning_rate * grad
```
"""

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.SGD(),
              metrics=['accuracy'])
model.summary()

"""### Modelin Eğitilm ve Test Sonuçları"""

hist_SGD=model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test), callbacks=[reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

"""### ADAM OPTİMİZASYONU
***Adam veya adaptif momentum AdaDelta’ya benzer bir algoritmadır. AdaDelta’dan farklı olarak parametrelerin her birinin öğrenme oranlarının yanısıra momentum değişikliklerini de önbellekte (cache) saklar; yani RMSprop ve momentumu birleştirir.***
"""

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])

model.summary()

"""### Modelin Eğitilm ve Test Sonuçları"""

hist_ADAM=model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test), callbacks=[reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

"""### RMSprop OPTİMİZASYONU

***RMSprop ve benzeri olan AdaDelta, AdaGrad’ın bu sorununu çözerek bu hızlı düşüşü önler.***
"""

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.RMSprop(),
              metrics=['accuracy'])
model.summary()

hist_RMSprob=model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test), callbacks=[reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

"""### ADAGRAD OPTİMİZASYONU

***AdaGrad seyrek parametreler için büyük güncellemeler yaparken sık parametreler için daha küçük güncellemeler yapar. Bu nedenle NLP ve resim tanıma gibi seyrek veriler için daha uygundur.***
AdaGrad’da her parametrenin kendi öğrenme hızı vardır ve algoritmanın özelliklerine bağlı olarak öğrenme oranı giderek azalmaktadır. Bu nedenle öğreneme oranı giderek azalır ve zamanın bir noktasında sistem öğrenmeyi bırakır. Bu AdaGrad’ın en büyük dez avantajıdır.
"""

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adagrad(),
              metrics=['accuracy'])
model.summary()

hist_adagrad=model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test), callbacks=[reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

"""### ADADELTA OPTİMİZASYONU
***AdaDelta, AdaGrad’ın bu sorununu çözerek bu hızlı düşüşü önler.***
"""

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()

hist_adadelta=model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test), callbacks=[reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

"""## Kaydedilen sonuçların çizilmesi için plot fonksiyonunun tanımlanması"""

def plot_history(hists, attribute='val_loss', axis=(-1,21,0.85,0.94), loc='lower right'):
    ylabel = {'oss': 'loss', 'acc': 'accuracy'}
    title = {'val_loss': 'valid. loss', 'loss': 'trn. loss', 'val_acc': 'valid. accuracy', 'acc': 'trn. accuracy'}
    num_hists = len(hists)

    plt.figure(figsize=(12, 8))
    plt.axis(axis)
    for i in range(num_hists):
        plt.plot(hists[i].history[attribute])
    plt.title(title[attribute])
    plt.ylabel(ylabel[attribute[-3:]])
    plt.xlabel('epoch')
    plt.legend(['ADAM', 'SGD', 'RMSprob', 'adadelta', 'adagrad'], loc=loc)

    plt.show()

hists = [hist_ADAM, hist_SGD, hist_RMSprob, hist_adadelta, hist_adagrad]

"""## SONUÇLARIN KARŞILAŞTIRILMASI"""

plot_history(hists, attribute='acc', axis=(-1,21,0.985,1.0), loc='lower right')

plot_history(hists, attribute='loss', axis=(-1,21,0.009,0.07), loc='upper right')


# -*- coding: utf-8 -*-
#
# This file is part of gpgliblib (https://github.com/mathiasertl/gpgliblib).
#
# gpgliblib is free software: you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# gpgliblib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with gpgliblib. If
# not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import
from __future__ import unicode_literals

from contextlib import contextmanager
from datetime import datetime
from threading import local

import gpgme
import gpgme.editutil
import six
from gpgme import ERR_EOF
from gpgme import ERR_GENERAL
from gpgme import ERR_SOURCE_GPGME
from gpgme import ERR_SOURCE_UNKNOWN
from gpgme import ERR_UNUSABLE_PUBKEY

from .base import GpgBackendBase
from .base import GpgBadSignature
from .base import GpgDecryptionFailed
from .base import GpgKey
from .base import GpgKeyNotFoundError
from .base import GpgSecretKeyPresent
from .base import GpgUntrustedKeyError
from .base import MODE_ARMOR
from .base import UnknownGpgliblibError
from .base import VALIDITY_FULL
from .base import VALIDITY_MARGINAL
from .base import VALIDITY_NEVER
from .base import VALIDITY_ULTIMATE
from .base import VALIDITY_UNKNOWN
from .utils import get_version

class GpgMeBackend(GpgBackendBase):
    """A gpgliblib backend using `pygpgme <https://pypi.python.org/pypi/pygpgme/>`_.

    ``pygpgme`` cannot get the GnuPG version used by itself, and setting key trust works different
    depending on what version is used. This backend thus requires the ``gnupg_version`` parameter
    to be passed if you want to set the trust of keys.
    """

    def __init__(self, **kwargs):
        super(GpgMeBackend, self).__init__(**kwargs)
        self._local = local()

    @property
    def context(self):
        if hasattr(self._local, 'context') is False:
            context = gpgme.Context()
            context.armor = True

            if self._path or self._home:
                context.set_engine_info(gpgme.PROTOCOL_OpenPGP, self._path, self._home)
            self._local.context = context

        return self._local.context

    @contextmanager
    def _attrs(self, signers=None, armor=None):
        context = self.context

        if signers is not None:
            old_signers = context.signers
            context.signers = signers
        if armor is not None:
            old_armor = context.armor
            context.armor = armor

        try:
            yield context
        finally:
            if signers is not None:
                context.signers = old_signers
            if armor is not None:
                context.armor = old_armor

    @property
    def gnupg_version(self):
        if self._gnupg_version is None:
            self._gnupg_version = get_version()

        return self._gnupg_version

    def get_key(self, fingerprint):
        return GpgMeKey(self, fingerprint)

    def _get_gpgme_key(self, obj):
        if isinstance(obj, six.string_types):
            return GpgMeKey(self, obj)._key
        return obj._key

    def _encrypt_flags(self, always_trust=True, **kwargs):
        flags = 0
        if always_trust is True:
            flags |= gpgme.ENCRYPT_ALWAYS_TRUST
        return flags

    def _encrypt(self, data, recipients, always_trust):
        recipients = [self._get_gpgme_key(r) for r in recipients]

        output_bytes = six.BytesIO()
        flags = self._encrypt_flags(always_trust=always_trust)
        try:
            if self.context.signers:
                self.context.encrypt_sign(recipients, flags, six.BytesIO(data), output_bytes)
            else:
                self.context.encrypt(recipients, flags, six.BytesIO(data), output_bytes)
        except gpgme.GpgmeError as e:
            if e.source == ERR_SOURCE_UNKNOWN and e.code == ERR_GENERAL:  # pragma: gpg1
                raise GpgUntrustedKeyError("Key not trusted.")

            if e.source == ERR_SOURCE_GPGME and e.code == ERR_UNUSABLE_PUBKEY:  # pragma: gpg2
                raise GpgUntrustedKeyError("Key not trusted.")

            raise UnknownGpgliblibError(e.strerror)  # pragma: no cover

        output_bytes.seek(0)
        return output_bytes.getvalue()

    def sign(self, data, signer):
        output_bytes = six.BytesIO()

        with self._attrs(signers=[self._get_gpgme_key(signer)]) as context:
            context.sign(six.BytesIO(data), output_bytes, gpgme.SIG_MODE_DETACH)

        output_bytes.seek(0)
        return output_bytes.getvalue()

    def encrypt(self, data, recipients, **kwargs):
        always_trust = kwargs.get('always_trust', self._default_trust)
        return self._encrypt(data, recipients, always_trust)

    def sign_encrypt(self, data, recipients, signer, **kwargs):
        always_trust = kwargs.get('always_trust', self._default_trust)
        with self._attrs(signers=[self._get_gpgme_key(signer)]):
            return self._encrypt(data, recipients, always_trust)

    def verify(self, data, signature):
        signatures = self.context.verify(six.BytesIO(signature), six.BytesIO(data), None)

        errors = list(filter(lambda s: s.status is not None, signatures))
        if not errors:
            return signatures[0].fpr
        raise GpgBadSignature("Bad signature", errors=errors)

    def decrypt(self, data):
        output = six.BytesIO()
        try:
            self.context.decrypt(six.BytesIO(data), output)
        except gpgme.GpgmeError as e:
            if e.source == gpgme.ERR_SOURCE_GPGME and e.code == gpgme.ERR_DECRYPT_FAILED:
                raise GpgDecryptionFailed(e.strerror)
            raise UnknownGpgliblibError(e.strerror)  # pragma: no cover

        return output.getvalue()

    def decrypt_verify(self, data):
        output = six.BytesIO()
        signatures = self.context.decrypt_verify(six.BytesIO(data), output)

        errors = list(filter(lambda s: s.status is not None, signatures))
        if not errors:
            if signatures:
                return output.getvalue(), signatures[0].fpr
            else:
                return output.getvalue(), None

    def import_key(self, data):
        if six.PY3 and isinstance(data, str):  # pragma: py3
            data = data.encode('utf-8')
        elif six.PY2 is True and isinstance(data, unicode):  # pragma: py2
            data = data.encode('utf-8')

        result = self.context.import_(six.BytesIO(data))
        return [GpgMeKey(self, r[0]) for r in result.imports]

    def import_private_key(self, data):
        if six.PY3 and isinstance(data, str):
            data = data.encode('utf-8')

        result = self.context.import_(six.BytesIO(data))
        return list(set([GpgMeKey(self, r[0]) for r in result.imports]))

    def list_keys(self, query=None, secret_keys=False):
        return [GpgMeKey(self, key=k) for k in self.context.keylist(query, secret_keys)]

class GpgMeKey(GpgKey):
    _loaded_key = None
    _loaded_secret_key = None

    def __init__(self, backend, fingerprint=None, key=None):
        if not fingerprint and not key:
            raise ValueError("Must pass either fingerprint or key.")
        elif not fingerprint:
            fingerprint = key.subkeys[0].fpr

        super(GpgMeKey, self).__init__(backend, fingerprint)
        self._loaded_key = key

    @property
    def _key(self):
        if self._loaded_key is None:
            try:
                self._loaded_key = self.backend.context.get_key(self.fingerprint)
            except gpgme.GpgmeError as e:
                if e.source == ERR_SOURCE_GPGME and e.code == ERR_EOF:
                    raise GpgKeyNotFoundError(self.fingerprint)

                raise UnknownGpgliblibError(e.strerror)  # pragma: no cover
        return self._loaded_key

    @property
    def _secret_key(self):
        if self._loaded_secret_key is None:
            try:
                self._loaded_secret_key = self.backend.context.get_key(self.fingerprint, True)
            except gpgme.GpgmeError:
                self._loaded_secret_key = False
        return self._loaded_secret_key

    def refresh(self):
        self._loaded_key = None

    @property
    def name(self):
        return self._key.uids[0].name

    @property
    def comment(self):
        comment = self._key.uids[0].comment
        if comment:
            return comment

    @property
    def email(self):
        return self._key.uids[0].email

    @property
    def has_secret_key(self):
        return self._secret_key is not False

    @property
    def trust(self):
        if self._key.owner_trust == gpgme.VALIDITY_UNKNOWN:
            return VALIDITY_UNKNOWN
        elif self._key.owner_trust == gpgme.VALIDITY_NEVER:
            return VALIDITY_NEVER
        elif self._key.owner_trust == gpgme.VALIDITY_MARGINAL:
            return VALIDITY_MARGINAL
        elif self._key.owner_trust == gpgme.VALIDITY_FULL:
            return VALIDITY_FULL
        elif self._key.owner_trust == gpgme.VALIDITY_ULTIMATE:
            return VALIDITY_ULTIMATE
        else:  # pragma: no cover
            return VALIDITY_UNKNOWN

    @trust.setter
    def trust(self, value):
        if value == VALIDITY_NEVER:
            value = gpgme.VALIDITY_NEVER
        elif value == VALIDITY_MARGINAL:
            value = gpgme.VALIDITY_MARGINAL
        elif value == VALIDITY_FULL:
            value = gpgme.VALIDITY_FULL
        elif value == VALIDITY_ULTIMATE:
            value = gpgme.VALIDITY_ULTIMATE
        else:
            raise ValueError("Unknown value passed.")

        if self.backend.gnupg_version >= (2, ):  # pragma: gpg2

            @gpgme.editutil.key_editor
            def _edit_trust_gnupg2(ctx, key, trust):
                """Copy of gpgme.editutil.edit_trust fixed for gpg2."""
                if trust not in (gpgme.VALIDITY_UNDEFINED,
                                 gpgme.VALIDITY_NEVER,
                                 gpgme.VALIDITY_MARGINAL,
                                 gpgme.VALIDITY_FULL,
                                 gpgme.VALIDITY_ULTIMATE):
                    raise ValueError('Bad trust value %d' % trust)

                status, args = yield None

                # we need to yield an additional None in gpg2.
                status, args = yield None

                assert args == 'keyedit.prompt'
                status, args = yield 'trust\n'

                assert args == 'edit_ownertrust.value'
                status, args = yield '%d\n' % trust

                if args == 'edit_ownertrust.set_ultimate.okay':
                    status, args = yield 'Y\n'

                assert args == 'keyedit.prompt'
                status, args = yield 'quit\n'

                assert args == 'keyedit.save.okay'
                status, args = yield 'Y\n'

            _edit_trust_gnupg2(self.backend.context, self._key, value)
        else:
            gpgme.editutil.edit_trust(self.backend.context, self._key, value)
        self.refresh()

    @property
    def expires(self):
        expires = lambda i: datetime.fromtimestamp(i) if i else None
        subkeys = {sk.fpr: expires(sk.expires) for sk in self._key.subkeys}
        return subkeys[self.fingerprint]

    @property
    def revoked(self):
        return self._key.revoked

    def export(self, mode=MODE_ARMOR, output=None):
        if output is None:
            buf = six.BytesIO()
        else:
            buf = output

        if mode == MODE_ARMOR:
            args = {'armor': True}
        else:
            args = {'armor': False}

        with self.backend._attrs(**args) as context:
            context.export(self.fingerprint, buf)

        if output is None:
            value = buf.getvalue()
            if mode == MODE_ARMOR:
                return value.decode('utf-8')
            return value

    def delete(self, secret_key=False):
        if self.has_secret_key and not secret_key:
            raise GpgSecretKeyPresent('Secret key is present.')

        # NOTE: unlike the unofficial docs, this function does not take any keyword arguments
        self.backend.context.delete(self._key, secret_key)


from __future__ import division
import os
import math
import random

import numpy as np
import tensorflow as tf
import cv2
import time
slim = tf.contrib.slim
from collections import namedtuple

import sys

from nets import ssd_vgg_300, ssd_common, np_methods
from preprocessing import ssd_vgg_preprocessing
from darkflow.net.build import TFNet

classes = ['aeroplane', 'bicycle', 'bird', 'boat',
           'bottle', 'bus', 'car', 'cat', 'chair',
           'cow', 'diningtable', 'dog', 'horse',
           'motorbike', 'person', 'pottedplant',
           'sheep', 'sofa', 'train', 'tvmonitor']

BBox = namedtuple("BBox", ('ymin', 'xmin', 'ymax', 'xmax'))

def scale_box(box, x_scale, y_scale):
    scaled = BBox(ymin=box.ymin*y_scale,
                  xmin=box.xmin*x_scale,
                  ymax=box.ymax*y_scale,
                  xmax=box.xmax*x_scale)
    return scaled

def convert_ssd_result(rclasses, rscores, rbboxes):
    results = []
    for classid, score, bb in zip(rclasses, rscores, rbboxes):
        # bb[[0,2]]*w
        # bb[[1,3]]*h
        # bb = bb.astype(int)
        [ymin, xmin, ymax, xmax] = bb
        res = {}
        res['confidence'] = score
        res['label'] = classes[classid-1]
        res['box']=BBox(*bb)
        results.append(res)
    return results

def convert_yolo_result(res,w,h):
    for r in res:
        xmin=r['topleft']['x']
        ymin=r['topleft']['y']
        xmax=r['bottomright']['x']
        ymax=r['bottomright']['y']
        r['box']=scale_box(BBox(ymin,xmin,ymax,xmax), 1/w,1/h)
        for field in ['bottomright','topleft']:
            del r[field]
    return res

class SSD:
    def __init__(self, weights = "model_files/ssd_300_vgg.ckpt/ssd_300_vgg.ckpt", mem_frac=1):
        tf.reset_default_graph()
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=mem_frac)

        self.sess = sess =tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
        config = tf.ConfigProto(log_device_placement=False, gpu_options=gpu_options)
        self.isess = isess = tf.InteractiveSession(config=config)
        self.net_shape = net_shape = (300, 300)
        data_format = 'NHWC'
        img_input = tf.placeholder(tf.uint8, shape=(None, None, 3))
        image_pre, labels_pre, bboxes_pre, bbox_img = ssd_vgg_preprocessing.preprocess_for_eval(
            img_input, None, None, net_shape, data_format, resize=ssd_vgg_preprocessing.Resize.WARP_RESIZE)
        image_4d = tf.expand_dims(image_pre, 0)
        reuse = True if 'ssd_net' in locals() else None
        ssd_net = ssd_vgg_300.SSDNet()
        with slim.arg_scope(ssd_net.arg_scope(data_format=data_format)):
            predictions, localisations, _, _ = ssd_net.net(image_4d, is_training=False, reuse=reuse)
        isess.run(tf.global_variables_initializer())
        saver = tf.train.Saver()
        saver.restore(isess, weights)

        # SSD default anchor boxes.
        self.ssd_anchors = ssd_net.anchors(net_shape)
        self.bbox_img = bbox_img
        self.img_input = img_input
        self.image_4d = image_4d
        self.ssd_net = ssd_net
        self.predictions = predictions
        self.localisations = localisations

    def __call__(self,img, select_threshold=0.5, nms_threshold=.45, net_shape=(300, 300)):
        # Run SSD network.
        img_input = self.img_input
        image_4d = self.image_4d
        predictions = self.predictions
        localisations = self.localisations
        bbox_img = self.bbox_img
        ssd_anchors = self.ssd_anchors
        isess = self.isess
        rimg, rpredictions, rlocalisations, rbbox_img = isess.run([image_4d, predictions, localisations, bbox_img],feed_dict={img_input: img})

        # Get classes and bboxes from the net outputs.
        rclasses, rscores, rbboxes = np_methods.ssd_bboxes_select(
                rpredictions, rlocalisations, ssd_anchors,
                select_threshold=select_threshold, img_shape=self.net_shape, num_classes=21, decode=True)

        rbboxes = np_methods.bboxes_clip(rbbox_img, rbboxes)
        rclasses, rscores, rbboxes = np_methods.bboxes_sort(rclasses, rscores, rbboxes, top_k=400)
        rclasses, rscores, rbboxes = np_methods.bboxes_nms(rclasses, rscores, rbboxes, nms_threshold=nms_threshold)
        # Resize bboxes to original image shape. Note: useless for Resize.WARP!
        rbboxes = np_methods.bboxes_resize(rbbox_img, rbboxes)
        res = {}

        h,w = img.shape[:2]

        return convert_ssd_result(rclasses, rscores, rbboxes)

class YOLO:
    def __init__(self, weights="model_files/yolo.weights",
                 cfg="model_files/yolo.cfg", mem_frac=1):
        options = {"model": cfg,
                   "load": weights,
                   "threshold": 0.1,
                   "gpu":mem_frac}
        self.net = TFNet(options)

    def __call__(self, img):
        h,w = img.shape[:2]
        return convert_yolo_result(self.net.return_predict(img),w,h)


import constants
import sys
from PIL import Image, ImageOps
from copy import deepcopy
import base64
import io

class QrCode:

    @staticmethod
    def version_detector(error_corr, text, encoding_type):
        num_of_chars = len(bytearray(text, 'utf-8'))
        for i in range(1, 41):
            if constants.char_capacities[i][error_corr][encoding_type] >= num_of_chars:
                return i
        return -1

    @staticmethod
    def char_count_indicator(text, encoding_type, version, return_binary=False):
        k = int()
        if version <= 9:
            k = constants.character_count_indicator[1][encoding_type]
        elif version <= 26:
            k = constants.character_count_indicator[2][encoding_type]
        else:
            k = constants.character_count_indicator[3][encoding_type]

        if return_binary:
            return f"{len(bytearray(text, 'utf-8')):0{k}b}"
        return k

    def byte_encoding(self):
        text_bytes = bytearray(self.text, 'utf-8')
        byte_lists = []
        byte_lists = [f"{i:08b}" for i in text_bytes]
        # print(byte_lists)
        return ''.join(byte_lists)

    # Not Yet Implemented
    def alphanumeric_encoding(self):
        pass

    # Not Yet Implemented
    def numeric_encoding(self):
        pass

    def __init__(self, text, encoding_type='bytes', error_corr='L', version=None):
        self.text = text
        self.encoding_type = encoding_type
        self.error_corr = error_corr
        if version:
            self.version = version
        else:
            self.version = QrCode.version_detector(error_corr, text, encoding_type)
            if self.version == -1:
                raise Exception(
                    f"Cannot make QR Code of {len(bytes(text, 'utf-8'))} bytes. Try Reduce the error correction if possible.")

    def __str__(self):
        return f"[{self.text}, {self.encoding_type}, {self.error_corr}, {self.version}]"

    # Encode it into binary
    def into_binary(self):

        char_count = QrCode.char_count_indicator(self.text, self.encoding_type, self.version, return_binary=True)

        mode_indi = f"{constants.mode_indicator[self.encoding_type]:04b}"

        encoded_data = ''.join([mode_indi, char_count, self.byte_encoding()])

        required_list = constants.error_corr_table[self.version][self.error_corr]

        required_bits = 8 * ((required_list[1] * required_list[2]) + (required_list[3] * required_list[4]))

        # print(self)
        # print(f"Required - bits:{required_bits}")
        # terminator = ""

        if required_bits - len(encoded_data) >= 4:
            terminator = 4 * '0'
        else:
            terminator = (required_bits - len(encoded_data)) * '0'

        encoded_data += terminator
        if len(encoded_data) % 8 != 0:
            encoded_data += (8 - (len(encoded_data) % 8)) * '0'
        bytes_left = (required_bits - len(encoded_data)) // 8

        pads = [f"{constants.PAD0:08b}" if i % 2 == 0 else f"{constants.PAD1:08b}" for i in range(bytes_left)]

        bin_form = ''.join([encoded_data, *pads])

        int_form = [int(f"{bin_form[i:i + 8]}", base=2) for i in range(0, len(bin_form), 8)]

        iter = 0
        group1 = []
        for i in range(0, required_list[1]):
            block = []
            for j in range(0, required_list[2]):
                block.append(int_form[iter])
                iter += 1
            group1.append(block)
        group2 = []
        for i in range(0, required_list[3]):
            block = []
            for j in range(0, required_list[4]):
                block.append(int_form[iter])
                iter += 1
            group2.append(block)

        error_blocks = []
        for i in group1:
            error_blocks.append(self.poly_div(i.copy()))
        for i in group2:
            error_blocks.append(self.poly_div(i.copy()))
        final_block = []
        if not group2:
            for i in zip(*group1):
                final_block.extend(i)
        else:
            for i in zip(*group1, *group2):
                final_block.extend(i)
            for i in range(len(group2)):
                final_block.append(group2[i][-1])

        for i in zip(*error_blocks):
            final_block.extend(i)
        final_block = map(lambda a: f"{a:08b}", final_block)
        return ''.join(final_block) + ('0' * constants.remain_bits[self.version])

    def poly_div(self, encod_coeff):
        ecc = constants.error_corr_table[self.version][self.error_corr][0]
        encod_coeff.extend([0] * ecc)
        gen_coeff = constants.generator_polynomials[ecc].copy()
        i = 0
        while i < len(encod_coeff) - ecc:
            largest_deg_coeff = encod_coeff[i]
            # print(largest_deg_coeff)
            if largest_deg_coeff != 0:
                encod_coeff[i] ^= largest_deg_coeff
                for j in range(0, ecc):
                    encod_coeff[i + j + 1] = encod_coeff[i + j + 1] ^ constants.galois_log[
                        (gen_coeff[j] + constants.galois_antilog[largest_deg_coeff]) % 255]
                    # print(encod_coeff[i + j + 1], end=" ")
                # print()
                # print(encod_coeff)
            i += 1
        # print(encod_coeff[i:])
        return encod_coeff[i:]

"""
    The image convention:smallest value is black and largest value is white
    QR Code convetion : 0 is white and 1 is black
"""

class QrBuilder():
    ZERO = 255
    ONE = 0

    # print(size)

    def __init__(self, qrcode):
        self.qrcode = qrcode
        self.size = (constants.version_size[self.qrcode.version], constants.version_size[self.qrcode.version])
        pixel = [128 for i in range(0, self.size[0])]
        self.matrix = [deepcopy(pixel) for i in range(0, self.size[0])]
        self.data = self.qrcode.into_binary()

    def finding_pattern(self, i, j):
        for col in range(j, j + 7):
            self.matrix[i][col] = QrBuilder.ONE
            self.matrix[i + 6][col] = QrBuilder.ONE
        for row in range(i + 1, i + 6):
            self.matrix[row][j] = QrBuilder.ONE
            self.matrix[row][j + 6] = QrBuilder.ONE
        for col in range(j + 1, j + 6):
            self.matrix[i + 1][col] = QrBuilder.ZERO
            self.matrix[i + 5][col] = QrBuilder.ZERO
        for row in range(i + 2, i + 5):
            self.matrix[row][j + 1] = QrBuilder.ZERO
            self.matrix[row][j + 5] = QrBuilder.ZERO
        for row in range(i + 2, i + 5):
            for col in range(j + 2, j + 5):
                self.matrix[row][col] = QrBuilder.ONE

    def finding_position(self):
        self.finding_pattern(0, 0)
        self.finding_pattern(-7, 0)
        self.finding_pattern(0, -7)

        # for separators
        for i in range(0, 8):
            self.matrix[7][i] = QrBuilder.ZERO
            self.matrix[i][7] = QrBuilder.ZERO
            self.matrix[-8][i] = QrBuilder.ZERO
            self.matrix[i][-8] = QrBuilder.ZERO
            self.matrix[-i - 1][7] = QrBuilder.ZERO
            self.matrix[7][-i - 1] = QrBuilder.ZERO

    def alignment_pattern(self, i, j):
        for col in range(j, j + 5):
            self.matrix[i][col] = QrBuilder.ONE
            self.matrix[i + 4][col] = QrBuilder.ONE
        for row in range(i + 1, i + 4):
            self.matrix[row][j] = QrBuilder.ONE
            self.matrix[row][j + 4] = QrBuilder.ONE
        for col in range(j + 1, j + 4):
            self.matrix[i + 1][col] = QrBuilder.ZERO
            self.matrix[i + 3][col] = QrBuilder.ZERO
        for row in range(i + 2, i + 3):
            self.matrix[row][j + 1] = QrBuilder.ZERO
            self.matrix[row][j + 3] = QrBuilder.ZERO
        self.matrix[i + 2][j + 2] = QrBuilder.ONE

    def alignment_position(self):
        align_pos = constants.alignment_position[self.qrcode.version]
        # for dark module
        self.matrix[(4 * self.qrcode.version) + 9][8] = QrBuilder.ONE
        if not align_pos:
            return
        # print(align_pos)
        for j in range(1, len(align_pos) - 1):
            self.alignment_pattern(align_pos[0] - 2, align_pos[j] - 2)
        for i in range(1, len(align_pos) - 1):
            for j in range(0, len(align_pos)):
                self.alignment_pattern(align_pos[i] - 2, align_pos[j] - 2)
        for j in range(1, len(align_pos)):
            self.alignment_pattern(align_pos[-1] - 2, align_pos[j] - 2)

    def timing_position(self):
        size = self.size[0]
        for i in range(8, size - 7):
            if i % 2 == 0:
                self.matrix[i][6] = QrBuilder.ONE
                self.matrix[6][i] = QrBuilder.ONE
            else:
                self.matrix[i][6] = QrBuilder.ZERO
                self.matrix[6][i] = QrBuilder.ZERO

    def format_position(self, matrix, mask_number):
        format = constants.format_pattern[self.qrcode.error_corr][mask_number]
        i = 0
        counter1 = 0
        counter2 = 0
        while i <= 6:
            # print(counter1, counter2)
            if format[i] == '0':
                matrix[8][counter1] = QrBuilder.ZERO
                matrix[-counter2 - 1][8] = QrBuilder.ZERO
            else:
                matrix[8][counter1] = QrBuilder.ONE
                matrix[-counter2 - 1][8] = QrBuilder.ONE
            counter1 += 1
            counter2 += 1
            if counter1 == 6:
                counter1 += 1
            i += 1
        counter1 = 8
        counter2 = -8
        while i < 15:
            if format[i] == '0':
                matrix[counter1][8] = QrBuilder.ZERO
                matrix[8][counter2] = QrBuilder.ZERO
            else:
                matrix[counter1][8] = QrBuilder.ONE
                matrix[8][counter2] = QrBuilder.ONE
            counter1 -= 1
            counter2 += 1
            if counter1 == 6:
                counter1 -= 1
            i += 1

    def version_position(self):
        if self.qrcode.version < 7:
            return
        pattern = constants.version_pattern[self.qrcode.version]
        counter = 17
        for i in range(0, 6):
            for j in range(-11, -8):
                if pattern[counter] == '1':
                    self.matrix[i][j] = QrBuilder.ONE
                    self.matrix[j][i] = QrBuilder.ONE
                else:
                    self.matrix[i][j] = QrBuilder.ZERO
                    self.matrix[j][i] = QrBuilder.ZERO
                counter -= 1

    def masking_pattern(self):
        masks = [deepcopy(self.matrix) for i in range(8)]
        for i in range(8):
            self.format_position(masks[i], i)
            self.fill_data(masks[i], self.data, i)
        return masks

    def mask_score(self, mask):
        score = [0, 0, 0, 0]
        current = mask[0][0]
        # counter = 0
        total = 0
        # for consecutive vertical and horizontal bits
        for i in range(0, len(mask)):
            counter = 0
            for j in range(0, len(mask)):
                pixel = mask[i][j]

                if pixel == current:
                    counter += 1
                else:
                    if counter >= 5:
                        total += (counter - 5) + 3
                    counter = 1
                    current = pixel
            if counter >= 5:
                total += (counter - 5) + 3

        for j in range(0, len(mask)):
            counter = 0
            for i in range(0, len(mask)):
                pixel = mask[i][j]

                if pixel == current:
                    counter += 1
                else:
                    if counter >= 5:
                        total += (counter - 5) + 3
                    counter = 1
                    current = pixel
            if counter >= 5:
                total += (counter - 5) + 3

        score[0] = total

        # Rule 2
        counter = 0
        for i in range(len(mask) - 1):
            for j in range(len(mask) - 1):
                if mask[i][j] == mask[i + 1][j] and mask[i][j] == mask[i + 1][j + 1] and mask[i][j] == mask[i][j + 1]:
                    counter += 1
        score[1] = counter * 3

        # Rule 3
        patterns = [[255, 255, 255, 255, 0, 255, 0, 0, 0, 255, 0],
                    [0, 255, 0, 0, 0, 255, 0, 255, 255, 255, 255]]
        counter = 0
        for i in range(0, len(mask)):
            for j in range(0, len(mask)):
                for pattern in patterns:
                    match = True
                    k = j
                    # for row matches
                    for p in pattern:
                        if k >= len(mask) or mask[i][k] != p:
                            match = False
                            break
                        k += 1
                    if match:
                        counter += 1
                    match = True
                    k = j
                    # for column matches
                    for p in pattern:
                        if k >= len(mask) or mask[k][i] != p:
                            match = False
                            break
                        k += 1
                    if match:
                        counter += 1
        # print(counter)
        score[2] = counter * 40

        # dark_module = 0
        # for i in range(len(mask)):
        #     for j in range(len(mask)):
        #         if mask[i][j] == QrBuilder.ONE:
        #             dark_module += 1
        # Rule 4
        dark_module = sum((1 if j == QrBuilder.ONE else 0 for i in mask for j in i))
        percent = int(dark_module / (len(mask) ** 2) * 100)
        prv = percent - (percent % 5)
        nxt = prv + 5
        prv, nxt = abs(prv - 50) // 10, abs(nxt - 50) // 10
        score[3] = min(prv, nxt) * 10
        return score

    def fill_data(self, matrix, data, mask_number):
        counter = 0
        mask = constants.mask_patterns[mask_number]
        i, j = len(matrix) - 1, len(matrix) - 1
        up = True
        while True:
            # print(i,j)
            if matrix[i][j] == 128:
                if self.data[counter] == '1':
                    matrix[i][j] = QrBuilder.ONE ^ (QrBuilder.ZERO if mask(i, j) else QrBuilder.ONE)
                else:
                    matrix[i][j] = QrBuilder.ZERO ^ (QrBuilder.ZERO if mask(i, j) else QrBuilder.ONE)
                counter += 1
            if counter == len(data):
                break
            if matrix[i][j - 1] == 128:
                if self.data[counter] == '1':
                    matrix[i][j - 1] = QrBuilder.ONE ^ (QrBuilder.ZERO if mask(i, j - 1) else QrBuilder.ONE)
                else:
                    matrix[i][j - 1] = QrBuilder.ZERO ^ (QrBuilder.ZERO if mask(i, j - 1) else QrBuilder.ONE)
                counter += 1
            if counter == len(self.data):
                break
            if up:
                if i == 0:
                    if j - 2 != 6:
                        j -= 2
                    else:
                        j -= 3
                    up = False
                else:
                    i -= 1
            else:
                if i == len(matrix) - 1:
                    j -= 2
                    up = True
                else:
                    i += 1

    def build_image(self, mask_number=None):
        self.finding_position()
        self.alignment_position()
        self.timing_position()
        self.version_position()
        masks = self.masking_pattern()
        if not mask_number:
            mask_scores = [sum(self.mask_score(mask)) for mask in masks]
            mask_number = mask_scores.index(min(mask_scores))
        # for m_s in mask_scores:
        # #     print(m_s)
        pixels = [j for i in masks[mask_number] for j in i]
        # pixels = [j for i in self.matrix for j in i]
        image = Image.new(mode='L', size=self.size)
        image.putdata(pixels)
        image = ImageOps.expand(image, border=4, fill='white')
        image = ImageOps.scale(image, factor=6, resample=Image.Resampling.BOX)
        return image

def PIL_to_dataURL(image):
    data = io.BytesIO()
    image.save(data,"PNG")
    data64 = base64.b64encode(data.getvalue())
    return u'data:image/png;base64,'+data64.decode('utf-8')

# text="https://www.facebook.com/"
# text="ritwick"
# text="हिन्दी"
#
# text = input("Enter PNR:")
text = sys.argv[1]
qr = QrCode(text)
# print(qr)
qrbuilder = QrBuilder(qr)
image = qrbuilder.build_image()
# print(image.size)
# print(image)

text = text.split('/')[-1];
print(PIL_to_dataURL(image),end="")
# image.save(f"{text}.png")
# image.show()


#coding:utf-8

"""
ID:          issue-7446
ISSUE:       https://github.com/FirebirdSQL/firebird/issues/7446
DESCRIPTION:
    Problem was reported privately by firebird user. As a visible result there were core dump and an error in firebird.log:
        Operating system call pthread_mutex_lock failed. Error code 22

    An error happens due to an attempt to cleanup (too late attempt - when processing disconnect in CS)
    savepoint stored in metadata cache. Put attention that savepoints are always created in transaction memory pool and keeping
    them after commit/rollback in metadata cache is bad idea.

NOTES:
    [01.02.2023] pzotov.
    This test checks regression that was introduced by first attempt to solve problem described in the title.
    SQL example was provided by dimitr, see letter 31-jan-2023 13:43. Running SQL script must NOT issue any output.
    There is no similar test in old fbtest QA suite.

    Regression can be reproduced on:
        * FB 3.0.11.33654 (17-jan-2023): "SQLSTATE = 3B000 / Unable to find savepoint with name S in transaction context".
    Checked on:
        3.0.11.33658; 4.0.3.2894; 5.0.0.920 - all fine.
"""

import pytest
import locale
from firebird.qa import *

db = db_factory()
act = python_act('db')

@pytest.mark.version('>=3.0.11')
def test_1(act: Action):

    sql_chk = """
        set term ^;
        create procedure p0 returns (r int)
        as
        begin
           r = 0;
           suspend;
        end^

        create procedure p returns (r int)
        as
        begin
           in autonomous transaction do
           begin
             select p0.r from p0 into :r;
           end

           suspend;
        end^
        set term ;^

        savepoint s;
        set heading off;
        select * from p;
        release savepoint s;
    """
    act.expected_stdout = "0"
    act.isql(switches = ['-q'], input = sql_chk, combine_output = True, io_enc = locale.getpreferredencoding())
    assert act.clean_stdout == act.clean_expected_stdout


# -*- coding: utf-8 -*-
from flask import request, g, jsonify
from scripts.services import comment
from scripts.models.log import ActionType
from . import bp_main as main
# 加日志
from scripts.services import log

@main.route('/Comment/Create', methods=['POST'])
def createIssueComment():
    comment_type = int(request.json['CommentType'])
    object_id = request.json['ObjectId']
    content = request.json['Content']

    comment.createComment(comment_type, object_id, g.user_id, content)
    # ---------加日志-----------
    log.addLog(0, g.nick, ActionType.comment_createComment, content)
    # --------------------------
    return jsonify(createcomment=True)

@main.route('/Comment/Query', methods=['POST'])
def queryIssueComment():
    comment_type = int(request.json['CommentType'])
    object_id = request.json['ObjectId']
    page_no = request.json['PageNo']
    (row_count, page_count, page_no, page_size, data) = comment.queryComment(comment_type, object_id, page_no)
    commentList = []
    for i in data.all():
        commentList.append(
            {'CommentId': i.Comment.CommentId, 'CommentType': i.Comment.CommentType, 'ObjectId': i.Comment.ObjectId,
             'Author': i.Comment.Author, 'AuthorName': i.UserProfile.Nick,
             'CreateTime': i.Comment.CreateTime.strftime('%Y-%m-%d %H:%M:%S'), 'Content': (i.Comment.Content)})
    return jsonify(row_count=row_count, page_count=page_count, page_no=page_no, page_size=page_size,
                   commentList=commentList)


import sys
import os
import json
import requests
import settings

def main():
    text = open(build_input_text_path(), 'r', encoding='UTF-8').read()
    r = get_abstract_text(text)
    for x in r:
        print(x)

def build_input_text_path():
    args = sys.argv
    if len(args) != 2:
        raise ValueError('処理対象ファイルがコマンド引数に指定されていません')
    path = args[1]
    if os.path.isfile(path) != True:
        raise ValueError('処理対象ファイルの指定が誤っています')
    return path

def get_abstract_text(text):
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'x-api-key': settings.asahi_abstract_token
    }

    payload = json.dumps({
        'text': text,
        'rate': settings.asahi_abstract_rate,
        'auto_paragraph': settings.asahi_abstract_auto_paragraph
    }).encode('utf-8')

    r = requests.post(settings.asahi_abstract_url, headers=headers, data=payload)
    r.raise_for_status()
    return r.json()['result']

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


import pygame
import random

pygame.init()

yellow = (255, 255, 102)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

dis_width = 600
dis_height = 400

programIcon = pygame.image.load('snakeIcon.png')
pygame.display.set_icon(programIcon)

dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake game')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 10

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
food_font = pygame.font.SysFont("comicsansms", 20)

def high_score(score):  # Update and Show High Score of all times from txt file
    highScoreFile = open("High Score.txt", "r")
    highScore = highScoreFile.readline()
    if score > int(highScore):
        highScoreFile = open("High Score.txt", "w")
        highScoreFile.write(str(score))
    highScoreFile.close()
    value = score_font.render("High Score of all times: " + str(highScore), True, yellow)
    dis.blit(value, [0, 50])

def your_score(score):  # Show current game score
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])

def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def message(msg,color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg,[dis_width / 6, dis_height / 3])

def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    yummyTextTime = 0
    accelerateSpeed = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:
        while game_close:  # In case of losing check if the player wants another game.
            dis.fill(blue)
            message("Game Over! Press Q-Quit or C-Play Again", red)
            your_score(Length_of_snake - 1)
            high_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():  # Check the event of key pressing.
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:  # Check if the Snake hits the boundaries
            game_close = True

        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])  # Adding the food
        snake_Head = [x1, y1]
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        your_score(Length_of_snake - 1)

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
            yummyTextTime = snake_speed + accelerateSpeed

        if yummyTextTime > 0:
            yummyTextTime -= 1
            value = food_font.render("Yummy..!", True, yellow)
            dis.blit(value, [0, 50])

        pygame.display.update()

        if (Length_of_snake-1).__divmod__(5)[1] == 0:
            accelerateSpeed = ((Length_of_snake - 1) / 5) * 3
        clock.tick(snake_speed + accelerateSpeed)

    pygame.quit()
    quit()

gameLoop()


from __future__ import annotations
from enum import auto
from typing import Optional, TYPE_CHECKING

from base_enum import BaseEnum
from monster_base import MonsterBase
from random_gen import RandomGen
from helpers import get_all_monsters

from data_structures.referential_array import ArrayR
from data_structures.queue_adt import CircularQueue
from data_structures.stack_adt import ArrayStack
from data_structures.array_sorted_list import ArraySortedList
from data_structures.sorted_list_adt import ListItem

if TYPE_CHECKING:
    from battle import Battle

class MonsterTeam:

    class TeamMode(BaseEnum):

        FRONT = auto()
        BACK = auto()
        OPTIMISE = auto()

    class SelectionMode(BaseEnum):

        RANDOM = auto()
        MANUAL = auto()
        PROVIDED = auto()

    class SortMode(BaseEnum):

        HP = auto()
        ATTACK = auto()
        DEFENSE = auto()
        SPEED = auto()
        LEVEL = auto()

    TEAM_LIMIT = 6

    def mapping(self, monster : MonsterBase, sort_mode : SortMode):
        """
        Returns a value which will be used as the key in the ListItem objecct

        :param monster: The monster from which we want to get the value from
        :para sort_mode: The attribute that the monsters will be sorted with reference to

        :complexity: O(1)
        """

        if sort_mode == self.SortMode.HP:
            return monster.get_hp()
        elif sort_mode == self.SortMode.ATTACK:
            return monster.get_attack()
        elif sort_mode == self.SortMode.DEFENSE:
            return monster.get_defense()
        elif sort_mode == self.SortMode.SPEED:
            return monster.get_speed()
        elif sort_mode == self.SortMode.LEVEL:
            return monster.get_level()

    def __init__(self, team_mode: TeamMode, selection_mode, **kwargs) -> None:
        """
        The function initializes a team of monsters based on the team mode and selection mode provided.

        :implementation:
            We use a different data structure for each team mode.
            For the front team mode we use a stack as the monster last added is the one that is retrieved first
            For the back team mode we use a queue here as the monster first added is the one that is retrieved first
            For the optimise team mode we use a sorted list data structure since it is able to sort monsters when they are being added

        :param team_mode: The `team_mode` parameter determines the mode in which the team is organized.
        :param selection_mode: The `selection_mode` parameter determines how the monsters are selected
        for the team.

        :complexity:
        All best cases are considered in the context of using the select provided to create the teams
        All worst cases are considered in the context of using the random generator to create the teams

        FRONT:
                O(n+m) best case
                O(n+ a * m) worst case
        BACK:
                O(n+m) best case
                O(n + a*m) worst case
        OPTIMISE:
                O(n + m) best case
                O(a*n*log(m!))  worst case

        where n is the size of the team,
        a is the number of monsters in the game
        and m is the number of monsters to be added

        """

        self.team_mode = team_mode
        self.lives = 1

        if team_mode == self.TeamMode.FRONT:
            self.team = ArrayStack[MonsterBase](self.TEAM_LIMIT)
        elif team_mode == self.TeamMode.BACK:
            self.team = CircularQueue[MonsterBase](self.TEAM_LIMIT)
        elif team_mode == self.TeamMode.OPTIMISE:
            self.sort_mode = kwargs.get('sort_key')
            self.descending = True
            self.team = ArraySortedList(self.TEAM_LIMIT)
        else:
            raise ValueError(f"team_mode {team_mode} not supported.")

        self.monsters = CircularQueue[MonsterBase](self.TEAM_LIMIT) #Keeping a track of the team for revival.

        if selection_mode == self.SelectionMode.RANDOM:
            self.select_randomly(**kwargs)
        elif selection_mode == self.SelectionMode.MANUAL:
            self.select_manually(**kwargs)
        elif selection_mode == self.SelectionMode.PROVIDED:
            self.select_provided(**kwargs)
        else:
            raise ValueError(f"selection_mode {selection_mode} not supported.")

    def add_to_team(self, monster: MonsterBase):
        """
        Adds a new monster to the team

        :implementation:
            According to which team mode has been chosen, we must change how we add to the team
            since each team mode uses a different data structure.
            For the optimise team mode, we need to additionally check if we need to sort in a descending or ascending order
            since the special for optimise changes the order that must be maintained.

        :param monster: The monster to be added to the team

        :complexity:

        FRONT:
            Best case: O(1)
            Worst case: O(1)
        BACK:
            Best case: O(1)
            Worst case: O(1)
        OPTIMISE:
            Best case: O(log(n))
            Worst case: O(n)

            where n is the number of monsters in the team
        """
        if self.team_mode == self.TeamMode.FRONT:
            self.team.push(monster)
        elif self.team_mode == self.TeamMode.BACK:
            self.team.append(monster)
        elif self.team_mode == self.TeamMode.OPTIMISE:
            self.optimise_add(self.team, monster)

    def optimise_add(self, team : ArraySortedList, monster : MonsterBase) -> None:
        """
        The function optimise_add adds a monster to a team with a specific sorting mode.

        :param team: The "team" parameter is an object representing a team.
        :param monster: The "monster" parameter is an object representing a monster.
        """
        if self.descending:
            item = ListItem(monster, -1 * self.mapping(monster, self.sort_mode))
            team.add(item)
        else:
            item = ListItem(monster, self.mapping(monster, self.sort_mode))
            team.add(item)

    def retrieve_from_team(self) -> MonsterBase:
        """
        The function retrieves a monster object from a team based on the team mode.

        :implementation:
            Based on the team mode, the function will return a monster from the team differently.

        :returns: A monster object
        :complexity:

        FRONT:
            Best case: O(1)
            Worst case: O(1)
        BACK:
            Best case: O(1)
            Worst case: O(1)
        OPTIMISE:
            Best case: O(n)
            Worst case: O(n)

            This is because when an element is deleted, all the elements after that one will need to be shifted to the left.

        where n is the number of monsters in the team
        """
        if self.team_mode == self.TeamMode.FRONT:
            return self.team.pop()
        elif self.team_mode == self.TeamMode.BACK:
            return self.team.serve()
        elif self.team_mode == self.TeamMode.OPTIMISE:
            return self.team.delete_at_index(0).value

    def special(self) -> None:
        """
        The special function rearranges the team based on the selected team mode.

        :implementation:
            Based on which team mode is selected, special will be executed differently.
            FRONT: The first 3 monsters in the team will be appended into a queue and then pushed back onto the stack.
            This will effectively reverse the order of the first 3 monsters in the team
            BACK: The first half of the team will be appended into a queue and the second half will be pushed onto the stack.
            Then the second half of the team will be appended back into the queue and then the first half of the team will be
            appended back into the queue.
            OPTIMISE: The descending boolean flag will be set to its opposite value and then each monster will be reinserted back into
            the team.

        :complexity:
        FRONT:
            Best case: O(1)
            Worst case: O(1)

            The worst case is O(1) since in the long run as the team grows arbitrarily large,
            the largest amount that will need to be reversed is 3 which is a constant
        BACK:
            Best case: O(n)
            Worst case: O(n)
        OPTIMISE:
            Best case: O(nlog(n))
            Worst case: O(n^2)

            The best case occurs when we switch from ascending to descending and the worst case occurs when we switch
            from descending to ascending

        where n is the number of monsters in the team.
        """

        if self.team_mode == self.TeamMode.FRONT:
            temp_team_holder = CircularQueue[MonsterBase](min(3, len(self.team)))
            for _ in range(min(3, len(self.team))):
                temp_team_holder.append(self.team.pop())
            for _ in range(len(temp_team_holder)):
                self.team.push(temp_team_holder.serve())

        elif self.team_mode == self.TeamMode.BACK:
            first_half_size = len(self.team)//2
            first_half_team = CircularQueue[MonsterBase](first_half_size)
            second_half_team = ArrayStack[MonsterBase](len(self.team) - first_half_size)
            for _ in range(first_half_size):
                first_half_team.append(self.team.serve())
            for _ in range(len(self.team)):
                second_half_team.push(self.team.serve())
            for _ in range(len(second_half_team)):
                self.team.append(second_half_team.pop())
            for _ in range(len(first_half_team)):
                self.team.append(first_half_team.serve())

        elif self.team_mode == self.TeamMode.OPTIMISE:
            temp = ArraySortedList[MonsterBase](len(self.team))
            self.descending = not self.descending
            for _ in range(len(self.team)):
                self.optimise_add(temp, self.retrieve_from_team())
            self.team = temp

    def regenerate_team(self) -> None:
        """
        The `regenerate_team` function resets the HP of all monsters in the team and adds them back to
        the team.

        :implementation:
            The team will be reset. This will be done differently depending on which team mode has been selected.
            Then, using the queue which stored all the monsters that were orginally in the team will be readded back into the team.
            They will also will be maintained within the queue so the team can be regenerated again if necessary.

        :complexity:
        FRONT:
            Best case: O(n)
            Worst case: O(n)
        BACK:
            Best case: O(n)
            Worst case: O(n)
        OPTIMISE:
            Best case: O(n)
            Worst case: O(nlog(n!))

        where n is the number of monsters.
        """

        if self.team_mode == self.TeamMode.FRONT or self.team_mode == self.TeamMode.BACK:
            self.team.clear()

        elif self.team_mode == self.TeamMode.OPTIMISE:
            self.team.reset()
            self.descending = True

        for _ in range(len(self.monsters)):
                monster = self.monsters.serve()
                monster.set_hp(monster.get_max_hp())
                self.add_to_team(monster)
                self.monsters.append(monster)

    def __len__(self):
        return len(self.team)

    def select_randomly(self):
        """"
        Creates a random team of monsters

        :complexity:
        Best case: O(m*n)
        Worst Case: O(m*n)

        where m is the number of monsters and n is the team size

        """
        team_size = RandomGen.randint(1, self.TEAM_LIMIT)
        monsters = get_all_monsters()
        n_spawnable = 0
        for x in range(len(monsters)):
            if monsters[x].can_be_spawned():
                n_spawnable += 1

        for _ in range(team_size):
            spawner_index = RandomGen.randint(0, n_spawnable-1)
            cur_index = -1
            for x in range(len(monsters)):
                if monsters[x].can_be_spawned():
                    cur_index += 1
                    if cur_index == spawner_index:
                        # Spawn this monster
                        self.add_to_team(monsters[x]())
                        self.monsters.append(monsters[x]())
                        break
            else:
                raise ValueError("Spawning logic failed.")

    def select_manually(self):
        """
        Prompt the user for input on selecting the team.
        Any invalid input should have the code prompt the user again.

        First input: Team size. Single integer
        For _ in range(team size):
            Next input: Prompt selection of a Monster class.
                * Should take a single input, asking for an integer.
                    This integer corresponds to an index (1-indexed) of the helpers method
                    get_all_monsters()
                * If invalid of monster is not spawnable, should ask again.

        Add these monsters to the team in the same order input was provided. Example interaction:

        How many monsters are there? 2
        MONSTERS Are:
        1: Flamikin [✔]
        2: Infernoth [❌]
        3: Infernox [❌]
        4: Aquariuma [✔]
        5: Marititan [❌]
        6: Leviatitan [❌]
        7: Vineon [✔]
        8: Treetower [❌]
        9: Treemendous [❌]
        10: Rockodile [✔]
        11: Stonemountain [❌]
        12: Gustwing [✔]
        13: Stormeagle [❌]
        14: Frostbite [✔]
        15: Blizzarus [❌]
        16: Thundrake [✔]
        17: Thunderdrake [❌]
        18: Shadowcat [✔]
        19: Nightpanther [❌]
        20: Mystifly [✔]
        21: Telekite [❌]
        22: Metalhorn [✔]
        23: Ironclad [❌]
        24: Normake [❌]
        25: Strikeon [✔]
        26: Venomcoil [✔]
        27: Pythondra [✔]
        28: Constriclaw [✔]print
        33: Leafadder [✔]
        34: Iceviper [✔]
        35: Rockpython [✔]
        36: Soundcobra [✔]
        37: Psychosnake [✔]
        38: Groundviper [✔]
        39: Faeboa [✔]
        40: Bugrattler [✔]
        41: Darkadder [✔]
        Which monster are you spawning? 38
        MONSTERS Are:
        1: Flamikin [✔]
        2: Infernoth [❌]
        3: Infernox [❌]
        4: Aquariuma [✔]
        5: Marititan [❌]
        6: Leviatitan [❌]
        7: Vineon [✔]
        8: Treetower [❌]
        9: Treemendous [❌]
        10: Rockodile [✔]
        11: Stonemountain [❌]
        12: Gustwing [✔]
        13: Stormeagle [❌]
        14: Frostbite [✔]
        15: Blizzarus [❌]
        16: Thundrake [✔]
        17: Thunderdrake [❌]
        18: Shadowcat [✔]
        19: Nightpanther [❌]
        20: Mystifly [✔]
        21: Telekite [❌]
        22: Metalhorn [✔]
        23: Ironclad [❌]
        24: Normake [❌]
        25: Strikeon [✔]()
        27: Pythondra [✔]
        28: Constriclaw [✔]
        29: Shockserpent [✔]
        30: Driftsnake [✔]
        31: Aquanake [✔]
        32: Flameserpent [✔]
        33: Leafadder [✔]
        34: Iceviper [✔]
        35: Rockpython [✔]
        36: Soundcobra [✔]
        37: Psychosnake [✔]
        38: Groundviper [✔]
        39: Faeboa [✔]
        40: Bugrattler [✔]
        41: Darkadder [✔]
        Which monster are you spawning? 2
        This monster cannot be spawned.
        Which monster are you spawning? 1

        :complexity: O(n) in both best/worst case where n is the number of monsters to be spawned
        """
        while True:
            try:
                team_size = int(input("How many monsters are there (pick between 1 and 6): "))
                if 1 <= team_size <= self.TEAM_LIMIT:
                    break
                print("Please enter a number between 1 and 6.")
            except ValueError:
                print("Please enter a number. It must be between 1 and 6.")
        monsters = get_all_monsters()
        while team_size > 0:
            try:
                monster_index = int(input("Enter the index of the monster you would like on your team (between 1 and 41): "))
                if 1 <= monster_index <= 41 and monsters[monster_index - 1].can_be_spawned():
                    self.add_to_team(monsters[monster_index- 1]())
                    self.monsters.append(monsters[monster_index- 1]())
                    team_size -= 1
                else:
                    print("Sorry, a monster with that index does not exist or cannot be spawned. Please enter another monster index between 1 and 41.")
            except ValueError:
                print("Sorry, please enter a number. It must be between 1 and 41")

    def select_provided(self, provided_monsters:Optional[ArrayR[type[MonsterBase]]]=None, **kwargs):
        """
        Generates a team based on a list of already provided monster classes.

        While the type hint imples the argument can be none, this method should never be None

        :complexity: O(n) in both best/worst case where n is the number of monsters provided

        Example team if in TeamMode.FRONT:
        [Gustwing Instance, Aquariuma Instance, Flamikin Instance]
        """
        for monster in provided_monsters:
            if monster.can_be_spawned() and not self.team.is_full():
                self.add_to_team(monster())
                self.monsters.append(monster())
            else:
                raise ValueError("Too many monsters or a monster cannot be spawned")

    def choose_action(self, currently_out: MonsterBase, enemy: MonsterBase) -> Battle.Action:
        # This is just a placeholder function that doesn't matter much for testing.
        from battle import Battle
        if currently_out.get_speed() >= enemy.get_speed() or currently_out.get_hp() >= enemy.get_hp():
            return Battle.Action.ATTACK
        if self.team.is_empty():
            return Battle.Action.ATTACK
        return Battle.Action.SWAP


import pygame
import random
import sys
import time

usage = """\
rmd [reminder_text] [remind_me_in] [time_unit]
available time units are 's', 'm' and 'h', 's' is default
(press enter to exit) """

try:
    text = sys.argv[1]
    seconds = int(sys.argv[2])
except IndexError:
    input(usage)
    sys.exit(0)
try:
    unit = sys.argv[3]
except IndexError:
    unit = 's'

if unit == 'm':
    seconds *= 60
elif unit == 'h':
    seconds *= 3600

for _ in range(seconds):
    time.sleep(1)

pygame.init()
display_info = pygame.display.Info()
W, H = display_info.current_w, display_info.current_h
DISPLAY = pygame.display.set_mode((W, H), pygame.FULLSCREEN)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 50, 50)
GREEN = (50, 255, 50)
BLUE = (50, 50, 255)
YELLOW = (255, 255, 50)
MAGENTA = (255, 50, 255)
CYAN = (50, 255, 255)
COLORS = [RED, GREEN, BLUE, YELLOW, MAGENTA, CYAN]
random.shuffle(COLORS)

CLOCK = pygame.time.Clock()
FPS = 2

font_size = W // (len(text) + 1)
font = pygame.font.SysFont('times', font_size, True)
text_surf = font.render(text, True, BLACK)
text_rect = text_surf.get_rect()
text_rect.center = (W//2, H//2)

i = 0
Quit = False
while not Quit:

    DISPLAY.fill(COLORS[i % len(COLORS)])
    DISPLAY.blit(text_surf, text_rect)
    pygame.display.update()

    i += 1
    CLOCK.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                Quit = True
        if event.type == pygame.QUIT:
            Quit = True

pygame.quit()
sys.exit()


import os

import click

from kubeb.kubeb import Kubeb
from kubeb import __version__

@click.group()
@click.version_option(__version__)
def cli():
    pass

@cli.command()
@click.option('--name', '-n',
              default=lambda: os.path.basename(os.getcwd()),
              prompt='Release name',
              help='Release name.')
@click.option('--user', '-u',
              default=lambda: os.environ.get('USER', ''),
              prompt='Maintainer name',
              help='Maintainer name.')
@click.option('--template', '-t',
              default='laravel|podder-pipeline|podder-task-bean',
              prompt='Release template',
              help='Release template name.')
@click.option('--image',
              default=lambda: os.environ.get('USER', '') + '/' + os.path.basename(os.getcwd()),
              prompt='Docker image name',
              help='Docker image name.')
@click.option('--env',
              default='local',
              prompt='Environment name',
              help='Environment name.')
@click.option('--force',
              is_flag=True,
              help='Overwrite config file.')
def init(name, user, template, image, env, force):
    """ Init kubeb configuration
        Generate config, script files
    """
    Kubeb().initiate(name, user, template, image, env, force)

@cli.command()
def info():
    """ Show current configuration
    """
    Kubeb().info()

@cli.command()
@click.option('--message', '-m',
              multiple=True,
              help='Release note')
@click.option('--push',
              is_flag=True,
              default=False)
def build(message, push):
    """ Build current application
        Build Dockerfile image
        Add release note, tag to config file
    """
    Kubeb().build(message, push)

@cli.command()
@click.option('--version', '-v',
              help='Push version.')
def push(version):
    """ Push docker image to registry
    """
    Kubeb().push(version)

@cli.command()
@click.option('--version', '-v',
              help='Install version.')
@click.option('--set', 'options',
              type=str)
@click.option('--dry-run', 'dry_run',
              is_flag=True,
              default=False)
@click.option('--rollback',
              is_flag=True,
              default=True)
@click.confirmation_option()
def deploy(version, options, dry_run, rollback):
    """ Install current application to Kubernetes
        Generate Helm chart value file with docker image version
        If version is not specified, will get the latest version
    """
    deploy_options = dict()

    if options:
        for item in options.split(','):
            deploy_options.update([item.split('=')])

    Kubeb().deploy(version, deploy_options, dry_run, rollback)

@cli.command()
@click.confirmation_option()
def delete():
    """Uninstall current application from Kubernetes
    """
    Kubeb().delete()

@cli.command()
def version():
    Kubeb().version()

@cli.command()
def history():
    """Show current application deploy history
    """
    Kubeb().history()

@cli.command()
@click.argument('revision',
                default=0,
                type=int)
@click.confirmation_option()
def rollback(revision):
    """Rollback application to revision
        revision=0 is rollback to previous version
    """
    Kubeb().rollback(revision)

@cli.command()
@click.argument('env',
                default='local',
                type=str)
def env(env):
    """Use environment
        Example: kubeb env develop to use environment develop
    """
    Kubeb().env(env)

@cli.command()
@click.argument('variables',
                nargs=-1)
def setenv(variables):
    """Use environment
       Example: kubeb env develop to use environment develop
    """
    env_vars = dict()
    for item in variables:
        env_vars.update([item.split('=')])
    Kubeb().setenv(env_vars)

@cli.command()
@click.argument('name', required=True,
                default="sample",
                type=str)
@click.argument('path', required=True,
                default=".",
                type=click.Path(resolve_path=True))
@click.option('--force',
              is_flag=True,
              help='Overwrite template file.')
def template(name, path, force):
    """Add user template
        kubeb [template_name] [template_directory_path]
        Example: kubeb template example ./example
        Will add template to external template directory: ~/.kubeb/ext-templates/[template_name]
    """
    Kubeb().template(name, path, force)

@cli.command()
@click.confirmation_option()
def destroy():
    """Remove all kubeb configuration
    """
    Kubeb().destroy()


import healpy as hp
import numpy as n
import sys
import matplotlib.pyplot as plt

c=3.e8
f=137.5e6
lamb = c/f
h=0.3
vmin=-10

# Hertzian Dipole model
nsides = 8
npixels = hp.nside2npix(nsides)
thetas,phis = hp.pix2ang(nsides,n.arange(npixels))
hpower = (1-n.sin(thetas)**2*n.cos(phis)**2)*n.sin(2*n.pi*h*n.cos(thetas)/lamb)**2
hpower = 10*n.log10(hpower)-100*(thetas>n.pi/2)
hpower -= hpower.max()
hp.mollview(hpower,rot=[0,90,0],cmap='gnuplot',min=vmin,unit='dB',title=r'Hertzian Dipole Model')

#infile = sys.argv[1]
infile = 'new_ref_dipole_model_137_31july2015.txt'
#infile = 'ff137_5_xpol.txt'
rawdata = n.genfromtxt(infile,dtype='float',skip_header=3,usecols=(0,1,2))
thetas = rawdata[:,0]
phis = rawdata[:,1]
thetas = thetas*n.pi/180.
phis = phis*n.pi/180.
hpower = n.zeros(npixels)
pixInd = hp.ang2pix(nsides,thetas,phis)
hpower[pixInd] = rawdata[n.arange(len(thetas)),2]
hpower = hpower - hpower.max()
hp.mollview(hpower,rot=[0,90,0],cmap='gnuplot',title=infile+' Model',unit='dB',format='%d',min=vmin)
plt.show()


def getLinear(values) :
    i = 0
    final = []
    j = values[i]
    aux = []
    comp = 0
    while i < (len(values)-1) :
        if(checkDist(j,values[i+1])) :
            aux.append(values[i+1])
        else:
            if(len(aux)>30) :
                final.append(aux)
            comp +=len(aux)
            aux = []
            j = values[i]
        i+=1
    if(len(aux)>30) :
        final.append(aux)
    else:
        comp +=len(aux)
    return (final,comp)

def checkDist(ref, todo) :
    return (not (todo[0]>(ref[0] + (ref[0]*2)/100) or todo[0] <(ref[0] - (ref[0]*2)/100))) and (not (todo[3]>(ref[3] + (ref[3]*2)/100) or todo[3] <(ref[3] - (ref[3]*2)/100)))