# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 23:00:33 2018

@author: taishi-o
"""

import sys
import numpy as np
import cv2

#------------------
# Load images
#------------------
file = "./picture/asobi_asobase11/"
sketchnum = np.arange(678,694,1)
infnum = np.arange(0, 16, 1)

#------------------
# Define functions
#------------------
def myFillImages(src):
    dst = np.array(src)

    # Mask
    h, w = dst.shape[:2]
    mask = np.zeros((h, w), dtype=np.uint8)
    mask_for_fill = np.zeros((h+2, w+2), dtype=np.uint8)
    mask[src==0] = 1 # 1: Done, 0: Undone

    # Fill
    label = 1
    for i in range(h):
        for j in range(w):
            if mask[i, j] == 0: # If undone
                cv2.floodFill(
                        dst, mask_for_fill, (j,i), label)
                mask[mask_for_fill[1:1+h, 1:1+w]==1] = 1
                label += 1

                if np.sum(mask==0) == 0:
                    break

                if label >= 255:
                    print("label becomes larger than 255!!")
                    sys.exit()

    return label, dst

def spreadColor(src, fill, label):
    dst = np.array(src)

    for labelnum in range(label):
        med_B = np.median(src[:,:,0][fill==labelnum])
        med_G = np.median(src[:,:,1][fill==labelnum])
        med_R = np.median(src[:,:,2][fill==labelnum])

        dst[:,:,0][fill==labelnum] = med_B
        dst[:,:,1][fill==labelnum] = med_G
        dst[:,:,2][fill==labelnum] = med_R

    return dst

def combineSketchInfSpread(spread, inference, sketch, thresh):
    dst = np.array(spread)

    dst[:,:,0][thresh==0] = inference[:,:,0][thresh==0]
    dst[:,:,1][thresh==0] = inference[:,:,1][thresh==0]
    dst[:,:,2][thresh==0] = inference[:,:,2][thresh==0]

    dst = dst.astype(np.float32)
    sketch = sketch.astype(np.float32)

    sketch_inv = 255 - sketch
    dst[:,:,0] -= sketch_inv
    dst[:,:,1] -= sketch_inv
    dst[:,:,2] -= sketch_inv

    dst = np.clip(dst, 0, 255).astype(np.uint8)

    return dst

#------------------
# Main
#------------------
for imgnum in range(sketchnum.shape[0]):
    sketch = cv2.imread(file + "sketch/{:06d}.png".format(
            sketchnum[imgnum]), -1)
    inference = cv2.imread("./inference_{:03d}.png".format(
            infnum[imgnum]), -1)
    # Threshold sketch img
    ret, thresh = cv2.threshold(sketch, 240, 255, cv2.THRESH_BINARY)
    # Fill
    label, fill = myFillImages(thresh)
    # Spread
    spread = spreadColor(inference, fill, label)
    # Combine with inference
    result = combineSketchInfSpread(spread, inference, sketch, thresh)

    # Save
    cv2.imwrite("test{:03d}.png".format(imgnum), result)


import sys
import cv2
from scipy.misc import imread
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt

class Formatter(object):
    def __init__(self, im):
        self.im = im
    def __call__(self, x, y):
        z = self.im.get_array()[int(y), int(x)]
        return 'x={:.01f}, y={:.01f}, z={}'.format(x, y, z)
try:
    from tkinter import Tk
    from tkinter.filedialog import askopenfilename
    root = Tk()
    root.withdraw()
    fname = askopenfilename()
    root.destroy()
except:
    fname = sys.argv[1]

# img = imread(fname, 'F')
img = cv2.imread(fname, cv2.IMREAD_UNCHANGED)
print('img has shape and dtype:', img.shape, img.dtype)

fig, ax = plt.subplots()
im = ax.imshow(img, interpolation='none')
ax.format_coord = Formatter(im)
plt.show()


from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import update
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

# il

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    title = db.Column(db.String(100), nullable=False)
    date_created = db.Column(
        db.DateTime, default=datetime.now().date())
    description = db.Column(db.String(250), unique=False)
    phone = db.Column(db.String(12), unique=False, default="")
    email = db.Column(db.String(100), unique=False, default="")
    going = db.Column(db.Integer, unique=False, default=0)
    comments = db.Column(db.String(1000), unique=False, default="")

    def __init__(self, name, title, date_created,  description, phone, email, going, comments):
        self.name = name
        self.title = title
        self.date_created = date_created
        self.description = description
        self.phone = phone
        self.email = email
        self.going = going
        self.comments = comments

    def __repr__(self):
        return '<User %r>' % self.name

@app.route('/', methods=['POST', 'GET'])
def home():
    if request.method == 'POST':
        name = request.form['name']
        title = request.form['title']
        description = request.form['description']
        phone = request.form['phone']
        email = request.form['email']

        p1 = Post(name, title, datetime.now().date(),
                  description, phone, email, 0, "")

        try:
            db.session.add(p1)
            db.session.commit()
            return redirect('/')
        except:
            return 'there was an issue adding'
    else:
        post_list = Post.query.order_by(Post.date_created.desc()).all()
        return render_template('home.html', posts=post_list)

@app.route('/about')
def about():
    return render_template('about.html', title='about')

@app.route('/<user_id>')
def user(user_id):
    person = Post.query.filter_by(id=user_id).first()
    return render_template('user.html', user=person)

@app.route('/posts/<post_id>', methods=['POST', 'GET'])
def post_comments(post_id):

    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        date = str(datetime.now())[0:-10]
        post = Post.query.filter_by(id=post_id).first()
        post.comments += '⠀⠀⠀' + description + ' - ' + \
            name + ', ' + date + '\n\n'
        db.session.commit()
        return render_template('comment.html', post=post)
    else:
        post = Post.query.filter_by(id=post_id).first()
        return render_template('comment.html', post=post)

@app.route('/going/<post_id>')
def going(post_id):
    post = Post.query.filter_by(id=post_id).first()
    post.going += 1
    db.session.commit()
    return redirect('/')

@app.route('/cancelgoing/<post_id>')
def cancel_going(post_id):
    post = Post.query.filter_by(id=post_id).first()
    post.going -= 1
    db.session.commit()
    return redirect('/')

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


import wx

import common
import compat
import config
import misc
from edit_windows import ManagedBase, EditStylesMixin
from tree import Tree
from widget_properties import *
from ChoicesProperty import *

class EditComboBox(ManagedBase, EditStylesMixin):
    """\
    Class to handle wxComboBox objects
    """

    update_widget_style = False

    def __init__(self, name, parent, id, choices, sizer, pos, property_window,
                 show=True):

        # Initialise parent classes
        ManagedBase.__init__(self, name, 'wxComboBox', parent, id, sizer,
                             pos, property_window, show=show)
        EditStylesMixin.__init__(self)

        # initialise instance variables
        self.choices = choices
        if len(choices):
            self.selection = 0
        else:
            self.selection = -1
        if config.preferences.default_border:
            self.border = config.preferences.default_border_size
            self.flag = wx.ALL

        # initialise properties remaining staff
        self.access_functions['choices'] = (self.get_choices, self.set_choices)
        self.access_functions['style'] = (self.get_style, self.set_style)
        self.properties['style'] = CheckListProperty(
            self, 'style', self.widget_writer)
        self.properties['choices'] = ChoicesProperty(self, 'choices', None,
                                                     [('Label',
                                                       GridProperty.STRING)],
                                                     len(choices), label=_("choices"))
        self.access_functions['selection'] = (self.get_selection,
                                              self.set_selection)
        self.choices = list(choices)
        self.properties['selection'] = SpinProperty(self, 'selection', None,
                                                    r=(0, len(choices)-1), label=_("selection"))

    def create_widget(self):
        self.widget = wx.ComboBox(self.parent.widget, self.id,
                                 choices=self.choices)
        self.set_selection(self.selection)
        wx.EVT_LEFT_DOWN(self.widget, self.on_set_focus)

    def create_properties(self):
        ManagedBase.create_properties(self)
        panel = wx.Panel(self.notebook, -1)
        szr = wx.BoxSizer(wx.VERTICAL)
        self.properties['choices'].display(panel)
        self.properties['style'].display(panel)
        self.properties['selection'].display(panel)
        szr.Add(self.properties['style'].panel, 0, wx.EXPAND)
        szr.Add(self.properties['selection'].panel, 0, wx.EXPAND)
        szr.Add(self.properties['choices'].panel, 1, wx.EXPAND)
        panel.SetAutoLayout(True)
        compat.SizerItem_SetSizer(panel, szr)
        szr.Fit(panel)
        self.notebook.AddPage(panel, 'Widget')
        self.properties['choices'].set_col_sizes([-1])

    def get_selection(self):
        return self.selection

    def set_selection(self, value):
        value = int(value)
        if self.selection != value:
            self.selection = value
            if self.widget:
                self.widget.SetSelection(value)

    def get_choices(self):
        return zip(self.choices)

    def set_choices(self, values):
        self.choices = [ misc.wxstr(v[0]) for v in values ]
        self.properties['selection'].set_range(0, len(self.choices)-1)
        if self.widget:
            self.widget.Clear()
            for c in self.choices:
                self.widget.Append(c)
            if not self.properties['size'].is_active():
                self.sizer.set_item(self.pos, size=self.widget.GetBestSize())

    def get_property_handler(self, prop_name):
        if prop_name == 'choices':
            return ChoicesHandler(self)
        return ManagedBase.get_property_handler(self, prop_name)

# end of class EditComboBox

def builder(parent, sizer, pos, number=[1]):
    """\
    factory function for EditComboBox objects.
    """
    name = 'combo_box_%d' % number[0]
    while common.app_tree.has_name(name):
        number[0] += 1
        name = 'combo_box_%d' % number[0]
    choice = EditComboBox(name, parent, wx.NewId(),
                          [], sizer, pos, common.property_panel)
    node = Tree.Node(choice)
#    sizer.set_item(pos, size=choice.GetBestSize())
    choice.node = node
    choice.show_widget(True)
    common.app_tree.insert(node, sizer.node, pos - 1)

def xml_builder(attrs, parent, sizer, sizeritem, pos=None):
    """\
    factory to build EditComboBox objects from a XML file
    """
    from xml_parse import XmlParsingError
    try:
        name = attrs['name']
    except KeyError:
        raise XmlParsingError(_("'name' attribute missing"))
    if sizer is None or sizeritem is None:
        raise XmlParsingError(_("sizer or sizeritem object cannot be None"))
    choice = EditComboBox(name, parent, wx.NewId(), [], sizer, pos,
                          common.property_panel)
    sizer.set_item(choice.pos, option=sizeritem.option,
                   flag=sizeritem.flag, border=sizeritem.border)
    node = Tree.Node(choice)
    choice.node = node
    if pos is None:
        common.app_tree.add(node, sizer.node)
    else:
        common.app_tree.insert(node, sizer.node, pos - 1)
    return choice

def initialize():
    """\
    initialization function for the module: returns a wxBitmapButton to be
    added to the main palette.
    """
    common.widgets['EditComboBox'] = builder
    common.widgets_from_xml['EditComboBox'] = xml_builder

    return common.make_object_button('EditComboBox', 'combo_box.xpm')


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

__author__ = "苦叶子"

from selenium import webdriver
from selenium.webdriver import ActionChains

if __name__ == "__main__":
    driver = webdriver.Chrome()
    action_chains = ActionChains(driver)
    driver.get("http://www.python.org")

    # 获取About链接元素，并加入动作链
    About = driver.find_element_by_link_text("About")
    action_chains.click_and_hold(About)
    action_chains.pause(2)
    # 使用下列的动作可以释放按下的鼠标
    # action_chains.release()

    # 执行动作链
    action_chains.perform()

    driver.quit()


from django.conf.urls import patterns,url
from qtl import views

urlpatterns = patterns('',
	url(r'^trait/$', views.SearchTraitView, name = 'search_individual_trait'),
	url(r'^check/$', views.MultipleTraitView, name = 'search_multiple_trait'),
	url(r'^graph/$', views.Graphview, name='display_graph'),
	url(r'^godag/$', views.Graphview, name='display_godag'),
	url(r'^output/$', views.OutputDataView, name='display_data'),
	url(r'^storecsv/$', views.StoreCsvView, name='store_csv'),
						)


from collections import deque

class Graph:

    matrix = []
    def __init__(self, goalx, goaly):
        with open('input.txt') as file:
            self.matrix = [[int(digit) for digit in line.split()] for line in file]
        self.goalx = goalx
        self.goaly = goaly
        self.path = False

    def isValid(self, row, col, visited):

        if row == self.goalx and col == self.goaly: #GOAL State Found!
            print ("GOAL STATE FOUND!")
            self.path = True
            return False

        # Stop if goal state is found!
        if self.path == True:
            return False

        if row < 0 or col < 0 or row > 11 or col > 11:
            return False

        if visited[row][col] == True:
            return False

        if self.matrix[row][col] == False:
            return False

        return True

    def DFS(self, x, y, visited):

        global count

        visited[x][y] = True

        print(x, end = ",")
        print(y, end = " ")

        if self.isValid(x-1, y, visited): #Up
            print("UP")
            self.DFS(x-1, y, visited)
        if self.isValid(x, y-1, visited): #Left
            print("LEFT")
            self.DFS(x, y-1, visited)
        if self.isValid(x, y+1, visited): #Right
            print("RIGHT")
            self.DFS(x, y+1, visited)
        if self.isValid(x+1, y, visited): #Down
            print("DOWN")
            self.DFS(x+1, y, visited)
        count = count + 1

    def BFS(self, x, y):

        queue = deque()
        visited = [[ False for i in range(12)] for i in range(12)]
        queue.append((x, y))
        steps = 0

        while queue:
            node = queue.popleft()

            x = node[0]
            y = node[1]
            print(node)

            if (x == self.goalx and y == self.goaly):
                print ("GOAL STATE FOUND!")
                return steps

            if x < 0 or y < 0 or x >= 12 or y >= 12 or visited[x][y] or self.matrix[x][y] == False:
                continue

            visited[x][y] = True;

            queue.append((x-1, y)) #UP
            queue.append((x, y-1)) #LEFT
            queue.append((x, y+1)) #RIGHT
            queue.append((x+1, y)) #DOWN

            steps += 1
        return steps

if __name__ == "__main__":
    goalx = 10
    goaly = 0
    visited = [[ False for i in range(12)] for i in range(12)]

    # Create Graph
    maze = Graph(goalx, goaly)

    count = 0
    startx = 4
    starty = 11

    maze.DFS(startx, starty, visited)

    count = count + 1
    print("Algorithm: DFS, Steps Taken: " + str(count))

    print("----------------------------------------------")

    count = maze.BFS(startx, starty)
    count = count + 1
    print("Algorithm: BFS, Steps Taken: " + str(count))


#!/usr/bin/python

import time
from datetime import datetime
import argparse
import CHIP_IO.GPIO as GPIO
import socket

def doLog(log_msg):
    print("%s: %s" % (datetime.now().strftime("%Y_%d_%m (%a) - %H:%M:%S.%f")[:-3], log_msg))

if __name__ == "__main__":
    '''
    pd_socketServer.py -p port
    '''
    parser = argparse.ArgumentParser(description='open socket on specified port, listen for "go", produce PD signal')
    parser.add_argument('-p',  dest='port', type=int, default=8888, help='port to listen on')

    args = parser.parse_args()

    GPIO.setup("CSID0", GPIO.OUT)
    GPIO.setup("CSID1", GPIO.OUT)
    GPIO.output("CSID0", 0)
    GPIO.output("CSID1", 0)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', args.port))
    s.listen(10)
    doLog('Waiting on port %d' % ( args.port))
    conn, addr = s.accept()
    #doLog('Recieved conn from %s' % (addr))
    doLog('Recieved conn...')

    while True:
        d = conn.recv(10)
        if d[0:2] == 'go':
            doLog("Rcv'd: %s" % (d[:-2]))
            GPIO.output("CSID0", 1)
            GPIO.output("CSID1", 1)
            time.sleep(0.100)
            GPIO.output("CSID0", 0)
            GPIO.output("CSID1", 0)


def vetor_aleatorio(n):
    import random
    v = []
    for i in range(0,n):
        v.append(int(random.randrange(0,100)))
    return v

def arrumar_vetor(vet):
    n = len(vet)
    for i in range(n-1):
        for j in range(i+1,n):
            if(vet[i]>vet[j]):
                aux = vet[i]
                vet[i] = vet[j]
                vet[j] = aux


import myLibrary as Lib
import matplotlib.pyplot as plt

def f(x): return 4/(1+x**2)

a = 0
b = 1

Res = Lib.integ_MonteCarlo(f, a, b, 500, 10, 10)

# For plotting:

x = Res[1]
y = Res[2]

plt.plot(x, y)
plt.title("\u03C0 vs Monte Carlo Integration result")
plt.xlabel("Sample size -->")
plt.ylabel("Integration value -->")

plt.show()


"""myproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

# lets define a view function
#from views import myHomeViewFunction,myAboutUsViewFunction,myContactUsViewFunction
from . import views

urlpatterns = [ # List
    path('letmein/', admin.site.urls,name="adminRoute"),
    #path(routename, viewfunction, kwargs=None, nameOfTheRoute=None)
    path('', views.myHomeViewFunction , name="homeRoute" ),
    path('aboutus/', views.myAboutUsViewFunction , name="aboutUsoute" ),
    path('product/<slug:category>',views.category,name="categoryRoute"),
    path('cart/',views.cart,name="cartRoute"),
    path('detail/',views.detail,name="detailRoute"),
    path('contactus/',views.contact,name="contactRoute"),
    path('login/',views.login,name="loginRoute"),
    path('search/',views.search,name="searchRoute"),
    path('checkout/',views.checkout,name="checkoutRoute"),

]


import math
import os
import random
import re
import sys

def timeConversion(s):

    am_pm = s[-2:]
    time = s[:-2].split(":")
    hours = int(time[0])
    minutes = time[1]
    seconds = time[2]

    if (am_pm == 'PM'):
        hours = hours + 12

    if (hours % 12 == 0):
        hours -= 12

    military_time = str(hours).zfill(2) + ":" + minutes + ":" + seconds

    return military_time

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    fptr.write(result + '\n')

    fptr.close()


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

from retry import retry

@retry(ZeroDivisionError, tries=3, delay=1, max_delay=5, backoff=2, jitter=(0, 3))
def bar():
    """如果抛了ZeroDivisionError, 重试3次,每次延迟2秒,最大延迟5秒,每次异常,延迟时间乘以2,每次延迟加上0到3中间的随机秒

    如果还是抛错,将异常抛出"""

    res = 2 / 0
    return res

if __name__ == '__main__':
    import logging

    logging.basicConfig()
    bar()


from functools import wraps

def cache(func):
    @wraps(func)
    def wrapper(n):
        log_key = n
        if log_key not in wrapper.log:
            wrapper.log[log_key] = func(n)
        return wrapper.log[log_key]
    wrapper.log = {}
    return wrapper

@cache
def fibonacci(n):
    if n < 2:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(7)
print(fibonacci.log)
fibonacci(4)
print(fibonacci.log)


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

results = []

with open('/MapReduce/ejercicio1/output/ejercicio1_output.txt') as file:
    for line in file:
        station, station_t_max, station_t_min = line.strip().split('\t')
        results.append((station, float(station_t_max), float(station_t_min)))

max_temp = max(results, key=lambda x: x[1])[1]
min_temp = min(results, key=lambda x: x[2])[2]

max_stations = [station for station, temp_max,
                _ in results if temp_max == max_temp]

min_stations = [station for station, _,
                temp_min in results if temp_min == min_temp]

print('Temperatura máxima: %s en %s' % (max_temp, max_stations))
print('Temperatura mínima: %s en %s' % (min_temp, min_stations))


from pyrogram import Client, filters, errors
from time import sleep
import re

app = Client("my_account")

def dynamic_data_filter(data):
    return filters.create(
        lambda flt, _, query: flt.data == query.data,
        data=data  # "data" kwarg is accessed with "flt.data" above
    )

@app.on_message(filters.command("type", prefixes='.') & filters.me)
def type(_, msg):
    orig_text = msg.text.split(".type ", maxsplit=1)[1]
    text = orig_text
    tbp = ''
    chat_id, message_id = msg['chat']['id'], msg['message_id']
    typing_symbol = '▒'
    while(tbp != orig_text):
        try:
            app.edit_message_text(chat_id, message_id, f'{tbp + typing_symbol}', parse_mode='html')
            sleep(0.15)

            tbp = tbp + str(text)[0]
            text = text[1:]

            app.edit_message_text(chat_id, message_id, f'{tbp}', parse_mode='html')
            sleep(0.15)
        except errors.FloodWait as e:
            sleep(e.x)

@app.on_message(filters.command("b", prefixes='.') & filters.me)
def bold(_, msg):
    orig_text = re.split(".B |.b ", msg.text, maxsplit=1)[1]
    chat_id, message_id = msg['chat']['id'], msg['message_id']
    app.edit_message_text(chat_id, message_id, f'{orig_text}', parse_mode='html')

@app.on_message(filters.command("i", prefixes='.') & filters.me)
def italic(_, msg):
    orig_text = re.split(".I |.i ", msg.text, maxsplit=1)[1]
    chat_id, message_id = msg['chat']['id'], msg['message_id']
    app.edit_message_text(chat_id, message_id, f'{orig_text}', parse_mode='html')

@app.on_message(filters.command("bi", prefixes='.') & filters.me)
def bold_and_italic(_, msg):
    orig_text = re.split(".Bi |.bi ", msg.text, maxsplit=1)[1]
    chat_id, message_id = msg['chat']['id'], msg['message_id']
    app.edit_message_text(chat_id, message_id, f'{orig_text}', parse_mode='html')

@app.on_message(filters.command("wave", prefixes='.') & filters.me)
def wave(_, msg):
    orig_text = msg.text.split(".wave", maxsplit=1)[1]
    text = orig_text.lower()
    tbp = text
    for j in range(5):
        for i in range(0, len(text)):
            try:
                msg.edit(tbp[:i] + tbp[i].upper() + tbp[i + 1:])
                sleep(0.1)
            except errors.FloodWait as e:
                sleep(e.x)
        if tbp != tbp.lower():
            msg.edit(tbp.lower())

@app.on_message(filters.command("Я гуль", prefixes='') & filters.me)
def zxc(_, msg):
    a = 1000
    contacts = app.get_contacts()
#    print(contacts)
    while a > 0:
        try:
            app.send_message(msg["chat"]["id"], f"{a} - 7 = {a - 7}", parse_mode="html")
            a -= 7
        except errors.FloodWait as e:
            sleep(e.x)
    app.send_message(msg["chat"]["id"], "let me die", parse_mode="html")

app.run()


import asyncio
import httpx

async def log_request(request):
        print(f"Request: {request.method} {request.url}")

async def log_response(respose):
    request = respose.request
    print(f"Response: {request.method} {request.url} - Status {respose.status_code}")

async def get_episode(ep_id: int):
    async with httpx.AsyncClient(event_hooks={'request': [log_request], 'response':[log_response]}) as client:
        r = await client.get(f'https://rickandmortyapi.com/api/episode/{ep_id}')
        results.append(r.json())
        return

async def main():
    tasks = []
    for ep_id in range(1,11):
        tasks.append(get_episode(ep_id))
    await asyncio.gather(*tasks)

results = []
asyncio.run(main())

print(len(results))


import cv2
import numpy as np

from utils import get_four_points

image = cv2.imread('data/images/book1.jpg')

# cv2.imshow('Original', image)

# image 좌표 4곳
# 시계방향으로 찍을 것
# 좌표만 알아내고 주석처리함
# 주석처리 안하고는 좌표찍으면 결과 이미지 나옴
point_src = get_four_points(image)
print(point_src)

# image의 4개의 점은 마우스 클릭으로 해결완료
# point_original = np.array([[318., 256.],[535., 374.],[318., 669.],[ 74., 475.]])
point_dst = np.array([[0, 0], [300, 0], [300, 400], [0, 400]])
# image_dst의 4개의 점은 우리가 구할것
# 행렬 구하기
matrix, status = cv2.findHomography(point_src, point_dst)
# 변환함수를 통해 이미지를 가져올 것
# 새로운 이미지의 사이즈는 x=400, y=300
result = cv2.warpPerspective(src = image, M = matrix, dsize = (300, 400))

cv2.imshow('result', result)

cv2.waitKey(0)
cv2.destroyAllWindows()


import glob
import numpy as np

indir = '/Users/mike_e_dubs/MWA/INS/Long_Run/All/metadata'
lr_list_path = '/Users/mike_e_dubs/python_stuff/MJW-MWA/Obs_Lists'
obslist = glob.glob('%s/*lst_array*' % (indir))
L = len(indir) + 1
obslist = [path[L:L + 10] for path in obslist]
print(len(obslist))
with open('%s/Long_Run_8s_Autos_OBSIDS.txt' % lr_list_path) as f:
    lr_list = f.read().split("\n")
lr_list.remove('')
print(len(lr_list))
print(len(np.unique(lr_list)))
final_list = [obs for obs in lr_list if obs not in obslist]
print(len(final_list))
g = open('%s/Long_Run_Missed_Obs.txt' % lr_list_path, 'w')
for obs in final_list:
    g.write('%s\n' % obs)


import math
import random
from DecisionNode import DecisionNode
from utilities import ImportData

def mostFreqClass(dataset):
    valueFreq = {}

    for row in dataset:
        c = row[-1]
        if c in valueFreq.keys():
            valueFreq[c] += 1
        else:
            valueFreq[c] = 1

    mfc = ""
    maxFreq = 0

    for k in valueFreq.keys():
        if valueFreq[k] > maxFreq:
            maxFreq = valueFreq[k]
            mfc = k

    return mfc

def bestAttribute(attributes, dataset):
    best = attributes[0]
    maxInfGain = 0

    for attr in attributes:
        currInfGain = calculateInfGain(attr, dataset)
        if currInfGain > maxInfGain:
            maxInfGain = currInfGain
            best = attr

    return best

def calculateEntropy2(dataset):
    valueFreq = {}
    entropy = 0.0

    for row in dataset:
        if row[-1] in valueFreq.keys():
            valueFreq[row[-1]] += 1
        else:
            valueFreq[row[-1]] = 1

    for f in valueFreq.values():
        fi = f / len(dataset)
        entropy -= fi * math.log(fi, math.e)

    return entropy

def calculateInfGain(attrIndex, dataset):
    datasetEntropy = calculateEntropy2(dataset)

    attrValueFreq = {}
    attrEntropy = 0.0

    for row in dataset:
        if row[attrIndex] in attrValueFreq.keys():
            attrValueFreq[row[attrIndex]] += 1
        else:
            attrValueFreq[row[attrIndex]] = 1

    for attr in attrValueFreq.keys():
        subset = splitForEntropy(attrIndex, attr, dataset)
        attrEntropy += float(attrValueFreq[attr] / len(dataset) * calculateEntropy2(subset))

    return datasetEntropy - attrEntropy

def splitForEntropy(attrIndex, attrVal, dataset):
    newDataset = []

    for row in dataset:
        if row[attrIndex] == attrVal:
            subset = row
            newDataset.append(subset)

    return newDataset

def dataset_slice(attrIndex, attrVal, dataset):
    newDataset = []

    for record in dataset:
        if record[attrIndex] == attrVal:
            newDataset.append(record)

    return newDataset

def ID3(attributes: list, dataset: list, parentDecision, parentNode: DecisionNode):
    classes = []
    for record in dataset:
        classes.append(record[-1])

    if classes.count(classes[0]) == len(classes):
        return DecisionNode.createLeaf(classes[0], parentDecision, parentNode)

    if len(attributes) == 0:
        majorityClass = mostFreqClass(dataset)
        return DecisionNode.createLeaf(majorityClass, parentDecision, parentNode)

    bestSplitAttribute = bestAttribute(attributes, dataset)
    attributes.remove(bestSplitAttribute)

    decisionNode = DecisionNode.createDecision(bestSplitAttribute, parentDecision, parentNode)

    attributeValues = set()

    for record in dataset:
        attrVal = record[bestSplitAttribute]
        attributeValues.add(attrVal)
        if len(attributes) == 5:
            break

    for val in attributeValues:
        subDataSet = dataset_slice(bestSplitAttribute, val, dataset)
        decisionNode.children[val] = ID3(attributes.copy(), subDataSet, val, decisionNode)

    return decisionNode

def predict(root: DecisionNode, attributeValues):
    if root is None:
        return random.randint(0, 1)

    if root.isLeaf:
        return root.classValue

    decisionAttr = root.attributeNumber

    currAttrValue = attributeValues[decisionAttr]

    return predict(root.children[currAttrValue], attributeValues)

def small_test():
    dataset2 = [[1, 1, 2, 0, 0], [2, 1, 4, 1, 1], [2, 2, 2, 2, 0], [2, 2, 0, 3, 1], [2, 3, 1, 4, 1],
                [1, 4, 0, 2, 1], [1, 1, 4, 3, 0], [1, 1, 1, 4, 1], [3, 1, 0, 1, 1], [4, 3, 0, 0, 0],
                [3, 2, 1, 4, 0], [4, 0, 2, 3, 1], [3, 4, 3, 2, 0], [4, 0, 4, 1, 0], [1, 2, 4, 0, 1]]

    attributes2 = [0, 1, 2, 3]

    root = ID3(attributes2, dataset2, None, None)

def test():
    attributes = list(range(54))

    output = ImportData.convert()

    root = ID3(attributes, output, None, None)

    return root


import numpy as np
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from util import io

def baseline_crf(train_percentage, sft, future, embed='none'):
    """
    news day n results in day n+1 price, shift index by 1 position
    :param train_percentage: train test split
    :return: x_train, y_train, x_test, y_test
    """
    if future:
        train = io.read_future_market_v2('gpl')
    else:
        train = io.read_spot_market_v2('gpl')
        train = train.drop(['ncg', 'Tradingday', 'Liefertag'], axis=1)
    train['price'] = train['price'].diff()
    train['price'] = train['price'] > 0
    news = io.load_news(embed)
    train = train.join(news, how='left')
    train['price'] = train['price'].shift(sft)
    train.dropna(inplace=True)

    x_train, x_test, y_train, y_test = train_test_split(train.drop('price', axis=1), train['price'],
                                                        test_size=1 - train_percentage, shuffle=False)
    return x_train, x_test, y_train, y_test

def generate(window, stride, predict_length, future=True, save_scaler=True, train_percentage=0.6, embed=True, is_regress=True, news=True):
    """
    :param window: length of the predict data
    :param stride: stride
    :param predict_length: how much days will be predicted
    :param save_scaler: save scaler to be used later in reference
    :param future: read future or spot market
    :param train_percentage: train test split
    :param embed: embed the news or full text
    :param is_regress: False if classification
    :return: x_train, y_train, x_test, y_test
    """
    if future:
        train = io.read_future_market_v2('gpl')
    else:
        train = io.read_spot_market_v2('gpl')
    if news:
        news = io.load_news(embed)
    else:
        news = io.load_events()
    # the training label, don't scale
    original_price = np.array(train.values).squeeze()
    if is_regress:
        y = np.array(
            [original_price[i:i + predict_length] for i in range(window, len(original_price) - predict_length, stride)])
    else:
        original_price = original_price[predict_length:] - original_price[0:-predict_length]
        y = np.array([original_price[i] for i in range(window, len(original_price) - predict_length, stride)])

    # do not scale one hot encoding for now, scale later and see if things change, try to explain, gives out the source
    # is data rich enough to form a triplet or knowledge graph, (also for linked news)
    future_price_scaler = StandardScaler()
    train = train.join(news, how='left')
    train.fillna(0, inplace=True)
    split = int(len(train) * train_percentage)

    train.loc[:split, 'price'] = future_price_scaler.fit_transform(
        train['price'][:split].values.reshape(-1, 1)).squeeze()
    train.loc[split:, 'price'] = future_price_scaler.transform(
        train['price'][split:].values.reshape(-1, 1)).squeeze()

    train = np.array(train)
    # scaled_ = np.concatenate((scaled_, future_price_scaler.transform(train[split:])))
    x = np.array([train[i:i + window] for i in range(0, len(train) - window, stride)])
    if len(x) > len(y):
        x = x[:len(y)]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1 - train_percentage, shuffle=False)

    # how a news has big effect on event long term and short term
    print("Saving scaler")
    if save_scaler:
        joblib.dump(future_price_scaler, 'scaler.pkl')

    print("Saving scaler done")
    return x_train, x_test, y_train, y_test


import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras

# load data files
UFO_complete_df = pd.read_csv('./data/ufo/complete.csv',
                              on_bad_lines='skip',
                              dtype={
                                  'datetime': str,
                                  'city': str,
                                  'state': str,
                                  'country': str,
                                  'shape': str,
                                  'duration (seconds)': str,
                                  'duration (hours/min)': str,
                                  'comments': str,
                                  'date posted': str,
                                  'latitude': str,
                                  'longitude': str,
                                  }
                              )
UFO_scrubbed_df = pd.read_csv('./data/ufo/scrubbed.csv',
                              on_bad_lines='skip',
                              dtype={
                                  'datetime': str,
                                  'city': str,
                                  'state': str,
                                  'country': str,
                                  'shape': str,
                                  'duration (seconds)': str,
                                  'duration (hours/min)': str,
                                  'comments': str,
                                  'date posted': str,
                                  'latitude': str,
                                  'longitude': str,
                                  }
                              )
AAL_df = pd.read_csv('./data/airline_stock/AAL.csv', on_bad_lines='skip')
DAL_df = pd.read_csv('./data/airline_stock/DAL.csv', on_bad_lines='skip')
LUV_df = pd.read_csv('./data/airline_stock/LUV.csv', on_bad_lines='skip')
UAL_df = pd.read_csv('./data/airline_stock/UAL.csv', on_bad_lines='skip')

# variable identification
# print('UFO_complete_df.head', UFO_df.head(), sep="\n")
# print('AAL_df.head', AAL_df.head(), sep="\n")

# count missing value in each column
# print(UFO_complete_df.isna().sum())
# print(UFO_scrubbed_df.isna().sum())

# remove each row which has missing value
UFO_complete_df = UFO_complete_df.dropna()
UFO_scrubbed_df = UFO_scrubbed_df.dropna()
AAL_df = AAL_df.dropna()
DAL_df = DAL_df.dropna()
LUV_df = LUV_df.dropna()
UAL_df = UAL_df.dropna()

# sort dataframe by date format 'yyyy/mm/dd' & remove time element in datetime column
UFO_complete_df = UFO_complete_df.sort_values(by='datetime')
UFO_scrubbed_df = UFO_scrubbed_df.sort_values(by='datetime')

UFO_complete_df['datetime'] = pd.to_datetime(UFO_complete_df['datetime'], errors='coerce', format='%m/%d/%Y %H:%M').dt.date
UFO_scrubbed_df['datetime'] = pd.to_datetime(UFO_scrubbed_df['datetime'], errors='coerce', format='%m/%d/%Y %H:%M').dt.date

UFO_complete_df = UFO_complete_df.dropna(subset=['datetime'])
UFO_scrubbed_df = UFO_scrubbed_df.dropna(subset=['datetime'])

UFO_complete_df['datetime'] = pd.to_datetime(UFO_complete_df['datetime'], format='%Y/%m/%d')
UFO_scrubbed_df['datetime'] = pd.to_datetime(UFO_scrubbed_df['datetime'], format='%Y/%m/%d')

UFO_complete_df['datetime'] = UFO_complete_df['datetime'].dt.strftime('%Y/%m/%d')
UFO_scrubbed_df['datetime'] = UFO_scrubbed_df['datetime'].dt.strftime('%Y/%m/%d')

print('UFO_complete_df.head', UFO_complete_df.head(), sep="\n")
print('UFO_scrubbed_df.head', UFO_scrubbed_df.head(), sep="\n")

# visualize each dataframe's distribution
city_count = UFO_complete_df['city'].value_counts()
top_10 = city_count.nlargest(50)

country_count = UFO_complete_df['country'].value_counts()
top_50 = country_count.nlargest(50)
# print(type(city_count))

top_10.plot(kind='bar')
plt.xlabel('City')
plt.ylabel('Count')
plt.title('Cities UFO Frequence')
plt.show()

top_50.plot(kind='bar')
plt.xlabel('Country')
plt.ylabel('Count')
plt.title('Countries UFO Frequence')
plt.show()

# fig, ax = plt.subplots()
# city_count.plot(kind='bar', ax=ax)

# # 축 및 제목 설정
# ax.set_xlabel('datetime')
# ax.set_ylabel('city Frequency')
# ax.set_title('Distribution of city Frequency')

# # 그래프 표시
# plt.show()


#!/usr/bin/env python3
'''
Author: qiupengfei@rxthinking.com
Date: 2021-04-22 18:19:28

'''
import logging

from qcaudit.common.const import AUDIT_TYPE_HOSPITAL
from qcaudit.context import Context
from qcaudit.app import Application
from qcaudit.domain.case.req import GetCaseListRequest, GetEmrListRequest
import unittest
import os

class TestCaseApplication(unittest.TestCase):

    def setUp(self):
        mysqlUrl = os.environ.get('MYSQL_URL', 'mysql+pymysql://root:rxthinkingmysql@192.168.100.40:31444/qcmanager_v3?charset=utf8mb4')
        mongoUrl = os.environ.get('MONGO_URL', 'mongodb://192.168.101.159')
        self.app = Application(mysqlUrl, mongoUrl)

        self.context = Context(self.app)

    def test_getCaseList(self):
        req = GetCaseListRequest(
            caseId='7948899',
            start=0,
            size=10
        )
        r = list(self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseList(req))
        assert(len(r) > 0)

    def test_getCaseListBytag(self):
        req = GetCaseListRequest(
            tags=['dead', 'hard'],
            start=0,
            size=10
        )
        r = list(self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseList(req))
        for item in r:
            print(item.tags, item.caseId)
        assert(len(r) > 0)

    def test_getCaseDetail(self):
        c = self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseDetail('7948899')
        assert(c.caseId is not None)

    def test_getCaseEmr(self):
        req = GetEmrListRequest(
            caseId='7948899'
        )
        r = list(self.context.getCaseApplication(AUDIT_TYPE_HOSPITAL).getCaseEmr(req))
        assert(len(r) > 0)

    def test_calculateCaseScore(self):
        r = self.context.getAuditApplication(AUDIT_TYPE_HOSPITAL).calculateCaseScore('7948899', 22)
        print(r.isSuccess)
        print(r.message)
        assert(r.isSuccess == True)

    def test_getReviewers(self):
        r = self.context.getAuditApplication(AUDIT_TYPE_HOSPITAL).getReviewers()
        print(type(r))

        assert(len(r) > 0)


"""The code editor of GraphDonkey, with a few features:

- Syntax Highlighting
- Error Highlighting
- Line Numbers
    Based on https://stackoverflow.com/questions/2443358/how-to-add-lines-numbers-to-qtextedit
- Selection/Line Events (Duplicate, Copy, Cut, Comment/Uncomment, Auto-Indent, Indent/Unindent...)
- Parenthesis Matching
    Based on QtQuarterly 31: https://doc.qt.io/archives/qq/QtQuarterly31.pdf
- Auto-Expand Squiggly and Square brackets

Author: Randy Paredis
Date:   12/14/2019
"""
from dbm import error

from PyQt5 import QtGui, QtWidgets, QtCore

from main.extra import Constants, left
from main.extra.IOHandler import IOHandler
from main.editor.Highlighter import BaseHighlighter
from main.extra.GraphicsView import GraphicsView
from main.Preferences import bool
from main.plugins import PluginLoader
from main.editor.Intellisense import Types, ICONS
import os

pluginloader = PluginLoader.instance()
Config = IOHandler.get_preferences()

class StatusBar(QtWidgets.QStatusBar):
    def __init__(self, wrapper, parent=None):
        super(StatusBar, self).__init__(parent)
        self.wrapper = wrapper
        self.statusMessage = QtWidgets.QLabel("")
        self.statusMessage.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignBaseline)

        self.positionIndicator = QtWidgets.QLabel(":")
        self.positionIndicator.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)

        self.leCombo = QtWidgets.QComboBox()
        self.seps = {
            "Posix (LF)": '\n',
            "Mac OS [Pre-OSX] (CR)": '\r',
            "Windows (CRLF)": '\r\n'
        }
        for name in self.seps:
            self.leCombo.addItem(name, self.seps[name])
        self.setLineSep(os.linesep)

        self.encCombo = QtWidgets.QComboBox()
        self.encCombo.addItem("UTF-8", "utf-8")
        self.encCombo.addItem("UTF-16", "utf-16")
        self.encCombo.addItem("ASCII", "ascii")
        self.encCombo.addItem("ISO-8859-1", "latin1")

        self.ftCombo = QtWidgets.QComboBox()

        rdr = QtWidgets.QLabel("Render with:")
        rdr.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.rendererCombo = QtWidgets.QComboBox()

        self.addPermanentWidget(QtWidgets.QLabel(" "))
        self.addPermanentWidget(self.statusMessage, 7)
        self.addPermanentWidget(self.positionIndicator, 1)
        self.addPermanentWidget(self.leCombo, 1)
        self.addPermanentWidget(self.encCombo, 1)
        self.addPermanentWidget(self.ftCombo, 0)
        self.addPermanentWidget(rdr, 1)
        self.addPermanentWidget(self.rendererCombo, 0)
        self.addPermanentWidget(QtWidgets.QLabel(" "))

    def setLineSep(self, sep):
        seps = {self.seps[n]: n for n in self.seps}
        self.leCombo.setCurrentText(seps.get(sep, ""))

class EditorWrapper(QtWidgets.QWidget):
    def __init__(self, parent):
        super(EditorWrapper, self).__init__(parent)
        self._layout = QtWidgets.QGridLayout()
        self.editor = CodeEditor(self)
        self.mainwindow = parent
        self.types = []
        self.statusBar = StatusBar(self)
        self.filetype = self.statusBar.ftCombo
        self.engine = self.statusBar.rendererCombo
        self.linesep = self.statusBar.leCombo
        self.encoding = self.statusBar.encCombo

        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(self.editor, 0, 0, 1, -1)
        self.filetype.currentIndexChanged.connect(self.alter)
        self.setTypes()
        self.setLayout(self._layout)

    def setTypes(self):
        self.types = pluginloader.getFileTypes()
        txt = self.filetype.currentText()
        self.filetype.clear()
        for type in self.types:
            name, klass = self.types[type]
            self.filetype.addItem(name, klass)
        # TODO: determine filetype based on extension
        self.filetype.setCurrentText(txt)

    def alter(self, idx):
        self.engine.clear()
        if idx >= 0:
            data = self.filetype.itemData(idx)
            self.editor.alter(data(self.editor.document(), self.editor))
            self.editor.highlighter.rehighlight()
            ens = pluginloader.getEnginesForFileType(self.filetype.itemText(idx))
            for en in ens:
                self.engine.addItem(en)
            self.engine.setCurrentText(Config.value("view/engine"))
        self.mainwindow.displayGraph()

    def setType(self, type):
        self.filetype.setCurrentText(self.types[type][0])

class CodeEditor(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.mainwindow = parent.parent()
        self.wrapper = parent
        self.lineNumberArea = LineNumberArea(self)

        self.undoAvailable.connect(self.mainwindow.setUndoEnabled)
        self.redoAvailable.connect(self.mainwindow.setRedoEnabled)

        self.blockCountChanged.connect(self.lineNrChanged)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.positionChangedSlot)
        self.textChanged.connect(self.textChangedSlot)

        self.updateLineNumberAreaWidth()
        self.highlightCurrentLine()
        self.highlighter = BaseHighlighter(self.document(), self)

        self.matches = []
        self.errors = []

        self.setMouseTracking(True)

        self.filename = ""
        self.filecontents = ""

        self.completer = None
        self.setCompleter()

        self.treeView = None

        # Optimize performance of user experience; big files are slow when editing every change event
        self.stTimer = QtCore.QTimer(self)
        self.stTimer.setSingleShot(True)
        self.stTimer.timeout.connect(self.stoppedTyping)

    def textChangedSlot(self):
        txt = self.toPlainText()
        if bool(Config.value("editor/emptyline")) and not txt.endswith(Constants.LINE_ENDING) \
                and not txt.endswith('\n'):
            curs = self.textCursor()
            curs.movePosition(QtGui.QTextCursor.End)
            curs.insertText(Constants.LINE_ENDING)
            curs = self.textCursor()
            curs.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)
            if len(curs.selectedText()) == 0:
                curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
                self.setTextCursor(curs)

    def alter(self, highlighter):
        self.highlighter.deleteLater()
        self.highlighter = highlighter

    def convert(self, engine):
        curs = self.textCursor()
        return self.highlighter.parser.convert(self.toPlainText(), engine,
                                               line=curs.block().blockNumber() + 1, col=curs.columnNumber())

    def stoppedTyping(self):
        self.highlighter.storeErrors()
        if bool(Config.value("editor/useParser", True)):
            self.highlightErrors()

    def positionChangedSlot(self):
        self.stTimer.start(int(Config.value("editor/autoreparse", 100)))
        if bool(Config.value("editor/highlightCurrentLine")):
            self.highlightCurrentLine()
        if bool(Config.value("editor/parentheses")):
            self.matchBrackets()
        self.highlightMatches()
        self.updateIndicator()
        self.mainwindow.updateTitle()

    def lineNrChanged(self):
        self.updateLineNumberAreaWidth()
        self.highlighter.rehighlight()

    def contextMenuEvent(self, event: QtGui.QContextMenuEvent):
        menu = QtWidgets.QMenu(self)
        menu.addAction(self.mainwindow.action_Undo)
        menu.addAction(self.mainwindow.action_Redo)
        menu.addSeparator()
        menu.addAction(self.mainwindow.action_Copy)
        menu.addAction(self.mainwindow.action_Paste)
        menu.addAction(self.mainwindow.action_Cut)
        menu.addAction(self.mainwindow.action_Delete)
        menu.addSeparator()
        menu.addAction(self.mainwindow.action_Select_All)
        menu.exec_(event.globalPos())

    def isSaved(self):
        """Returns True if the file was saved."""
        txt = self.toPlainText()
        if self.filename != "":
            return txt == self.filecontents
        if bool(Config.value("editor/emptyline")):
            txt = txt[:-len(os.linesep)]
        return txt == ""

    def save(self):
        self.filecontents = self.toPlainText()
        if self.treeView is not None and self.treeView.isVisible():
            self.viewParseTree(False)

    def clearContents(self):
        self.selectAll()
        self.insertPlainText("")

    def clearFile(self):
        self.filename = ""
        self.filecontents = ""

    def setCompleter(self):
        self.completer = QtWidgets.QCompleter(self)
        table = QtWidgets.QTableView()
        table.horizontalHeader().hide()
        table.verticalHeader().hide()
        table.setShowGrid(False)
        table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.completer.setPopup(table)
        self.completer.setModel(QtGui.QStandardItemModel())
        self.completer.setFilterMode(QtCore.Qt.MatchContains)
        self.completer.setModelSorting(QtWidgets.QCompleter.CaseInsensitivelySortedModel)
        self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer.setWrapAround(False)
        self.completer.setWidget(self)
        self.completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)

    def insertCompletion(self, completion):
        comp, _ = self.highlighter.parser.visitor.completer.get(completion)
        if len(comp) == 0:
            text = completion
        else: # In case of snippets, use the value (not the name)
            text = comp[0][0] if comp[0][2] is None else comp[0][2]

        cursor = self.textCursor()
        cursor.select(QtGui.QTextCursor.WordUnderCursor)
        cursor.insertText(text)
        self.setTextCursor(cursor)

    def encapsulateText(self, o, c):
        curs = self.textCursor()
        s = curs.selectionStart()
        e = curs.selectionEnd()
        curs.beginEditBlock()
        curs.setPosition(s)
        self.setTextCursor(curs)
        self.insertPlainText(o)

        mc = True
        if s == e:
            ci = curs.block().userData().indexOf(curs.positionInBlock())
            cpos = self.getClosingBracketPos((o, c), curs.block(), ci)
            if cpos >= 0:
                curs.setPosition(cpos)
                oi = curs.block().userData().indexOf(curs.positionInBlock())
                opos = self.getOpeningBracketPos((o, c), curs.block(), oi - 1)
                if opos == s or opos == -1:
                    mc = False
        if mc:
            curs.setPosition(e + len(o))
            self.setTextCursor(curs)
            self.insertPlainText(c)
        curs.setPosition(s + len(o))
        curs.setPosition(e + len(o), QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def keyPressEvent(self, event: QtGui.QKeyEvent):
        paired = pluginloader.getPairedBrackets(self.wrapper.filetype.currentText())

        if self.completer.popup().isVisible():
            if event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, QtCore.Qt.Key_Tab]:
                completion = self.completer.popup().currentIndex().data(QtCore.Qt.UserRole)
                self.insertCompletion(completion)
                self.completer.popup().hide()
            elif event.key() == QtCore.Qt.Key_Escape:
                self.completer.popup().hide()
            else:
                QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
                self.completer.popup().hide()
                self.complete()
        elif event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return]:
            self.insertPlainText(Constants.LINE_ENDING)
            self.autoIndent()
            cursor = self.textCursor()
            cursor.beginEditBlock()
            pos = cursor.position()
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText().lstrip()
            cursor.setPosition(pos)
            cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
            if len(txt) > 0 and txt[0] in [x[1] for x in paired] and len(cursor.selectedText()) == 0:
                cursor.setPosition(pos)
                cursor.insertText(Constants.LINE_ENDING)
                cursor.movePosition(QtGui.QTextCursor.Up, QtGui.QTextCursor.KeepAnchor)
                self.setTextCursor(cursor)
                self.autoIndent()
                cursor.setPosition(pos)
                cursor.movePosition(QtGui.QTextCursor.EndOfLine)
                self.setTextCursor(cursor)
            cursor.endEditBlock()
        elif event.key() == QtCore.Qt.Key_Home:
            cursor = self.textCursor()
            end = cursor.selectionEnd()
            cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            if len(txt.strip()) == 0 != len(txt):
                cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            else:
                cursor.movePosition(QtGui.QTextCursor.StartOfLine)
                cursor.movePosition(QtGui.QTextCursor.NextWord)
            cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
        elif event.key() == QtCore.Qt.Key_Backspace:
            if bool(Config.value("editor/pairedBrackets")):
                curs = self.textCursor()
                s = curs.selectionStart()
                e = curs.selectionEnd()
                if s == e:
                    curs.movePosition(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
                    prev = curs.selectedText()
                    curs.setPosition(s)
                    curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                    next = curs.selectedText()
                    curs.setPosition(s)
                    if (prev, next) in paired:
                        curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
                        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor, 2)
                        self.setTextCursor(curs)
            QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
        elif event.key() not in [QtCore.Qt.Key_Delete, QtCore.Qt.Key_Tab]:
            if bool(Config.value("editor/pairedBrackets")):
                et = event.text()
                if et in [x[0] for x in paired]:    # OPEN
                    pair = [x for x in paired if et in x][0]
                    if pair[0] == pair[1]:
                        curs = self.textCursor()
                        s = curs.selectionStart()
                        e = curs.selectionEnd()
                        if s == e:
                            curs.setPosition(e)
                            curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                            txt = curs.selectedText()
                            if txt != pair[0]:
                                self.encapsulateText(*pair)
                            else:
                                curs.setPosition(e)
                                curs.movePosition(QtGui.QTextCursor.NextCharacter)
                                self.setTextCursor(curs)
                        else:
                            self.encapsulateText(*pair)
                    else:
                        self.encapsulateText(*pair)
                elif et in [x[1] for x in paired]:  # CLOSE
                    pair = [x for x in paired if et in x][0]
                    curs = self.textCursor()
                    s = curs.selectionStart()
                    e = curs.selectionEnd()
                    if s == e:
                        curs.setPosition(e)
                        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                        txt = curs.selectedText()
                        if txt != pair[1]:
                            self.insertPlainText(pair[1])
                        else:
                            curs.setPosition(e)
                            curs.movePosition(QtGui.QTextCursor.NextCharacter)
                            self.setTextCursor(curs)
                    else:
                        self.insertPlainText(pair[1])
                else:
                    QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
            else:
                QtWidgets.QPlainTextEdit.keyPressEvent(self, event)

    def event(self, event: QtCore.QEvent):
        if event.type() == QtCore.QEvent.ShortcutOverride:
            return False
        return QtWidgets.QPlainTextEdit.event(self, event)

    def setText(self, text):
        self.document().setPlainText(text)

    def mouseMoveEvent(self, event: QtGui.QMouseEvent):
        pos = event.pos()
        cursor = self.cursorForPosition(pos)
        cursor.select(QtGui.QTextCursor.WordUnderCursor)
        tpos = cursor.position()
        for start, size, msg in self.errors:
            if start <= tpos <= start + size:
                QtWidgets.QToolTip.showText(event.globalPos(), msg, self)
        return QtWidgets.QPlainTextEdit.mouseMoveEvent(self, event)

    def delete(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt == "":
            cursor.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
        self.insertPlainText("")

    def _cc(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt == "":
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)

    def copy(self):
        self._cc()
        QtWidgets.QPlainTextEdit.copy(self)

    def cut(self):
        self._cc()
        QtWidgets.QPlainTextEdit.cut(self)

    def duplicate(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        posE = cursor.selectionEnd()
        if txt == "":   # Duplicate line
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            cursor.insertText(txt + Constants.LINE_ENDING + txt)
        else:           # Duplicate selection
            cursor.insertText(txt + txt)
            cursor.setPosition(posE)
            cursor.setPosition(posE + len(txt), QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)

    def lines(self, func, state=None):
        cursor = self.textCursor()
        posS = cursor.selectionStart()
        posE = cursor.selectionEnd()

        cursor.beginEditBlock()
        cursor.setPosition(posS)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine)
        cursor.setPosition(posE, QtGui.QTextCursor.KeepAnchor)
        cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        otxt = cursor.selectedText()
        txt = otxt.split(Constants.LINE_ENDING)
        add = 0
        for i in range(len(txt)):
            state, line = func(txt[i], state)
            if i == 0:
                add = len(line) - len(txt[i])
            txt[i] = line
        ntxt = Constants.LINE_ENDING.join(txt)
        cursor.setPosition(posS)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine)
        cursor.setPosition(posE, QtGui.QTextCursor.KeepAnchor)
        if cursor.selectedText() == Constants.LINE_ENDING or posS == posE:
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        cursor.insertText(ntxt)
        cursor.setPosition(posS + add)
        cursor.setPosition(posE + len(ntxt) - len(otxt), QtGui.QTextCursor.KeepAnchor)
        cursor.endEditBlock()
        self.setTextCursor(cursor)

        return cursor

    def comment(self):
        # TODO: identify indents before/after comment signs
        def cmnt(line, state):
            txt = line
            if txt[:2] == "//" and state in [True, None]:
                txt = txt[2:]
                state = True
            elif len(txt) > 0 and txt[0] == "#" and state in [True, None]:
                txt = txt[1:]
                state = True
            elif state in [False, None]:
                txt = "//" + txt
                state = False
            return state, txt

        self.lines(cmnt)

    def indent(self):
        tab = '\t'
        if bool(Config.value("editor/spacesOverTabs")):
            tab = ' ' * int(Config.value("editor/tabwidth"))

        def func(line, state):
            return state, tab + line

        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt != "":
            self.lines(func)
        else:
            self.insertPlainText(tab)

    def unindent(self):
        # 1) take all left whitespace;
        # 2) replace tabs with spaces (w.r.t. Config);
        # 3) remove 1 character;
        # 4) reduce string length until length % tablength == 0;
        # 5) this is new whitespace length
        ws = (' ', '\t')
        useSpaces = bool(Config.value("editor/spacesOverTabs"))
        tablength = int(Config.value("editor/tabwidth"))

        def func(line, state):
            txt = line
            lft = left(txt, ws)
            if useSpaces:
                lft = lft.replace("\t", " " * tablength)
                if len(lft) > 0:
                    lft = lft[:-1]
                lft = lft[:(len(lft) // tablength) * tablength]
                txt = lft + txt.lstrip()
            else:
                if len(lft) > 0 and lft[-1] in ws:
                    txt = lft[:-1] + txt.lstrip()
            return state, txt

        self.lines(func)

    def autoIndent(self):
        cursor = self.textCursor()
        posS = cursor.selectionStart()
        cursor.setPosition(posS)
        s = cursor.movePosition(QtGui.QTextCursor.Up)
        linenr = 0
        indent = 0
        tw = int(Config.value("editor/tabwidth"))
        sot = bool(Config.value("editor/spacesOverTabs"))
        if s:
            linenr = cursor.blockNumber() + 1
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            for c in txt:
                if c == ' ':
                    indent += 1
                elif c == '\t':
                    indent += tw
                else:
                    break

        if not sot:
            indent //= tw

        vis = self.highlighter.parser.visitor

        def indentLine(line, state):
            vobt = vis.obtain(state, linenr)
            txt = line.lstrip()
            if sot:
                inc = indent + (vobt * tw)
                line = (" " * inc) + txt
            else:
                inc = indent + vobt
                line = ("\t" * inc) + txt
            state += 1
            return state, line

        self.lines(indentLine, linenr + 1)

    def moveUp(self):
        curs = self.textCursor()
        curs.beginEditBlock()
        start = curs.selectionStart()
        end = curs.selectionEnd()
        curs.setPosition(start)
        curs.movePosition(QtGui.QTextCursor.PreviousBlock)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
        curs.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        txt = curs.selectedText()
        curs.removeSelectedText()
        start -= len(txt)
        end -= len(txt)
        curs.setPosition(end)
        curs.movePosition(QtGui.QTextCursor.EndOfLine)
        curs.insertText(txt)
        curs.setPosition(start)
        curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def moveDown(self):
        curs = self.textCursor()
        curs.beginEditBlock()
        start = curs.selectionStart()
        end = curs.selectionEnd()
        curs.setPosition(end)
        curs.movePosition(QtGui.QTextCursor.NextBlock)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
        txt = curs.selectedText()
        curs.removeSelectedText()
        curs.setPosition(start)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.insertText(txt)
        start += len(txt)
        end += len(txt)
        curs.setPosition(start)
        curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def complete(self):
        cursor = self.textCursor()
        cursor.setPosition(cursor.selectionStart())
        cursor.movePosition(QtGui.QTextCursor.StartOfWord, QtGui.QTextCursor.KeepAnchor)
        prefix = cursor.selectedText()

        ctr = self.highlighter.parser.visitor.completer

        # Reload the completion set
        ctr.clear()
        self.highlighter.storeErrors()

        tp = self.wrapper.filetype.currentText()
        for p in pluginloader.get():
            snps = p.types.get(tp, {}).get("snippets", {})
            for n in snps:
                ctr.add(n, Types.SNIPPET, snps[n])
        snps = self.mainwindow.snippets.snippets
        for n in snps.get(tp, {}):
            ctr.add(n, Types.SNIPPET, snps[tp].get(n, None))
        completions, prefix = ctr.get(prefix)

        mdl = self.completer.model()
        mdl.clear()
        for px, ty, v in completions:
            if px == prefix: continue
            pth = [px.index(x) for x in prefix]
            itc = "".join(["<b>%s</b>" % px[s] if s in pth else px[s] for s in range(len(px))])
            ite = ""
            if v is not None:
                ite = "<div align='right'>%s </div>" % v
            it = QtGui.QStandardItem(itc)
            ico = ICONS[ty]
            if ico is not None:
                it.setIcon(ico)
            it.setData(px, QtCore.Qt.UserRole)
            mdl.appendRow([it, QtGui.QStandardItem(ite)])

        if len(completions) == 0:
            return

        if self.completer.popup().currentIndex().row() == -1 or prefix != self.completer.completionPrefix():
            self.completer.setCompletionPrefix(prefix)
            self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0))

        cr = self.cursorRect()
        cr.setLeft(cr.left() + self.completer.popup().verticalScrollBar().sizeHint().width() * 3)
        cr.setWidth(self.mainwindow.width() / 4)
        # TODO: Completer font size
        self.completer.popup().horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.completer.popup().setItemDelegate(HTMLDelegate(self.completer.popup()))
        self.completer.complete(cr)

        if self.completer.popup().currentIndex().row() == -1 or prefix != self.completer.completionPrefix():
            self.completer.setCompletionPrefix(prefix)
            self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0))

    def matchBrackets(self):
        paired = pluginloader.getPairedBrackets(self.wrapper.filetype.currentText())
        bopen = [x[0] for x in paired]
        bclose = [x[1] for x in paired]

        curs = self.textCursor()
        data = curs.block().userData()
        if data:
            infos = data.parenthesis

            pos = curs.block().position()
            curPos = curs.positionInBlock()
            block = curs.block()
            for i in range(len(infos)):
                info = infos[i]
                if info.at(curPos):
                    oidx = bopen.index(info.char) if info.char in bopen else -1
                    cidx = bclose.index(info.char) if info.char in bclose else -1
                    if info.char in bopen:
                        cpos = self.getClosingBracketPos(paired[oidx], block, i + 1)
                        if cpos >= 0:
                            curs.setPosition(cpos)
                            j = curs.block().userData().indexOf(curs.positionInBlock())
                            opos = self.getOpeningBracketPos(paired[oidx], curs.block(), j - 1)
                            if info.pos == opos - pos:
                                self.highlightBrackets(opos, len(paired[oidx][0]))
                                self.highlightBrackets(cpos, len(paired[oidx][1]))
                    if info.char in bclose:
                        opos = self.getOpeningBracketPos(paired[cidx], block, i - 1)
                        if opos >= 0:
                            curs.setPosition(opos)
                            j = curs.block().userData().indexOf(curs.positionInBlock())
                            cpos = self.getClosingBracketPos(paired[cidx], curs.block(), j + 1)
                            if info.pos == cpos - pos:
                                self.highlightBrackets(cpos, len(paired[cidx][1]))
                                self.highlightBrackets(opos, len(paired[cidx][0]))

    def getOpeningBracketPos(self, pair, block, i, num=0):
        data = block.userData()
        infos = data.parenthesis

        docPos = block.position()
        for j in range(i, -1, -1):
            if len(infos) == 0:
                break
            info = infos[j]

            if info.char == pair[1] and pair[0] != pair[1]:
                num += 1
                continue
            if info.char == pair[0]:
                if num == 0:
                    return docPos + info.pos
                num -= 1

        block = block.previous()
        if block.isValid():
            return self.getOpeningBracketPos(pair, block, 0, num)

        return -1

    def getClosingBracketPos(self, pair, block, i, num=0):
        if i < 0:
            return -1
        data = block.userData()
        infos = data.parenthesis

        docPos = block.position()
        for j in range(i, len(infos)):
            info = infos[j]

            if info.char == pair[0] and pair[0] != pair[1]:
                num += 1
                continue
            if info.char == pair[1]:
                if num == 0:
                    return docPos + info.pos
                num -= 1

        block = block.next()
        if block.isValid():
            return self.getClosingBracketPos(pair, block, 0, num)

        return -1

    def highlightBrackets(self, pos, size=1):
        selection = QtWidgets.QTextEdit.ExtraSelection()
        selection.format.setBackground(QtGui.QColor(Config.value("col/clnb")))
        selection.format.setForeground(QtGui.QColor(Config.value("col/clnf")))

        curs = self.textCursor()
        curs.setPosition(pos)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor, size)
        selection.cursor = curs

        selections = self.extraSelections()
        selections.append(selection)
        self.setExtraSelections(selections)

    def highlightMatches(self):
        selections = self.extraSelections()

        for start, end, _ in self.matches:
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format.setBackground(QtGui.QColor(Config.value("col/find")))

            curs = self.textCursor()
            curs.setPosition(start)
            curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
            selection.cursor = curs
            selections.append(selection)

        self.setExtraSelections(selections)

    def highlightErrors(self):
        selections = self.extraSelections()
        for start, size, message in self.errors:
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format = BaseHighlighter.format_error()

            curs = self.textCursor()
            curs.setPosition(start)
            curs.setPosition(start + size, QtGui.QTextCursor.KeepAnchor)
            selection.cursor = curs
            selections.append(selection)
        self.setExtraSelections(selections)

    def highlightCurrentLine(self):
        selections = []
        if not self.isReadOnly():
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format.setBackground(QtGui.QColor(Config.value("col/cline")))
            selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
            selection.cursor = self.textCursor()
            selection.cursor.clearSelection()
            selections.append(selection)

        self.setExtraSelections(selections)

    def lineNumberAreaPaintEvent(self, event):
        self.verticalScrollBar().setSliderPosition(self.verticalScrollBar().sliderPosition())
        painter = QtGui.QPainter(self.lineNumberArea)
        painter.fillRect(event.rect(), QtGui.QColor(Config.value("col/lnb")))

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + round(self.blockBoundingRect(block).height())

        currentBlockNumber = self.textCursor().block().blockNumber()

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = str(blockNumber + 1)
                if currentBlockNumber == blockNumber:
                    painter.fillRect(QtCore.QRect(0, top, self.lineNumberArea.width(), self.fontMetrics().height()),
                                     QtGui.QColor(Config.value("col/clnb")))
                    painter.setPen(QtGui.QColor(Config.value("col/clnf")))
                else:
                    painter.setPen(QtGui.QColor(Config.value("col/lnf")))
                painter.drawText(0, top, self.lineNumberArea.textWidth(), self.fontMetrics().height(),
                                 QtCore.Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + round(self.blockBoundingRect(block).height())
            blockNumber += 1

    def lineNumberAreaWidth(self):
        if not bool(Config.value("editor/showLineNumbers", True)):
            return 0
        digits = 1
        _max = max(1, self.document().blockCount())
        while _max >= 10:
            _max /= 10
            digits += 1

        return 13 + self.fontMetrics().width('9') * digits + self.lineNumberArea.offset

    def resizeEvent(self, event):
        QtWidgets.QPlainTextEdit.resizeEvent(self, event)
        cr = self.contentsRect()
        self.lineNumberArea.setGeometry(QtCore.QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))

    def updateIndicator(self):
        if isinstance(self.mainwindow.statusBar(), StatusBar):
            text = ""
            cursor = self.textCursor()
            if cursor.selectedText() != "":
                text = "[%i chars]" % len(cursor.selectedText())
            self.mainwindow.statusBar().positionIndicator\
                .setText("%s      %i:%i" % (text, cursor.blockNumber() + 1, cursor.columnNumber() + 1))

    def updateLineNumberAreaWidth(self, newBlockCount=0):
        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

    def updateLineNumberArea(self, rect, dy):
        self.verticalScrollBar().setSliderPosition(self.verticalScrollBar().sliderPosition())

        if dy:
            self.lineNumberArea.scroll(0, dy)
        else:
            self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())

        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth()

    def viewParseTree(self, focus=True):
        txt = self.toPlainText()
        T = self.highlighter.parser.parse(txt, True)
        if T is not None:
            if self.treeView is None:
                self.treeView = QtWidgets.QDialog(self.parent(), flags=QtCore.Qt.Window)
                layout = QtWidgets.QGridLayout()
                view = GraphicsView(self.mainwindow, self.parent())
                layout.addWidget(view)
                self.treeView.setLayout(layout)
            self.treeView.setWindowTitle("Lark LALR Parse Tree of %s" % self.filename)
            view = self.treeView.layout().itemAtPosition(0, 0).widget()
            view.setControls(bool(Config.value("view/controls")))
            view.setMinZoomLevel(float(Config.value("view/zoomMin")) / 100)
            view.setMaxZoomLevel(float(Config.value("view/zoomMax")) / 100)
            view.setZoomFactorBase(float(Config.value("view/zoomFactor")))
            view.clear()

            ename = self.wrapper.engine.currentText()
            T = self.highlighter.parser.parse(self.toPlainText())
            engine = pluginloader.getEngines()[ename]
            if T is not None:
                if "AST" in engine:
                    bdata = engine["AST"](T)
                    view.add(bdata)
                else:
                    engine = pluginloader.getEngines().get("Graphviz", {})
                    if "AST" in engine:
                        bdata = engine["AST"](T)
                        view.add(bdata)
                    else:
                        self.mainwindow.error("Error!", "The current rendering engine '%s' does not support the "
                                                        "rendering of Abstract Syntax Trees and the fallback renderer "
                                                        "'Graphviz' cannot be found.\n\nCurrently unable to display the"
                                                        " AST." % ename)
                        return

            if not self.treeView.isVisible():
                self.treeView.show()
            if focus:
                self.treeView.activateWindow()
                self.treeView.raise_()
                self.treeView.setFocus()
        else:
            self.mainwindow.warn("Warning!", "It looks like your file contains some errors. Impossible to render AST.")
            if self.treeView is not None and self.treeView.isVisible():
                self.treeView.close()

class LineNumberArea(QtWidgets.QWidget):
    def __init__(self, editor):
        super(LineNumberArea, self).__init__(editor)
        self.editor = editor
        self.offset = 10

    def textWidth(self):
        return self.width() - self.offset

    def sizeHint(self):
        return QtCore.QSize(self.editor.lineNumberAreaWidth(), 0)

    def paintEvent(self, QPaintEvent):
        self.editor.lineNumberAreaPaintEvent(QPaintEvent)

class HTMLDelegate(QtWidgets.QStyledItemDelegate):
    """Delegate inspired by:

    https://stackoverflow.com/questions/1956542/how-to-make-item-view-render-rich-html-text-in-qt/1956781#1956781
    """
    def paint(self, painter, options, QModelIndex):
        self.initStyleOption(options, QModelIndex)
        style = QtWidgets.QApplication.style() if options.widget is None else options.widget.style()

        doc = QtGui.QTextDocument()
        col = Config.value("col/foreground")
        if self.parent().currentIndex().row() == QModelIndex.row():
            col = Config.value("col/highlightedText")
        doc.setHtml("<nobr><font color='%s'>%s</font></nobr>" % (col, options.text))
        doc.setTextWidth(options.rect.width())

        options.text = ""
        # options.showDecorationSelected = False
        # options.features ^= QtWidgets.QStyleOptionViewItem.HasDisplay
        # style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()

        painter.save()
        rh = options.rect.height()
        iconSize = QtCore.QSize(rh, rh) * 0.8
        isize = iconSize * 0.8
        pt = options.rect.topLeft()
        o = (rh - isize.height()) / 2
        pt += QtCore.QPoint(o, o)
        options.icon.paint(painter, QtCore.QRect(pt, isize))
        painter.translate(options.rect.left() + iconSize.width(), options.rect.top())
        clip = QtCore.QRectF(0, 0, options.rect.width() + iconSize.width(), options.rect.height())
        painter.setClipRect(clip)
        ctx.clip = clip
        doc.documentLayout().draw(painter, ctx)

        painter.restore()

    def sizeHint(self, options, QModelIndex):
        self.initStyleOption(options, QModelIndex)

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())

        return QtCore.QSize(doc.idealWidth(), doc.size().height())


import argparse
import sys
import warnings

from train_acc import *
from train_auc import *
from train_binary import *
from train_noContent import *
from train_noContentGRL2Spoof import *
from train_auc_no_depth import *
from train_auc_triplet_ours import *
from train_auc_triplet_ssdg import *
from train_auc_2domain import *
from train_celeba import *
from train_shared_auc import *
from train_shared_nodomain import *
from train_shared_nocontent import *
from test_auc import *

def main(args):
    if args.type == 'train_auc':
        train_auc(args)

    elif args.type == 'train_shared_auc':
        train_shared_auc(args)

    elif args.type == 'train_shared_auc_no_domain':
        train_shared_auc_no_domain(args)

    if args.type == 'train_shared_auc_no_content':
        train_shared_auc_no_content(args)

    elif args.type == 'train_acc':
        train_acc(args)

    elif args.type == 'train_binary':
        train_binary(args)

    elif args.type == 'train_noContent':
        train_noContent(args)

    elif args.type == 'train_noContentGRL2Spoof':
        train_noContentGRL2Spoof(args)

    elif args.type == 'train_noDepth':
        train_noDepth(args)

    elif args.type == 'train_aucTripletOurs':
        train_auc_triplet_ours(args)

    elif args.type == 'train_aucTripletSSDG':
        train_auc_triplet_ssdg(args)

    elif args.type == "train_2domain":
        train_auc_2domain(args)

    elif args.type == 'train_celeba':
        train_celeba(args)

    elif args.type == 'test_auc':
        test_auc(args)

    else:
        warnings.warn("Please check your training type")
        sys.exit()

if __name__ == '__main__':
    # path: model will be saved to path/model/target_domain/number_folder/model.pt
    # dataset_path: folder of training and testing file (includes pr_depth_map)
    # target_domain
    # number_folder
    # img_size: resize img
    # depth_size: resize depth img
    # batch_size
    # batch_triplet
    # lr
    # n_epoch

    parser = argparse.ArgumentParser(description="FRANK")

    parser.add_argument('--seed', type=int, default=0)
    parser.add_argument('--path', type=str, default="./")
    parser.add_argument('--dataset_path', type=str, default="./pr_depth_map_256")
    parser.add_argument('--type', type=str, default='train_auc')
    parser.add_argument('--gpu_id', type=str, default='0')
    parser.add_argument('--spoof_encoder', type=str, default="/home/tsaolin/Face_Anti-Spoofing/FaceAntiSpoofing-WACV/model/oulu/224_0/oulu_spoof_encoder.pt")
    parser.add_argument('--spoof_classifier', type=str, default="/home/tsaolin/Face_Anti-Spoofing/FaceAntiSpoofing-WACV/model/oulu/224_0/oulu_spoof_classify.pt")

    # datasets
    parser.add_argument('--target_domain', type=str, default='oulu')
    parser.add_argument('--number_folder', type=str, default='0')

    # model
    parser.add_argument('--scratch', type=str, default='True')
    parser.add_argument('--load_folder', type=str, default='0')

    # optimizer
    parser.add_argument('--lr', type=float, default=0.0001)

    # training configs
    parser.add_argument('--img_size', type=int, default=256)
    parser.add_argument('--depth_size', type=int, default=64)
    parser.add_argument('--batch_size', type=int, default=10)
    parser.add_argument('--test_batch_size', type=int, default=64)
    parser.add_argument('--batch_triplet', type=int, default=4)
    parser.add_argument('--n_epoch', type=int, default=100)

    print(parser.parse_args())
    main(parser.parse_args())


# A binary tree node
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
    def __str__(self):
        return f"TreeNode(val={self.val}, left={self.left}, right={self.right})"

def maxPathSum(root:TreeNode) -> int:
    res = root.val

    def dfs(node):
        if not node:
            return 0

        leftMax = max(dfs(node.left), 0)
        rightMax = max(dfs(node.right), 0)

        # recording the possibility that we just take the left and right max and
        # split at this node
        nonlocal res
        res = max(res, node.val+leftMax+rightMax)

        # returning the value without a split to be used by the parent node
        return node.val + max(leftMax, rightMax)

    dfs(root)
    return res

tree = TreeNode(
    val=4,
    left=TreeNode(
        val=2,
        left=TreeNode(
            val=13,
            left=TreeNode(
                val=-2)),
        right=TreeNode(
            val=6,)
    ),
    right=TreeNode(
        val=15,
        right=TreeNode(
            val=-5))
    )

#           4
#         /   \
#        2     15
#      /  \      \
#     13   6      -5
#    /
#   -2

print(maxPathSum(tree))


import shortest_path_switch
import simple_switch
from ryu.controller.handler import MAIN_DISPATCHER, set_ev_cls
from ryu.controller import ofp_event
import os
import socket
import json
from ryu.lib import hub

SOCKFILE = '/tmp/hello_sock'

class ShortestRestSwitch(simple_switch.SimpleSwitch13):

	def __init__(self, *args, **kwargs):
		super(ShortestRestSwitch, self).__init__(*args, **kwargs)
		self.sock = None
		self.config = {}
		self.start_sock_server()

	def set_vtable(self, host, vlan):
		if self.vtable[host] != vlan:
			self.vtable.update({host:vlan})
			self.SimpleSwitchDeleteFlow(self.default_datapath, host)

	def recv_loop(self):
		print('start loop')
		while True:
			print('wait for recev')
			data = self.sock.recv(1024)
			print('Receive new vtable from web')
			print(data)
			msg = json.loads(data)
			if msg:
				print('get msg')

			for host, vlan in msg.items():
				self.set_vtable(host, vlan)

	def start_sock_server(self):
		if os.path.exists(SOCKFILE):
			os.unlink(SOCKFILE)

		self.sock = hub.socket.socket(hub.socket.AF_UNIX, hub.socket.SOCK_DGRAM)
		self.sock.bind(SOCKFILE)
		hub.spawn(self.recv_loop)


from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

from bs4 import BeautifulSoup
import urllib.request

class CraiglistScraper(object):
	def __init__(self, location, postal, max_price, radius):
		self.location = location
		self.postal = postal
		self.max_price = max_price
		self.radius = radius
		self.driver = webdriver.Chrome('/home/refuge/code/scraping/soup/chromedriver')
		self.delay = 3
		self.url = "https://%s.craigslist.org/search/sss?search_distance=%s&postal=%s&max_price=%s" %(location,postal,radius,max_price)

	def load_craigslist(self):
		self.driver.get(self.url)
		try:
			wait = WebDriverWait(self.driver, self.delay)
			wait.until(EC.presence_of_element_located((By.ID, "searchform")))
			print("pag is ready")
		except TimeoutException:
			print("Location took too much time")

	def extract_post_infomation(self):
		all_posts = self.driver.find_elements_by_class_name("result-row")

		dates = []
		titles = []
		prices = []

		for post in all_posts:
			title = post.text.split("$")
			# print(title)
			if title[0] == '':
				title = title[1]
			else:
				title = title[0]
			title = title.split("\n")
			price = title[0]
			title = title[-1]

			title = title.split(" ")
			month = title[0]
			day = title[1]
			title = ' '.join(title[2:])
			date = month + " " + day

			# print("PRICE: " + price)
			# print("TITLE: " + title)
			# print("DATE: " + date)

			# storing them in alist
			titles.append(title)
			prices.append(price)
			dates.append(date)
		return titles, prices, dates

	def extract_post_urls(self):
		url_list = []
		html_page = urllib.request.urlopen(self.url)
		soup = BeautifulSoup(html_page, "lxml")
		# get the url plus the class
		for link in soup.findAll("a", {"class": "result-title hdrlnk"}):
			# only grabing the href
			print(link["href"])
			url_list.append(link["href"])
		return url_list

	def quit(self):
		self.driver.close()

location = "sfbay"
postal = "94201"
max_price = "500"
radius = "5"
scraper = CraiglistScraper(location, postal, max_price, radius)
scraper.load_craigslist()
titles, prices, dates, = scraper.extract_post_infomation()
print(dates)
# scraper.extract_post_urls()
# scraper.quit()


#!/usr/bin/env python
"""
Convert tsv to fasta"""
import sys
import re
f=open(sys.argv[1])
o=open(sys.argv[2],'w')

for line in f:
    fields=line.split()
    o.write(">%s\n"%(fields[0]))
    line1=fields[1].replace('-','')
    o.write("%s\n"%(line1))

f.close()
o.close()


import torch
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.nn.init as init
from DiscriminatorSIMP import DiscriminatorNet
from torch.utils.data import DataLoader
from GeneratorSIMP import GeneratorNet
from PIL import Image
from torchvision import transforms, datasets
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

def noise(size):
    '''
    Generates a 1-d vector of gaussian sampled random values
    '''
    n = Variable(torch.from_numpy(np.random.normal(0, 1, 1))).flat()
    return n

def ones_target(size):
    '''
    Tensor containing ones, with shape = size
    '''
    data = Variable(torch.ones(size, 1))
    return data

def zeros_target(size):
    '''
    Tensor containing zeros, with shape = size
    '''
    data = Variable(torch.zeros(size, 1))
    return data

def train_discriminator(optimizer, real_data, fake_data):
    N = real_data.size(0)
    # Reset gradients
    optimizer.zero_grad()

    # 1.1 Train on Real Data
    prediction_real = discriminator(real_data)
    # Calculate error and backpropagate
    error_real = loss(prediction_real, ones_target(N) )
    error_real.backward()

    # 1.2 Train on Fake Data
    prediction_fake = discriminator(fake_data)
    # Calculate error and backpropagate
    error_fake = loss(prediction_fake, zeros_target(N))
    error_fake.backward()

    # 1.3 Update weights with gradients
    optimizer.step()

    # Return error and predictions for real and fake inputs
    return error_real + error_fake, prediction_real, prediction_fake

def train_generator(mu, fake_data, discriminator):
    N = fake_data.size(0)
    learning_step = 0.01
    sum = 0
    predictions = discriminator(fake_data)
    zipped = zip(fake_data, predictions)
    for row in zipped:
        sum += row[1].data*(mu-row[0].data)

    sum = sum/N

    mu = mu - learning_step*(sum.data)
    return mu

#Get 1000 samples from normal distribution with mean 0, variance 1
data = np.random.normal(0, 1, 10000)

train_ratios = [1, 2, 3, 4, 5, 10, 20, 50]

num_epochs = 50
samples_run_through = 1
d_errors_f = open("Errors/simple"+str(num_epochs)+ "_lr001_SGD/d_errors.txt","w")
g_errors_f = open("Errors/simple"+ str(num_epochs)+ "_lr001_SGD/g_errors.txt","w")
x_train = DataLoader(torch.from_numpy(data).float(), 512, shuffle=True)
for train_ratio in train_ratios:
    torch.manual_seed(0)
    mu = torch.Tensor([2])
    discriminator = DiscriminatorNet()
    discriminator = discriminator.float()
    d_optimizer = optim.SGD(discriminator.parameters(), lr=0.001)
    loss = nn.BCELoss()
    print(train_ratio)
    for epoch in range(num_epochs):
        for n_batch, real_batch in enumerate(x_train):
            N = real_batch.size(0)
            # 1. Train Discriminator
            real_data = Variable(real_batch)
            for i in range(train_ratio):
                # Generate fake data and detach
                # (so gradients are not calculated for generator)
                fake_data = Variable(torch.from_numpy(np.random.normal(mu, 1, N))).float()
                # Train D
                d_error, d_pred_real, d_pred_fake = train_discriminator(d_optimizer, real_data, fake_data)
            samples_run_through += 1
            params = list(discriminator.parameters())
            d_errors_f.write(str(params[0].item())+";" + str(params[1].item()) + ";" +str(samples_run_through)+";"+str(epoch)+";"+str(n_batch)+";" + str(train_ratio) + "\n")
            g_errors_f.write(str(mu.item())+";"+str(samples_run_through)+";"+str(epoch)+";"+ str(train_ratio) +"\n")
            # 2. Train Generator
            # Generate fake data
            fake_data = Variable(torch.from_numpy(np.random.normal(mu, 1, N))).float()
            # Train G
            mu = train_generator(mu, fake_data, discriminator)


import numpy as np
import pandas as pd

def outlier_z_score_filter_df(df, threshold=3):
    """
    데이터프레임의 모든 feature에 대해 Z-score 방법을 이용하여 이상치를 제거하고, NA 값을 가진 행을 제거하는 함수
    :param df: 이상치를 제거할 데이터프레임
    :param threshold: 이상치 판단 기준값 (일반적으로 3 사용)
    :return: 이상치가 제거된 데이터프레임
    """
    # 데이터프레임의 모든 feature에 대해 Z-score 방법을 이용하여 이상치 제거
    filtered_df = df.apply(
        lambda x: x[np.abs((x - x.mean()) / x.std()) < threshold])

    # NA 값을 가진 행 제거
    print("Drop Data \n", filtered_df.isna().sum())
    filtered_df = filtered_df.fillna(method='ffill')
    # filtered_df = filtered_df.dropna()

    # 결과 반환
    return filtered_df

def moving_average(df, period):
    """
    데이터프레임에서 이동평균을 구하는 함수

    :param df: 이동평균을 계산할 데이터프레임
    :param period: 이동평균의 기간
    :return: 이동평균이 추가된 데이터프레임
    """
    ma = df.rolling(period).mean().fillna(method='bfill')  # 이동평균 계산
    ma.columns = [col + '_MA' + str(period) for col in df.columns]  # 컬럼 이름 변경
    return pd.concat([df, ma], axis=1)  # 데이터프레임 합치기


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

def solution() :
    n = int(input())
    cards = deque([i for i in range(1, n+1)])

    while len(cards) != 1 :
        cards.popleft()
        cards.append(cards.popleft())

    print(cards[0])

solution()


def analise(* num):
    soma = 0
    cont = 0
    maior = 0
    for i in num:
        print(f'{i}', end=' ')
        soma += i
        cont += 1
        if i > maior:
            maior = i
    print(f'\nForam informados {cont} valores.')
    print(f'A soma dos valores é igual a {soma}')
    print(f'O maior numero é {maior}')

analise(1, 2, 3)

analise(4, 5, 7, 9)


# -*- coding:UTF-8 -*-
from ttk import *
from Tkinter import *
import ttk
import os

def centering(win):
		"""
		This function is used for centering main window
		"""
		win.update_idletasks()
		width = win.winfo_width()
		frm_width = win.winfo_rootx() - win.winfo_x()
		win_width = width + 2 * frm_width
		height = win.winfo_height()
		titlebar_height = win.winfo_rooty() - win.winfo_y()
		win_height = height + titlebar_height + frm_width
		x = win.winfo_screenwidth() // 2 - win_width // 2
		y = win.winfo_screenheight() // 2 - win_height // 2
		win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

class Sucket:

    def __init__(self, window):
        """
        This function is used for all work, or in other words, this is the main window
        """
        self.window = window
        self.window.resizable(width=False, height=False)
        self.window.title('Sucket - Because dealing with sockets suck')
        base = Frame(self.window, bg='#2A1717')
        base.place(relx=0.01, rely=0.01,relheight=0.97, relwidth=0.98)
        chat = LabelFrame(base)
        chat.place(relx=0.01, rely=0.02,relheight=0.63, relwidth=0.98)
        text = Text(base)
        text.place(relx=0.01, rely=0.74,relheight=0.24, relwidth=0.84)
        bar = Scrollbar(base)
        bar.place(relx=0.84, rely=0.74,relheight=0.24, relwidth=0.03)
        bar.config(command=text.yview)
        text.config(yscrollcommand=bar.set)
        encrypt = Checkbutton(base, bg='#2A1717', fg='#ED0A0A', text="if this is active, enable hash text", command=None)
        encrypt.place(relx=0.01, rely=0.66, relheight=0.06, relwidth=0.49)
        send = Button(base, text='Send')
        send.place(relx=0.88, rely=0.74, relheight=0.20, relwidth=0.11)

def Program():
	"""
	this function is used for call all methods and construct the program
	"""
	root=Tk()
	root.geometry('460x240')
	acess=Sucket(root)
	centering(root)
	root.mainloop()
Program()


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def postorderTraversal(self, root):
        answer = []
        stack = [root]
        while stack:
            temp = stack.pop()
            if temp:
                answer.append(temp.val)
                stack.append(temp.left)
                stack.append(temp.right)
        return answer[::-1]


import os

import networkx as nx

if __name__ == "__main__":
    path_to_data = os.path.join("data", "email-Eu-core.txt")

    graph = nx.read_edgelist(path_to_data, create_using=nx.DiGraph)
    graph.remove_edges_from(list(nx.selfloop_edges(graph)))

    conn_comp = list(map(lambda x: (x, len(x)), nx.algorithms.strongly_connected_components(graph)))
    conn_comp.sort(reverse=True, key=lambda x: x[1])

    subg = graph.subgraph(conn_comp[0][0])

    nx.write_edgelist(subg, os.path.join(os.path.dirname(path_to_data), "simplified.txt"), encoding="utf-8", data=False)