import time
from itertools import count

from bs4 import BeautifulSoup
from selenium import webdriver
from datetime import datetime

wd = webdriver.Chrome('D:\cafe24\chromedriver_win32\chromedriver.exe')
wd.get('http://goobne.co.kr/store/search_store.jsp')

time.sleep(5)

results = []

for page in count(start=1):

    script = 'store.getList(%d)' % page

    wd.execute_script(script)

    print(f'{datetime.now()}: success for request[{script}]')
    time.sleep(3)

    # 렌더링 후 HTML 가져오기
    html = wd.page_source

    bs = BeautifulSoup(html, 'html.parser')
    tag_tbody = bs.find('tbody', attrs={'id': 'store_list'})
    tags_tr = tag_tbody.findAll('tr')

    for tag_tr in tags_tr:
        strings = list(tag_tr.strings)
        name = strings[1]
        address = strings[6]
        sidogu = address.split()[:2]
        results.append((name, address)+tuple(sidogu))

wd.quit()


import socket

PORT = 8086
IP = "127.0.0.1"
MAX_OPEN_REQUESTS = 5

def process_client(clientsocket):
    print(clientsocket)
    condition = True
    while condition:
        inbox = clientsocket.recv(2048).decode("utf-8")
        print("El cliente nos dice: ", inbox)
        if inbox.lower() == "salir":
            print("saliendo")
            condition = False

        out = input("Introduzca un mensaje (nos dice el servidor): ")
        outbox = str.encode(out)
        clientsocket.send(outbox)
        if out.lower() == "salir" :
            print("saliendo")
            condition = False

    clientsocket.close()

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

hostname = IP
try:
    serversocket.bind((hostname, PORT))
    serversocket.listen(MAX_OPEN_REQUESTS)

    while True:
        print("Esperando conexión con %s %i" % (hostname, PORT))
        (clientsocket, address) = serversocket.accept()

        process_client(clientsocket)

except socket.error:
    print("Problemas using port %i. Do you have permission?" % PORT)


from flask import Flask,render_template,url_for,request,redirect
import csv
app = Flask(__name__)
print(__name__)

@app.route("/")
def hello_world():
    return render_template("index.html")

@app.route("/<string:page_name>")
def hello_index(page_name):
    return render_template(page_name)

def writing_data(data):
    with open("database.txt",mode="a") as database:
        email =data["email"]
        subject =data["subject"]
        message =data["message"]
        file=database.write(f"\n {email},{subject},{message}")

def writing_data_csv(data):
    with open("database.csv",mode="a") as database2:
        email =data["email"]
        subject =data["subject"]
        message =data["message"]
        csv_writer=csv.writer(database2,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL)
        csv_writer.writerow([email,subject,message])

@app.route("/submit_form",methods=["POST","GET"])
def submit_form():
    if request.method == "POST":
      try:
        data=request.form.to_dict()
        writing_data_csv(data)
        return redirect("thankyou.html")
      except:
          "Did not save!"
    else:
        return "something went wrong"


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

from __future__ import absolute_import, unicode_literals

# -------------------------------------------#
# author: sean lee                           #
# email: xmlee97@gmail.com                   #
#--------------------------------------------#

"""MIT License
Copyright (c) 2018 Sean
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""

import sys
if sys.version_info[0] == 2:
    reload(sys)
    sys.setdefaultencoding('utf8')

import os

_root_ = os.sep.join(os.path.dirname(os.path.abspath(__file__)).split(os.sep)[:-1])

_corpus_ = os.path.join(_root_, 'corpus')
_postag_ = os.path.join(_root_, 'postag')
_checker_ = os.path.join(_root_, 'checker')
_sentiment_ = os.path.join(_root_, 'sentiment')
_pinyin_ = os.path.join(_root_, 'pinyin')
_radical_ = os.path.join(_root_, 'radical')

root_f = lambda x: os.path.join(_root_, x)
corpus_f = lambda x: os.path.join(_corpus_, x)

postag_f = lambda x: os.path.join(_postag_, x)
checker_f = lambda x: os.path.join(_checker_, x)
sentiment_f = lambda x: os.path.join(_sentiment_, x)
pinyin_f = lambda x: os.path.join(_pinyin_, x)
radical_f = lambda x: os.path.join(_radical_, x)

postag = {
    'corpus': {
        'dag': corpus_f('word_freq_tag'),
        'seg': corpus_f('seg'),
        'tag': corpus_f('tag')
    },
    'model': {
        'dag': postag_f('postag.pickle'),
        'seg': postag_f('seg.hmm.pickle'),
        'tag': postag_f('tag.hmm.pickle')
    }
}

pinyin = {
    'corpus': {
        'pinyin': corpus_f('pinyin'),
    },
    'model': {
        'pinyin': pinyin_f('pinyin.pickle')
    }
}

checker = {
    'corpus': {
        'checker': checker_f('words.txt'),
    },
}

sentiment = {
    'corpus': {
        'pos': corpus_f(os.path.join('sentiment', 'pos.txt')),
        'neg': corpus_f(os.path.join('sentiment', 'neg.txt')),
    },
    'model': {
        'sentiment': sentiment_f('sentiment.pickle')
    }
}

radical = {
    'corpus': {
        'radical': corpus_f('radical'),
    },
    'model': {
        'radical': radical_f('radical.pickle')
    }
}

stopword = {
    'corpus': {
        'stopword': root_f('stopword.txt'),
    }
}


from django import template

from apps.core.utils import get_internal_link

register = template.Library()

@register.simple_tag(takes_context=True)
def internal_link(context, name, text=None, permission=None):
    if permission:
        if permission == 'login_required':
            if not context.request.user.is_authenticated():
                return ''
        else:
            if not context.request.user.has_perm(permission):
                return ''

    return get_internal_link(name, text)

@register.simple_tag(takes_context=True)
def admin_link(context, text='Admin'):
    if not context.request.user.is_superuser:
        return ''

    return get_internal_link('admin:index', text)

@register.simple_tag(takes_context=True)
def login_link(context):
    if context.request.user.is_authenticated():
        return get_internal_link('logout', 'Logout')
    else:
        return get_internal_link('login', 'Login')

@register.simple_tag()
def full_name(user):
    if hasattr(user, 'first_name') and hasattr(user, 'last_name') and user.first_name and user.last_name:
        return '%s %s' % (user.first_name, user.last_name)
    else:
        return user.username


import json
import boto3

def lambda_handler(event, context):
    #Sending messages to the queue

    client = boto3.client('sqs', endpoint_url='https://sqs.us-east-1.amazonaws.com:443') #used for VPC endpoints. For FIFO queues, you will need to enable Content-Based Deduplication, or  provide this as an extra argument

    #Config
    i=0
    limit = 1000

    while i < limit:
        response = client.send_message(
            QueueUrl='<Enter your Queue URL>',
            MessageBody='this is message ' + str(i)
        )
        print(
            "RequestId: " + response['ResponseMetadata']['HTTPHeaders']['x-amzn-requestid'] + " | " +
            "TimeStamp: " + response['ResponseMetadata']['HTTPHeaders']['date'] + " | "
            "MessageId: " + response['MessageId']
        )
        i += 1


import math
import logging
import time

import cv2
import numpy as np

from fishy.engine.fullautofisher.engine import FullAuto
from pynput import keyboard, mouse

from fishy.helper import hotkey
from fishy.helper.config import config
from fishy.helper.helper import wait_until
from fishy.helper.hotkey import Key

mse = mouse.Controller()
kb = keyboard.Controller()

offset = 0

def get_crop_coods(window):
    img = window.get_capture()
    img = cv2.inRange(img, 0, 1)

    cnt, h = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    """
    code from https://stackoverflow.com/a/45770227/4512396
    """
    for i in range(len(cnt)):
        area = cv2.contourArea(cnt[i])
        if 5000 < area < 100000:
            mask = np.zeros_like(img)
            cv2.drawContours(mask, cnt, i, 255, -1)
            x, y, w, h = cv2.boundingRect(cnt[i])
            return x, y + offset, x + w, y + h - offset

def _update_factor(key, value):
    full_auto_factors = config.get("full_auto_factors", {})
    full_auto_factors[key] = value
    config.set("full_auto_factors", full_auto_factors)

def _get_factor(key):
    return config.get("full_auto_factors", {}).get(key)

class Calibrate:
    def __init__(self, engine: FullAuto):
        self._callibrate_state = -1
        self.engine = engine

    # region getters
    @property
    def crop(self):
        return _get_factor("crop")

    @property
    def move_factor(self):
        return _get_factor("move_factor")

    @property
    def rot_factor(self):
        return _get_factor("rot_factor")

    @property
    def time_to_reach_bottom(self):
        return _get_factor("time_to_reach_bottom")

    # endregion

    def all_callibrated(self):
        return self.crop is not None and self.move_factor is not None and self.rot_factor is not None

    def toggle_show(self):
        self.engine.show_crop = not self.engine.show_crop

    def update_crop(self, enable_crop=True):
        if enable_crop:
            self.engine.show_crop = True
        crop = get_crop_coods(self.engine.window)
        _update_factor("crop", crop)
        self.engine.window.crop = crop

    def walk_calibrate(self):
        walking_time = 3

        coods = self.engine.get_coods()
        if coods is None:
            return

        x1, y1, rot1 = coods

        kb.press('w')
        time.sleep(walking_time)
        kb.release('w')
        time.sleep(0.5)

        coods = self.engine.get_coods()
        if coods is None:
            return
        x2, y2, rot2 = coods

        move_factor = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) / walking_time
        _update_factor("move_factor", move_factor)
        logging.info("done")

    def rotate_calibrate(self):
        rotate_times = 50

        coods = self.engine.get_coods()
        if coods is None:
            return
        _, _, rot2 = coods

        for _ in range(rotate_times):
            mse.move(FullAuto.rotate_by, 0)
            time.sleep(0.05)

        coods = self.engine.get_coods()
        if coods is None:
            return
        x3, y3, rot3 = coods

        if rot3 > rot2:
            rot3 -= 360

        rot_factor = (rot3 - rot2) / rotate_times
        _update_factor("rot_factor", rot_factor)
        logging.info("done")

    def time_to_reach_bottom_callibrate(self):
        self._callibrate_state = 0

        def _f8_pressed():
            self._callibrate_state += 1

        logging.info("look straight up and press f8")
        hotkey.set_hotkey(Key.F8, _f8_pressed)

        wait_until(lambda: self._callibrate_state == 1)

        logging.info("as soon as you look on the floor, press f8 again")

        y_cal_start_time = time.time()
        while self._callibrate_state == 1:
            mse.move(0, FullAuto.rotate_by)
            time.sleep(0.05)
        hotkey.free_key(Key.F8)

        time_to_reach_bottom = time.time() - y_cal_start_time
        _update_factor("time_to_reach_bottom", time_to_reach_bottom)
        logging.info("done")


from django.contrib import admin
from blog.models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):

    date_hierarchy = 'pub_date'

    list_filter = ('pub_date',)

    search_fields = ('title',)

    # fieldsets = (
    #     (None,{
    #         'fields':(
    #             'title','author','status',

    #         )
    #     }),
    # )

    list_display = (
        ('title',
         'slug',
         'author',
         'status',
         'pub_date',
         'created_date',
         'updated_date',
        )
    )

    prepopulated_fields = {'slug':('title',)}

    def make_published(self, request, queryset):
        row_updated = queryset.update(status='published')
        if row_updated == 'published':
            message_bit = '1 message was'
        else:
            message_bit = '%s post were' % row_updated
        self.message_user(request,
                          '%s successfully marked as published'
                         % message_bit)

    def make_drafted(self, request, queryset):
        row_updated = queryset.update(status='draft')
        if row_updated == 'draft':
            message_bit = '1 message was'
        else:
            message_bit = '%s post were' % row_updated
        self.message_user(request,
                          '%s successfully marked as published'
                         % message_bit)

    make_published.short_description = 'Mark Select Published'
    make_drafted.short_description = 'Mark Select Drafted'

    actions = [make_published, make_drafted]


import argparse
import asyncio
import logging
import sys

import yaml
from senor_octopus import __version__
from senor_octopus.graph import build_dag
from senor_octopus.lib import render_dag
from senor_octopus.scheduler import Scheduler

__author__ = "Beto Dealmeida"
__copyright__ = "Beto Dealmeida"
__license__ = "MIT"

_logger = logging.getLogger(__name__)

def parse_args(args):
    """Parse command line parameters

    Args:
      args (List[str]): command line parameters as list of strings
          (for example  ``["--help"]``).

    Returns:
      :obj:`argparse.Namespace`: command line parameters namespace
    """
    parser = argparse.ArgumentParser(description="Schedule pipelines")
    parser.add_argument(
        "--version",
        action="version",
        version="senor-octopus {ver}".format(ver=__version__),
    )
    parser.add_argument(
        dest="f",
        help="Location of the config file",
        type=str,
        metavar="PATH",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="loglevel",
        help="set loglevel to INFO",
        action="store_const",
        const=logging.INFO,
    )
    parser.add_argument(
        "-vv",
        "--very-verbose",
        dest="loglevel",
        help="set loglevel to DEBUG",
        action="store_const",
        const=logging.DEBUG,
    )
    return parser.parse_args(args)

def setup_logging(loglevel):
    logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
    logging.basicConfig(
        level=loglevel,
        stream=sys.stdout,
        format=logformat,
        datefmt="%Y-%m-%d %H:%M:%S",
    )

async def main(args):
    args = parse_args(args)
    setup_logging(args.loglevel)

    _logger.info("Reading configuration")
    with open(args.f) as fp:
        config = yaml.load(fp)
    _logger.info("Building DAG")
    dag = build_dag(config)
    _logger.info("\n%s", render_dag(dag))

    _logger.info("Running Sr. Octopus")
    scheduler = Scheduler(dag)
    try:
        await scheduler.run()
    except asyncio.CancelledError:
        _logger.info("Canceled")
        scheduler.cancel()

    _logger.info("Done")

def run():
    try:
        asyncio.run(main(sys.argv[1:]))
    except KeyboardInterrupt:
        _logger.info("Stopping Sr. Octopus")

if __name__ == "__main__":
    run()


g = lambda x,y : x*y
print(g(2,3))

print((lambda x,y: x*y)(3,4))

#map
def sqrt(x):
    x=x*x
    return x

a=map(sqrt, [1,2,3,4,5,6,7,8,9,10])
print(a)   #map자체로는 출력안됨
#for문을 쓰거나 lsit 로 형전환 해야함

for item in map(sqrt, [1,2,3,4,5,6,7,8,9,10]):
    print(item)

for item in map(lambda x:x*x, [1,2,3,4,5,6,7,8,9,10]):
    print(item)

a=list(map(lambda x:x*x, [1,2,3,4,5,6,7,8,9,10]))
print(a)

"""
파이썬의 정렬함수
1.list - 자기순서가 바뀜
2.내장함수 sored - 정렬된 데이터를 반환
"""

a=[5,4,7,8,1,3,10,9,2,6]
b=a[:] #하드카피(새로운 객체 만들고 a값 복사)
a.sort()
print(a)
print(b)
c=sorted(b)
print("original : ", b)
print("sorted : ", c)

mya=[5,4,-7,8,1,-3,10,9,-2,6]
b=mya[:]
a.sort(key=sqrt) #음수값에 관련없이 정렬하고 싶을 때
print(a)
print(b)
c=sorted(b, key=sqrt)
c=sorted(b, key=lambda item:item*item)  #item이라는 이름을 줌
print("original : ", b)
print("sorted : ", c)

students=[
    {"name":"강만수", "kor":90, "eng":80},
    {"name":"김정하", "kor":80, "eng":60},
    {"name":"이민호", "kor":70, "eng":70},
    {"name":"김성훈", "kor":99, "eng":90},
    {"name":"강기정", "kor":95, "eng":70}
]

a=sorted(students, key=lambda item:item['name'], reverse=True) #reverse=True 내림차순 정렬
print(a)

a=["pen","water","desktop","snack","book"]
#filter(조건식, 리스트) 리스트에서 조건을 만족하는 요소만 추출한다
for item in filter(lambda x:len(x) >=5, a):
    print(item)


# Copyright © 2020-2021. All rights reserved.
# Authors: Vitalii Babenko
# Contacts: vbabenko2191@gmail.com

import os
import json
import numpy as np
import pandas as pd
from CalculateImageFeatures import get_all_features

def tree_prediction(tree, img_f):
    tree = pd.DataFrame(tree)
    index = 0
    leaf = 1
    flag = False
    y_hat = -1
    while not flag:
        node = tree.loc[index]
        node_X = img_f[node['feature']]
        if node['side'] == 1:
            if node_X < node['threshold']:
                y_hat = 0
            else:
                y_hat = 1
        else:
            if node_X < node['threshold']:
                y_hat = 1
            else:
                y_hat = 0
        if np.where((tree['previous_leaf'] == leaf) & (tree['previous_direction']) == y_hat + 1)[0].size > 0:
            index = np.where((tree['previous_leaf'] == leaf) & (
                tree['previous_direction'] == y_hat + 1))[0][0]
            leaf = tree.loc[index]['leaf_number']
        else:
            flag = True
    return y_hat

def forest_prediction(sensor_type, img_f):
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Classifiers/GeneticForests', sensor_type + '.json')) as f:
        forest = json.load(f)
    y_proba = 0
    for obj in forest:
        tree = obj['tree']
        y_pred = tree_prediction(tree, img_f)
        y_proba += y_pred * obj['weight']
    if y_proba < 0.5:
        y_hat = 0
    else:
        y_hat = 1
    if y_hat == 0:
        y_proba = 1 - y_proba
    return y_proba, y_hat

def get_mean_signs(sensor_type, img_f):
    # if task_type == 1:
    if sensor_type == 'Convex':
        feature1, feature2, feature3 = 'gm_wp_eq', 'horglrlm1l_entropy_orig', 'horglrlm2l_cov_eq'
        threshold1, threshold2, threshold3 = 0.558094, 4.181608, 2.276130
        value1, value2, value3 = img_f[feature1], img_f[feature2], img_f[feature3]
        if value1 < threshold1:
            res1 = 'Печень в норме'
        else:
            res1 = 'Печень не в норме'
        if value2 < threshold2:
            res2 = 'Печень в норме'
        else:
            res2 = 'Печень не в норме'
        if value3 < threshold3:
            res3 = 'Печень не в норме'
        else:
            res3 = 'Печень в норме'
    elif sensor_type == 'Linear':
        feature1, feature2, feature3 = 'gm_wp_eq', 'horglrlm2l_entropy_eq', 'horglrlm2l_entropy_orig'
        threshold1, threshold2, threshold3 = 0.543821, 3.788145, 3.718229
        value1, value2, value3 = img_f[feature1], img_f[feature2], img_f[feature3]
        if value1 < threshold1:
            res1 = 'Печень в норме'
        else:
            res1 = 'Печень не в норме'
        if value2 < threshold2:
            res2 = 'Печень в норме'
        else:
            res2 = 'Печень не в норме'
        if value3 < threshold3:
            res3 = 'Печень не в норме'
        else:
            res3 = 'Печень в норме'
    elif sensor_type == 'Reinforced':
        feature1, feature2, feature3 = 'gm_wp_eq', 'gm_lbp255_eq', 'gm_lbp159_eq'
        threshold1, threshold2, threshold3 = 0.436147, 0.044118, 0.005618
        value1, value2, value3 = img_f[feature1], img_f[feature2], img_f[feature3]
        if value1 < threshold1:
            res1 = 'Печень в норме'
        else:
            res1 = 'Печень не в норме'
        if value2 < threshold2:
            res2 = 'Печень в норме'
        else:
            res2 = 'Печень не в норме'
        if value3 < threshold3:
            res3 = 'Печень в норме'
        else:
            res3 = 'Печень не в норме'
    else:
        feature1, feature2, feature3 = '', '', ''
        threshold1, threshold2, threshold3 = 0, 0, 0
        value1, value2, value3 = 0, 0, 0
        res1, res2, res3 = 0, 0, 0
    # elif task_type == 2:
    #     feature1, feature2, feature3 = '', '', ''
    #     threshold1, threshold2, threshold3 = 0, 0, 0
    #     value1, value2, value3 = 0, 0, 0
    #     res1, res2, res3 = 0, 0, 0
    # else:
    #     feature1, feature2, feature3 = '', '', ''
    #     threshold1, threshold2, threshold3 = 0, 0, 0
    #     value1, value2, value3 = 0, 0, 0
    #     res1, res2, res3 = 0, 0, 0
    return [{'feature': feature1, 'threshold': threshold1, 'value': value1, 'result': res1},
            {'feature': feature2, 'threshold': threshold2,
                'value': value2, 'result': res2},
            {'feature': feature3, 'threshold': threshold3, 'value': value3, 'result': res3}]

def get_classification_results(parameters):
    # тип датчика
    sensor_type = parameters['sensor_type']
    # task_type: 1 - норма/патология, 2 - стадия фиброза
    task_type = parameters['task_type']
    # настройки для получения текстурных признаков
    settings = parameters['settings']
    diff_indices = settings['diff_indices']  # оттенки серого для бинаризации
    # структура моделей пространственной развертки
    ss_list = settings['ss_list']
    sw_list = settings['sw_list']  # структура моделей скользящего окна
    # лучшая градация серого для классификации "норма-патология"
    best_grad = settings['best_grad']
    best_d = settings['best_d']  # лучшая диагональ
    best_p = settings['best_p']  # лучший перпендикуляр к лучшей диагонали
    best_pairs = settings['best_pairs']  # лучшие пары оттенков серого
    # текстурные матрицы
    texture_matrices = parameters['texture_matrices']
    # расчёт признаков
    img_f = {}
    image_type = 'orig'
    gm = texture_matrices[image_type]['gm']
    glcm0, glcm90 = texture_matrices[image_type]['glcm0'], texture_matrices[image_type]['glcm90']
    glrlm0, glrlm90 = texture_matrices[image_type]['glrlm0'], texture_matrices[image_type]['glrlm90']
    img_f = get_all_features(img_f, image_type, gm, glcm0, glcm90, glrlm0, glrlm90,
                             diff_indices['indices'], ss_list['structure'], sw_list['structure'],
                             best_grad, best_d, best_p, best_pairs)
    image_type = 'eq'
    gm = texture_matrices[image_type]['gm']
    glcm0, glcm90 = texture_matrices[image_type]['glcm0'], texture_matrices[image_type]['glcm90']
    glrlm0, glrlm90 = texture_matrices[image_type]['glrlm0'], texture_matrices[image_type]['glrlm90']
    img_f = get_all_features(img_f, image_type, gm, glcm0, glcm90, glrlm0, glrlm90,
                             diff_indices['indices'], ss_list['structure'], sw_list['structure'],
                             best_grad, best_d, best_p, best_pairs)

    # Генетический лес
    gf_prob, gf_class = forest_prediction(sensor_type, img_f)
    gf_result = 'Печень в норме' if gf_class == 0 else 'Печень не в норме'

    # Пороги трёх наилучших признаков
    mean_signs = get_mean_signs(sensor_type, img_f)

    return {'gf_result': gf_result, 'gf_probability': round(gf_prob * 100, 1), 'mean_signs': mean_signs}


# https://en.wikipedia.org/wiki/Eulerian_path#Hierholzer's_algorithm
# https://www.geeksforgeeks.org/hierholzers-algorithm-directed-graph/
class Solution:
    def validArrangement(self, pairs):
        g = {}
        degree = {}
        for u, v in pairs:
            if u not in g:
                g[u] = []
            g[u].append(v)
            degree[u] = degree.get(u, 0) + 1
            degree[v] = degree.get(v, 0) - 1
        x = pairs[0][0]
        for v in degree:
            if degree[v] == 1:
                x = v
                break
        stack = []

        def backtrack(u):
            while u in g and g[u]:
                backtrack(g[u].pop())
            stack.append(u)

        backtrack(x)
        return [[stack[i], stack[i - 1]] for i in range(len(stack) - 1, 0, -1)]

s = Solution()
# print(s.validArrangement(
#     [[5, 13], [10, 6], [11, 3], [15, 19], [16, 19], [1, 10], [19, 11], [4, 16], [19, 9], [5, 11], [5, 6], [13, 5],
#      [13, 9], [9, 15], [11, 16], [6, 9], [9, 13], [3, 1], [16, 5], [6, 5]]))
print(s.validArrangement([[5, 1], [4, 5], [11, 9], [9, 4]]))
print(s.validArrangement([[1, 3], [3, 2], [2, 1]]))
print(s.validArrangement([[1, 2], [1, 3], [2, 1]]))


from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from .import views
from .views import *
#from Buffet import views
from django.contrib.auth.views import LoginView, LogoutView

app_name = 'Buffet'

urlpatterns = [
    path('', home_page),
    path('menu/', menu),
    path('reserva/', reserva),
    path('register/', register),
    path('login/', LoginView.as_view(template_name = 'login.html')),
    path('logout/', LogoutView.as_view(template_name = 'logout.html')),
    path('producto/<slug>/', ItemDetailView.as_view(), name = 'product'),
    path('order_summary/', OrderSummaryView.as_view(), name = 'order_summary'),
    path('grilla/', HomeView.as_view()),
    path('add_to_cart/<slug>/', add_to_cart, name = 'add_to_cart'),
    path('remove_cart/<slug>/', remove_cart, name = 'remove_cart')

]


from django.conf.urls import url
from api.views import wiki_api
urlpatterns = [
            # url(r'assets/$', assets_api.asset_list),
            # url(r'assets/(?P<id>[0-9]+)/$', assets_api.asset_detail),
            # url(r'assets/info/(?P<id>[0-9]+)/$', assets_api.asset_info),
            # url(r'service/$', assets_api.service_list),
            # url(r'service/(?P<id>[0-9]+)/$', assets_api.service_detail),
            # url(r'project/$', assets_api.project_list),
            # url(r'project/(?P<id>[0-9]+)/$', assets_api.project_detail),
            # url(r'group/$', assets_api.group_list),
            # url(r'group/(?P<id>[0-9]+)/$',assets_api.group_detail),
            # url(r'user/$', users_api.user_list),
            # url(r'user/(?P<id>[0-9]+)/$',users_api.user_detail),
            # url(r'zone/$', assets_api.zone_list),
            # url(r'zone/(?P<id>[0-9]+)/$',assets_api.zone_detail),
            # url(r'line/$', assets_api.line_list),
            # url(r'line/(?P<id>[0-9]+)/$',assets_api.line_detail),
            # url(r'raid/$', assets_api.raid_list),
            # url(r'raid/(?P<id>[0-9]+)/$',assets_api.raid_detail),
            # url(r'server/$', assets_api.asset_server_list),
            # url(r'server/(?P<id>[0-9]+)/$', assets_api.asset_server_detail),
            # url(r'net/$', assets_api.asset_net_list),
            # url(r'net/(?P<id>[0-9]+)/$', assets_api.asset_net_detail),
            # url(r'cron/$', cron_api.cron_list),
            # url(r'cron/(?P<id>[0-9]+)/$', cron_api.cron_detail),
            # url(r'deploy/$', deploy_api.deploy_list),
            # url(r'deploy/(?P<id>[0-9]+)/$', deploy_api.deploy_detail),
            # url(r'playbook/$', ansible_api.playbook_list),
            # url(r'playbook/(?P<id>[0-9]+)/$', ansible_api.playbook_detail),
            # url(r'inventory/(?P<id>[0-9]+)/$', ansible_api.inventory_detail),
            # url(r'host/vars/(?P<id>[0-9]+)/$', ansible_api.ansible_host_vars),
            # url(r'logs/assets/(?P<id>[0-9]+)/$', assets_api.assetsLog_detail),
            # url(r'logs/cron/(?P<id>[0-9]+)/$', cron_api.cronLogsdetail),
            # url(r'logs/ansible/model/(?P<id>[0-9]+)/$', ansible_api.modelLogsdetail),
            # url(r'logs/ansible/playbook/(?P<id>[0-9]+)/$', ansible_api.playbookLogsdetail),
            # url(r'logs/deploy/(?P<id>[0-9]+)/$', deploy_api.deployLogs_detail),
            # url(r'logs/search/model/$', logs_api.AnsibleModelLogsList),
            # url(r'logs/search/playbook/$', logs_api.AnsiblePlayBookLogsList),
            # url(r'logs/sql/(?P<id>[0-9]+)/$', db_api.sql_exec_logs),
            # url(r'inc/config/$', db_api.inc_list),
            # url(r'inc/config/(?P<id>[0-9]+)/$', db_api.inc_detail),
            # url(r'db/config/$', db_api.db_list),
            # url(r'db/config/(?P<id>[0-9]+)/$', db_api.db_detail),
            # url(r'db/status/(?P<id>[0-9]+)/$', db_api.db_status),
            # url(r'db/org/(?P<id>[0-9]+)/$', db_api.db_org),
            # url(r'orders/(?P<id>[0-9]+)/$', orders_api.order_detail),
            # url(r'sql/custom/$', db_api.sql_custom_list),
            # url(r'sql/custom/(?P<id>[0-9]+)/$', db_api.sql_custom_detail),
            url(r'wiki/tag/$', wiki_api.tag_list),
            url(r'wiki/tag/(?P<id>[0-9]+)/$', wiki_api.tag_detail),
            url(r'wiki/category/$', wiki_api.category_list),
            url(r'wiki/category/(?P<id>[0-9]+)/$', wiki_api.category_detail),
            url(r'wiki/archive/(?P<id>[0-9]+)/$', wiki_api.archive_detail),
            # url(r'file/upload/$', files_api.upload_file_list),
            # url(r'file/upload/(?P<id>[0-9]+)/$', files_api.upload_file_detail),
            # url(r'file/download/$', files_api.download_file_list),
            # url(r'file/download/(?P<id>[0-9]+)/$', files_api.download_file_detail),
            # url(r'task/crontab/$', task_api.task_crontab_list),
            # url(r'task/crontab/(?P<id>[0-9]+)/$', task_api.task_crontab_detail),
    ]


from esser.validators import EsserValidator
from esser.constants import AGGREGATE_KEY_DELIMITER
from esser.exceptions import EventValidationException

class BaseEvent(object):
    """Base Event class."""

    def __init__(self):
        """
        Initialise the validator for the event based on schema.

        A valid Event class should have Event.schema
        """
        self.validator = EsserValidator(
            self.schema, event=self
        )

    @property
    def event_name(self):
        """Event name by default is the class name."""
        return self.__class__.__name__

    def get_aggregate_key(self):
        """Increment version of the event for the aggregate."""
        version = self.entity.get_last_aggregate_version() + 1
        return '{aggregate_id}{delimiter}{version}'.format(
            aggregate_id=self.entity.aggregate_id,
            delimiter=AGGREGATE_KEY_DELIMITER,
            version=version
        )

    def attach_entity(self, entity):
        """Allow entity to be attached to the event."""
        setattr(self, 'entity', entity)
        setattr(self.validator, 'aggregate', entity)

    def persist(self, attrs):
        return self.entity.repository.persist(
            aggregate_id=self.get_aggregate_key(),
            event_type=self.event_name,
            attrs=attrs
        )

    def save(self, attrs):
        """Validate event input before saving."""
        if not self.validator.validate(attrs):
            raise EventValidationException(
                errors=self.validator.errors
            )
        return self.persist(attrs)

class CreateEvent(BaseEvent):
    """Event for creating an entity."""

    def save(self, attrs):
        """Generate aggregate id using uuid."""
        aggregate_id = self.entity.generate_new_guid()
        self.entity.aggregate_id = aggregate_id
        return super(CreateEvent, self).save(attrs)

    def get_aggregate_key(self):
        return '%s:%s' % (
            self.entity.aggregate_id, self.entity.INITIAL_VERSION
        )

class DeleteEvent(BaseEvent):

    @property
    def event_name(self):
        return 'Deleted'


'''
This is the ui interface for phase retrieval.
Created by Dan on 05/04/2017 (Happy Youth's Day!)
'''
import sys
from PyQt4 import QtGui, QtCore
import os

def import_module(path):
    filename = os.path.basename(path)
    return __import__(path, globals(), locals(), [filename], 0)

class _UI(object):
    '''
    Update log and brief instructions.
    '''
    def __init__(self,design_path):
        # initialize the UI.
        self._app = QtGui.QApplication(sys.argv)
        self._window = QtGui.QWidget()
        self._window.closeEvent = self.shutDown

        ui_module = import_module(design_path)
        self._ui = ui_module.Ui_Form()
        try:
            self._ui.setupUi(self._window)
        except:
            self._window = QtGui.QMainWindow()
            self._ui.setupUi(self._window)

        self._window.show()
        self._app.exec_()

    def shutDown(self, event):
        '''
        shut down the UI
        '''
        self._app.quit()


'''
USACO 2019 February Contest (Silver)
Problem 1: Sleepy Cow Herding
By Giantpizzahead

Let's go! :)
'''
import bisect

def smallest(cows):
    num_cows = len(cows)
    least = num_cows
    for cow_index, cow in enumerate(cows):
        target = cow + num_cows - 1
        # print("Target:", target)
        target_index = bisect.bisect_right(cows, target)
        # print("Index:", target_index)
        num_moves = num_cows - (target_index - cow_index)
        # print("Num moves:", num_moves)
        if num_moves == 1:
            # Special case
            need_to_add = True
            last = cows[cow_index] - 1
            for cow in cows[cow_index:target_index]:
                if abs(cow - last) == 1:
                    last = cow
                else:
                    need_to_add = False
                    break
            if need_to_add:
                # print("Added!")
                num_moves += 1
        if num_moves < least:
            least = num_moves
    return least

def longest(cows):
    # Error has something to do with this.
    num_moves = 0
    left_dist = 9999999999
    left_insert = 0
    prev = cows[1]
    for ci, cow in enumerate(cows[2:]):
        if cow == prev + 1:
            prev = cow
        else:
            left_dist = prev - cows[0] + 1
            left_insert = ci + 2
            break
    right_dist = 9999999999
    right_insert = 0
    prev = cows[-2]
    for ci, cow in enumerate(cows[-3::-1]):
        if cow == prev - 1:
            prev = cow
        else:
            right_dist = cows[-1] - prev + 1
            right_insert = ci - 2
            break
    print("Left", left_dist, left_insert)
    print("Right", right_dist, right_insert)
    if left_dist < right_dist:
        cows.insert(left_insert, cows[0] + left_dist)
        cows.pop(0)
    else:
        cows.insert(right_insert, cows[-1] - right_dist)
        cows.pop()
    num_moves += 1
    print(cows)
    num_moves += (cows[-1] - cows[0]) - (len(cows) - 1)
    if left_dist == right_dist and left_dist == 9999999999:
        num_moves = 0
    return num_moves

def main():
    # Input parsing
    cows = []
    with open("herding.in", 'r') as input:
        num_cows = int(input.readline())
        for i in range(num_cows):
            cows.append(int(input.readline()))
    cows = sorted(cows)
    least = smallest(cows)
    most = longest(cows)
    with open("herding.out", 'w') as output:
        output.write(str(least) + "\n" + str(most) + "\n")
    # print(least, most)

main()

USACO/Archived Contests/February 2019 (Silver)/herding.py


# Copyright 2019 NREL

# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

def nudge_outward(x):
    """
    Avoid numerical issue in grid data by sligly expanding input x,y

    Args:
        x (np.arraym float): Vector to be slightly expanded
    """
    nudge_val = 0.001
    min_x = np.min(x)
    max_x = np.max(x)
    x = np.where(x==min_x, min_x-nudge_val, x)
    x = np.where(x==max_x, max_x+nudge_val, x)
    return x

class _CutPlane():
    def __init__(self, flow_data, x1='x', x2='y', x3_value=None):
        """
        Initialize CutPlane object. Used to extract a 2D plane from a
        3D vectoral velocity field

        Args:
            flow_data (np.array): 3D vector field of velocity data
            x1 (str, optional): first dimension. Defaults to 'x'.
            x2 (str, optional): second dimension. Defaults to 'y'.
            x3_value (str, optional): third dimension. Defaults to None.
        """
        # Assign the axis names
        self.x1_name = x1
        self.x2_name = x2
        #TODO: if it will be assumed that x3 is one of x, y, or z that is x1 and x2,
        #       then we should verify that x1 and x2 are one of x, y, or z
        self.x3_name = [x3 for x3 in ['x', 'y', 'z'] if x3 not in [x1, x2]][0]

        # Get x1, x2 and x3 arrays
        x1_array = getattr(flow_data, self.x1_name)
        x2_array = getattr(flow_data, self.x2_name)
        x3_array = getattr(flow_data, self.x3_name)

        search_values = np.array(sorted(np.unique(x3_array)))
        nearest_idx = (np.abs(search_values - x3_value)).argmin()
        nearest_value = search_values[nearest_idx]
        print('Nearest value in %s to %.2f is %.2f' %
              (self.x3_name, x3_value, nearest_value))

        # Select down the data
        x3_select_mask = x3_array == nearest_value

        # Store the un-interpolated input arrays at this slice
        self.x1_in = x1_array[x3_select_mask]
        self.x2_in = x2_array[x3_select_mask]
        self.u_in = flow_data.u[x3_select_mask]
        self.v_in = flow_data.v[x3_select_mask]
        self.w_in = flow_data.w[x3_select_mask]

        # Initially, x1_lin, x2_lin are unique values of input
        self.x1_lin = np.unique(self.x1_in)
        self.x2_lin = np.unique(self.x2_in)

        # Save the resolution as the number of unique points in x1 and x2
        self.resolution = (len(np.unique(self.x1_lin)),
                           len(np.unique(self.x2_lin)))

        # Make initial meshing
        self._remesh()

    def _remesh(self):

        # Mesh and interpolate u, v and w
        self.x1_mesh, self.x2_mesh = np.meshgrid(self.x1_lin, self.x2_lin)
        self.u_mesh = griddata(
            np.column_stack([nudge_outward(self.x1_in), nudge_outward(self.x2_in)]),
            self.u_in, (self.x1_mesh.flatten(), self.x2_mesh.flatten()),
            method='cubic')
        self.v_mesh = griddata(
            np.column_stack([nudge_outward(self.x1_in), nudge_outward(self.x2_in)]),
            self.v_in, (self.x1_mesh.flatten(), self.x2_mesh.flatten()),
            method='cubic')
        self.w_mesh = griddata(
            np.column_stack([nudge_outward(self.x1_in), nudge_outward(self.x2_in)]),
            self.w_in, (self.x1_mesh.flatten(), self.x2_mesh.flatten()),
            method='cubic')

        # Save flat vectors
        self.x1_flat = self.x1_mesh.flatten()
        self.x2_flat = self.x2_mesh.flatten()

        # Save u-cubed
        self.u_cubed = self.u_mesh**3

# Define horizontal subclass
class HorPlane(_CutPlane):
    """
    Subclass of _CutPlane. Shortcut to extracting a horizontal plane.
    """

    def __init__(self, flow_data, z_value):
        """
        Initialize horizontal CutPlane

        Args:
            flow_data (np.array): 3D vector field of velocity data
            z_value (float): vertical position through which to slice
        """
        # Set up call super
        super().__init__(flow_data, x1='x', x2='y', x3_value=z_value)

# Define cross plane subclass
class CrossPlane(_CutPlane):
    """
    Subclass of _CutPlane. Shortcut to extracting a cross-stream plane.
    """

    def __init__(self, flow_data, x_value):
        """
        Initialize cross-stream CutPlane

        Args:
            flow_data (np.array): 3D vector field of velocity data
            x_value (float): streamwise position through which to slice
        """
        # Set up call super
        super().__init__(flow_data, x1='y', x2='z', x3_value=x_value)

# Define cross plane subclass
class VertPlane(_CutPlane):
    """
    Subclass of _CutPlane. Shortcut to extracting a streamwise-vertical plane.
    """

    def __init__(self, flow_data, y_value):
        """
        Initialize streamwise-vertical  CutPlane

        Args:
            flow_data (np.array): 3D vector field of velocity data
            y_value (float): spanwise position through which to slice
        """
        # Set up call super
        super().__init__(flow_data, x1='x', x2='z', x3_value=y_value)

## Modification functions
def set_origin(cut_plane, center_x1=0.0, center_x2=0.0):
    """
    Establish the origin of a CutPlane object.

    Args:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
            plane of data.
        center_x1 (float, optional): x1-coordinate of orign.
                Defaults to 0.0.
        center_x2 (float, optional): x2-coordinate of orign.
                Defaults to 0.0.

    Returns:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
                updated plane of data.
    """
    # Store the un-interpolated input arrays at this slice
    cut_plane.x1_in = cut_plane.x1_in - center_x1
    cut_plane.x2_in = cut_plane.x2_in - center_x2
    cut_plane.x1_lin = cut_plane.x1_lin - center_x1
    cut_plane.x2_lin = cut_plane.x2_lin - center_x2

    # Remesh
    cut_plane._remesh()

    return cut_plane

def change_resolution(cut_plane, resolution=(100, 100)):
    """
    Modify default resolution of a CutPlane object.

    Args:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
            plane of data.
        resolution (tuple, optional): Desired resolution in x1 and x2.
            Defaults to (100, 100).

    Returns:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
                updated plane of data.
    """
    # Grid the data
    cut_plane.x1_lin = np.linspace(min(cut_plane.x1_in), max(cut_plane.x1_in),
                                   resolution[0])
    cut_plane.x2_lin = np.linspace(min(cut_plane.x2_in), max(cut_plane.x2_in),
                                   resolution[1])

    # Save the new resolution
    cut_plane.resolution = resolution

    # Redo the mesh
    cut_plane._remesh()

    # Return the cutplane
    return cut_plane

def interpolate_onto_array(cut_plane, x1_array, x2_array):
    """
    Interpolate a CutPlane object onto specified coordinate arrays.

    Args:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
            plane of data.
        x1_array (np.array): specified x1-coordinate.
        x2_array (np.array): specified x2-coordinate.

    Returns:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
                updated plane of data.
    """
    # Grid the data given array
    cut_plane.x1_lin = x1_array
    cut_plane.x2_lin = x2_array

    # Save the new resolution
    cut_plane.resolution = (len(np.unique(cut_plane.x1_lin)),
                            len(np.unique(cut_plane.x2_lin)))

    # Redo the mesh
    cut_plane._remesh()

    # Return the cutplane
    return cut_plane

def rescale_axis(cut_plane, x1_factor=1.0, x2_factor=1.0):
    """
    Stretch or compress CutPlane coordinates.

    Args:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
            plane of data.
        x1_factor (float): scaling factor for x1-coordinate.
        x2_factor (float): scaling factor for x2-coordinate.

    Returns:
        cut_plane (:py:class:`floris.tools.cut_plane._CutPlane`):
                updated plane of data.
    """
    # Store the un-interpolated input arrays at this slice
    cut_plane.x1_in = cut_plane.x1_in / x1_factor
    cut_plane.x2_in = cut_plane.x2_in / x2_factor
    cut_plane.x1_lin = cut_plane.x1_lin / x1_factor
    cut_plane.x2_lin = cut_plane.x2_lin / x2_factor

    # Remesh
    cut_plane._remesh()

    return cut_plane

def calculate_wind_speed(cross_plane, x1_loc, x2_loc, R):
    """
    Calculate effective wind speed within specified range of a point.

    Args:
        cross_plane (:py:class:`floris.tools.cut_plane.CrossPlane`):
            plane of data.
        x1_loc (float): x1-coordinate of point of interst.
        x2_loc (float): x2-coordinate of point of interst.
        R (float): radius from point of interst to consider

    Returns:
        (float): effective wind speed
    """
    # Make a distance column
    distance = np.sqrt((cross_plane.x1_flat - x1_loc)**2 +
                       (cross_plane.x2_flat - x2_loc)**2)

    # Return the mean wind speed
    return np.cbrt(np.mean(cross_plane.u_cubed[distance < R]))

def calculate_power(cross_plane,
                    x1_loc,
                    x2_loc,
                    R,
                    ws_array,
                    cp_array,
                    air_density=1.225):
    """
    Calculate maximum power available in a given cross plane.

    Args:
        cross_plane (:py:class:`floris.tools.cut_plane.CrossPlane`):
            plane of data.
        x1_loc (float): x1-coordinate of point of interst.
        x2_loc (float): x2-coordinate of point of interst.
        R (float): Radius of wind turbine rotor.
        ws_array (np.array): reference wind speed for cp curve.
        cp_array (np.array): cp curve at reference wind speeds.
        air_density (float, optional): air density. Defaults to 1.225.

    Returns:
        float: Power!
    """
    # Compute the ws
    ws = calculate_wind_speed(cross_plane, x1_loc, x2_loc, R)

    # Compute the cp
    cp_value = np.interp(ws, ws_array, cp_array)

    #Return the power
    return 0.5 * air_density * (np.pi * R**2) * cp_value * ws**3

    # def get_profile(self, R, x2_loc, resolution=100, x1_locs=None):
    #     if x1_locs is None:
    #         x1_locs = np.linspace(
    #             min(self.x1_flat), max(self.x1_flat), resolution)
    #     v_array = np.array([self.calculate_wind_speed(
    #         x1_loc, x2_loc, R) for x1_loc in x1_locs])
    #     return x1_locs, v_array)

    # def get_power_profile(self, ws_array, cp_array, rotor_radius, air_density=1.225, resolution=100, x1_locs=None):

    #     # Get the wind speed profile
    #     x1_locs, v_array = self.get_profile(resolution=resolution, x1_locs=x1_locs)

    #     # Get Cp
    #     cp_array = np.interp(v_array,ws_array,cp_array)

    #     # Return power array
    #     return x1_locs, 0.5 * air_density * (np.pi * rotor_radius**2) * cp_array * v_array**3


import asyncio
import threading
import uuid

class ThreadAbortError(Exception):
    pass

class CauldronThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        """ """

        super(CauldronThread, self).__init__(*args, **kwargs)
        self.abort = False
        self.context = None
        self.daemon = True
        self.uid = str(uuid.uuid4())
        self.command = None
        self.parser = None
        self.kwargs = None
        self.result = None
        self.response = None
        self.is_executing = False
        self.exception = None
        self.logs = []
        self._loop = None

    def run(self):
        """ """

        async def run_command():
            try:
                self.result = self.command(
                    context=self.context,
                    **self.kwargs
                )
            except Exception as error:
                self.exception = error
                print(error)
                self.context.response.fail(
                    code='COMMAND_EXECUTION_ERROR',
                    message='Failed to execute command due to internal error',
                    error=error
                ).console(
                    whitespace=1
                )
            # self._loop.stop()

        self._loop = asyncio.new_event_loop()
        # self._loop.call_soon(run_command)
        # self._loop.run_forever()
        self._loop.run_until_complete(run_command())
        self._loop.close()
        self._loop = None

    def abort_running(self) -> bool:
        """
        Executes a hard abort by shutting down the event loop in this thread
        in which the running command was operating. This is carried out using
        the asyncio library to prevent the stopped execution from destabilizing
        the Python environment.
        """

        if not self._loop:
            return False

        try:
            self._loop.stop()
            return True
        except Exception:
            return False

def abort_thread():
    """
    This function checks to see if the user has indicated that they want the
    currently running execution to stop prematurely by marking the running
    thread as aborted. It only applies to operations that are run within
    CauldronThreads and not the main thread.

    :return:
    """

    thread = threading.current_thread()

    if not isinstance(thread, CauldronThread):
        return

    if thread.is_executing and thread.abort:
        raise ThreadAbortError('User Aborted Execution')


"""
1664. Ways to Make a Fair Array

You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.

For example, if nums = [6,1,7,4,1]:

Choosing to remove index 1 results in nums = [6,7,4,1].
Choosing to remove index 2 results in nums = [6,1,4,1].
Choosing to remove index 4 results in nums = [6,1,7,4].
An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.

Return the number of indices that you could choose such that after the removal, nums is fair.

Example 1:

Input: nums = [2,1,6,4]
Output: 1
Explanation:
Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
There is 1 index that you can remove to make nums fair.
Example 2:

Input: nums = [1,1,1]
Output: 3
Explanation: You can remove any index and the remaining array is fair.
Example 3:

Input: nums = [1,2,3]
Output: 0
Explanation: You cannot make a fair array after removing any index.

Constraints:

1 <= nums.length <= 105
1 <= nums[i] <= 104

"""

class WaysToFairArray:

    def doit_twopointer(self, nums: list) -> int:
        def waysToBalance(self, nums: list) -> int:
            n = len(nums)
            evens = [nums[0]] * n
            odds = [0] * n
            for i in range(1, n):
                if i % 2:
                    odds[i] = nums[i] + odds[i - 1]
                    evens[i] = evens[i - 1]
                else:
                    odds[i] = odds[i - 1]
                    evens[i] = nums[i] + evens[i - 1]
            ans = 0

            for i in range(n):
                if i % 2:
                    odd = odds[i - 1] + evens[-1] - evens[i]
                    even = evens[i] + odds[-1] - odds[i]
                else:
                    if i == 0:
                        even = odds[-1]
                        odd = evens[-1] - evens[0]
                    else:
                        even = evens[i - 1] + odds[-1] - odds[i]
                        odd = odds[i] + evens[-1] - evens[i]
                if odd == even:
                    ans += 1
            return ans

    def doit_(self, nums: list) -> int:
        from collections import deque

        right = deque()
        for i in range(len(nums) - 1, -1, -1):
            if 1 % 2 == 1:
                right.appendleft([nums[i], 0])
            else:
                right.appendleft([0, nums[i]])

            if len(right) > 1:
                right[0][0] += right[1][0]
                right[0][1] += right[1][1]

        left = deque()
        for i in range(len(nums)):
            left.append([nums[i], 0] if 1 % 2 == 1 else [0, nums[i]])
            if len(left) > 1:
                left[i][0] += left[i - 1][0]
                left[i][1] += left[i - 1][1]

        print(right)
        print(left)

        res = 0
        for i in range(len(nums)):

            if i == 0 and right[i + 1][0] == right[i + 1][1]:
                res += 1
                continue

            if i == len(nums) - 1 and left[i - 1][0] == left[i - 1][1]:
                res += 1
                continue

            if 0 < i < len(nums) - 1 and left[i - 1][0] + right[i + 1][1] == left[i - 1][1] + right[i + 1][0]:
                res += 1

        return res

if __name__ == '__main__':

    WaysToFairArray().waysToMakeFair([2, 1, 6, 4])


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

from webvita import app, db

from flask import request, session, redirect, url_for, abort,\
                  render_template, flash

from flask.ext.sqlalchemy import SQLAlchemy

from models import Blogpost, Tag, User

from datetime import datetime

from helpers import is_blogpost_unique, is_blogpost_short_unique,\
                    delete_unused_tags

import markdown

@app.route('/blog/<blogpost_short_title>')
def show_blogpost(blogpost_short_title):

    blogpost = Blogpost.query.filter_by(short_title=blogpost_short_title)\
                       .first_or_404()
    return render_template('show_blogpost.html', blogpost=blogpost)

@app.route('/blog/create')
def create_blogpost():
    if not session.get('logged_in'):
        abort(401)

    return render_template('create_blogpost.html')

@app.route('/blog/add', methods=['GET', 'POST'])
def add_blogpost():
    if not session.get('logged_in'):
        abort(401)

    title = unicode(request.form['title'])
    if not is_blogpost_unique(title):
        flash('Title already exists. Please choose a different title ' + \
              'for your blogpost.')
        # TODO: send previous data
        return redirect(url_for('create_blogpost'))
    short_title = unicode(request.form['short_title']).replace(' ', '-')
    if not is_blogpost_short_unique(short_title):
        flash('Short title already exists. Please choose a different ' + \
              'short title for your blogpost.')
        # TODO: send previous data
        return redirect(url_for('create_blogpost'))
    subtitle = unicode(request.form['subtitle'])

    text_markdown = unicode(request.form['text'])
    text_html = markdown.markdown(text_markdown, ['codehilite'])

    blogpost_tags = []
    tags = unicode(request.form['tags'])
    for t in tags.split(','):
        t = t.strip()
        if t:
            blogpost_tags.append(t)

    user = User.query.filter_by(username=session['user']).first_or_404()
    blogpost = Blogpost(user, title, subtitle, short_title, text_markdown,
                        text_html, blogpost_tags, hidden=False)
    db.session.add(blogpost)
    db.session.commit()

    flash('New blogpost has been added.')
    return redirect(url_for('show_blog'))

@app.route('/blog/edit')
def edit_blogpost_list():
    if not session.get('logged_in'):
        abort(401)

    blogposts = Blogpost.query.order_by('posted desc').all()
    return render_template('edit_blogpost_list.html', blogposts=blogposts)

@app.route('/blog/edit/<blogpost_short_title>')
def edit_blogpost(blogpost_short_title):
    if not session.get('logged_in'):
        abort(401)

    blogpost = Blogpost.query.filter_by(short_title=blogpost_short_title).first_or_404()
    tags = ', '.join([tag.name for tag in blogpost.tags])
    return render_template('edit_blogpost.html',
                           blogpost=blogpost,
                           tags=tags)

@app.route('/blog/update/<blogpost_short_title>', methods=['GET', 'POST'])
def update_blogpost(blogpost_short_title):
    if not session.get('logged_in'):
        abort(401)

    old_bp = Blogpost.query.filter_by(short_title=blogpost_short_title)\
                     .first_or_404()
    blogpost_title = old_bp.title
    title = unicode(request.form['title'])
    if title!=blogpost_title and not is_blogpost_unique(title):
        flash('Title already exists. Please choose a different title' + \
              ' for your blogpost.')
        # TODO: send previous data
        return redirect(url_for('edit_blogpost',
                                blogpost_title=blogpost_title))
    short_title = unicode(request.form['short_title']).replace(' ', '-')
    if short_title!=blogpost_short_title and not \
       is_blogpost_short_unique(short_title):
        flash('Short title already exists. Please choose a different ' + \
              'short title for your blogpost.')
        # TODO: send previous data
        return redirect(url_for('edit_blogpost',
                                blogpost_title=blogpost_title))
    subtitle = unicode(request.form['subtitle'])

    text_markdown = unicode(request.form['text'])
    text_html = markdown.markdown(text_markdown, ['codehilite'])

    old_tags = list(old_bp.tags)
    blogpost_tags = []
    tags = unicode(request.form['tags'])
    for t in tags.split(','):
        t = t.strip()
        if t:
            blogpost_tags.append(t)

    old_bp.title = title
    old_bp.subtitle = subtitle
    old_bp.short_title = short_title
    old_bp.text_markdown = text_markdown
    old_bp.text_html = text_html
    old_bp.update_tags(blogpost_tags)
    old_bp.edited = datetime.utcnow()
    db.session.commit()
    delete_unused_tags(old_tags)

    flash('Blogpost has been updated.')
    return redirect(url_for('show_blogpost',
                            blogpost_short_title=short_title))

@app.route('/blog/delete/<blogpost_short_title>')
def delete_blogpost(blogpost_short_title):
    if not session.get('logged_in'):
        abort(401)

    blogpost = Blogpost.query.filter_by(short_title=blogpost_short_title)\
                       .first_or_404()
    old_tags = list(blogpost.tags)
    db.session.delete(blogpost)
    db.session.commit()
    delete_unused_tags(old_tags)

    flash('Blogpost has been deleted.')
    return render_template('dashboard.html')

@app.route('/blog/tag/<tag_name>')
def show_tag(tag_name):

    blogposts = Blogpost.query.order_by('posted desc')\
                        .filter(Blogpost.tags.any(name=tag_name)).all()
    return render_template('show_tag_blogposts.html',
                           tag_name=tag_name,
                           blogposts=blogposts)


from typing import Optional

from aioowm.const import const
from aioowm.http.http import request
from aioowm.types.models import Model

class OWM:
	def __init__(self, token: str, language: Optional[str]):
		"""
		:param token: your api-key https://home.openweathermap.org/api_keys
		:param language: accepts country identifier (en, ru, fr)
		"""
		self._token = token
		self.language = language

	async def get(self, city: str) -> Model:
		response = await request(
				const.weather_api, {
					'q':     city,
					'lang':  self.language,
					'appid': self._token
				}
		)
		return Model(**response)


import os

import pytest
from scrapy.settings import Settings

@pytest.fixture()
def settings(request):
    """ Default scrapy-prerender settings """
    s = dict(
        # collect scraped items to .collected_items attribute
        ITEM_PIPELINES={
            'tests.utils.CollectorPipeline': 100,
        },

        # scrapy-prerender settings
        PRERENDER_URL=os.environ.get('PRERENDER_URL'),
        DOWNLOADER_MIDDLEWARES={
            # Engine side
            'scrapy_prerender.PrerenderCookiesMiddleware': 723,
            'scrapy_prerender.PrerenderMiddleware': 725,
            'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
            # Downloader side
        },
        SPIDER_MIDDLEWARES={
            'scrapy_prerender.PrerenderDeduplicateArgsMiddleware': 100,
        },
        DUPEFILTER_CLASS='scrapy_prerender.PrerenderAwareDupeFilter',
        HTTPCACHE_STORAGE='scrapy_prerender.PrerenderAwareFSCacheStorage',
    )
    return Settings(s)


from django.conf.urls import url,patterns

urlpatterns = patterns('score.views',
                        url(r'^$','home_page'),
                        url(r'^login/$','user_login'),
                        url(r'^submission/$','submission'),
                        url(r'^flag-response/$','flag_response'),
                        url(r'^user-register/$','user_register'),
                        url(r'^hint/','hint'),
                        url(r'^hint-count/$','hint_count'),
                       )


from glob import glob
from twisted.internet import defer, reactor
from wormhole.errors import WormholeError
import functools
import hpos_seed
import logging
import os
import sys
import time

log = logging.getLogger(__name__)

@functools.lru_cache()
def runtime_dir():
    return os.getenv('RUNTIME_DIRECTORY', '.')

@functools.lru_cache()
def state_dir():
    return os.getenv('STATE_DIRECTORY', '.')

@functools.lru_cache()
def runtime_config_path():
    return runtime_dir() + '/hp-*.json'

@functools.lru_cache()
def state_config_path():
    return state_dir() + '/hp-*.json'

@functools.lru_cache()
def wormhole_code_path():
    return runtime_dir() + '/wormhole-code.txt'

def ensureDeferred(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        return defer.ensureDeferred(result)
    return wrapper

@ensureDeferred
async def receive_config(backoff_exp=1):
    def on_wormhole_code(wormhole_code):
        with open(wormhole_code_path(), 'w') as f:
            f.write(wormhole_code)
    try:
        config = await hpos_seed.receive(on_wormhole_code, reactor)
        with open(state_config_path(), 'wb') as f:
            f.write(config)
    except WormholeError as e:
        backoff = 2 ** backoff_exp
        (exc_type, _, _) = sys.exc_info()
        log.warning("receive failed with %s, retrying in %d seconds",
                    exc_type, backoff)
        reactor.callLater(backoff, receive_config, backoff_exp + 1)
    except:
        log.warning("Wormhole receive failed with %s, process will now terminate")
    finally:
        if os.path.exists(wormhole_code_path()):
            os.remove(wormhole_code_path())

def scan_config_paths():
    return glob(state_config_path()) + glob('/media/*/hp-*.json')

def scan_reset_file():
    return glob('/media/*/hpos-reset')

def check_reset():
    reset_file = scan_reset_file()
    if reset_file:
        try:
            os.system("rm -f /media/*/hpos-reset")
            os.system("hpos-reset")
        except:
            print("unable to reset")

@ensureDeferred
async def scan_for_config():
    check_reset()
    config_paths = scan_config_paths()
    if config_paths:
        try:
            os.symlink(config_paths[0], runtime_config_path())
        finally:
            reactor.callLater(0, reactor.stop)
    reactor.callLater(1, scan_for_config)

def main():
    if glob(runtime_config_path()) == []:
        reactor.callLater(0, receive_config)
        reactor.callLater(0, scan_for_config)
        reactor.run()

if __name__ == '__main__':
    main()


import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet
import nltk.corpus

# Rule: Replace a set of phonemes with a different set.
def RuleReplace(rule, line):
    res = line
    d = []
    l1 = len(line[1])
    l = len(rule[2])
    r = range(l)
    if rule[1] == 'any':
        for i in range(l1):
            if line[1][i] != rule[2][0] or i+l > l1:
                d.append(line[1][i])
                continue
            is_match = True
            for j in r:
                if line[1][i+j] != rule[2][j]:
                    is_match = False
            if is_match:
                for j in rule[3]:
                    d.append(j)
                i = i + l - 1
    elif rule[1] == 'start':
        is_match = True
        for j in r:
            if line[1][j] != rule[2][j]:
                is_match = False
        s = 0
        if is_match:
            for j in rule[3]:
                d.append(j)
            s = l
        for i in range(s,l1):
            d.append(line[1][i])
    elif rule[1] == 'end':
        is_match = True
        for j in r:
            if line[1][l1-l+j] != rule[2][j]:
                is_match = False
        e = l1
        if is_match:
            e = l1-l
        for i in range(e):
            d.append(line[1][i])
        if is_match:
            for j in rule[3]:
                d.append(j)
    else:
        d = res[1]
    res = (res[0], d)
    return res

# Rule: Test WordNet to see if word exists there.
def RuleWordNetFilter(rule, line):
    if line[0] in RuleWordNetFilter.words:
        return line
    if len(wordnet.synsets(line[0])) == 0:
        return None
    return line

# Creates a list of rules
# Argument: List of strings, each string a rule.
# Result:
#     Tuple ("Phon" rules, "Word" rules, "Sent" rules).
#     "Phon" rules:
#         List of 4-member tuples each containing:
#             1. The function applying to the rule
#             2. The location of application:
#                'start' - The first phoneme/s in each word
#                'end' - The last phoneme/s in each word
#                'any' - Any matching phoneme
#             3. Phoneme/s to which to apply
#             4. Phoneme/s to apply
#     "Word" rules:
#         List of 1-member tuples each containing a rule
#         function.
#     "Sent" rules:
#         List of tuples (name, value).
def PrepareRules(rule_lines):
    res = ([],[],{})
    funcs = {"Replace":RuleReplace, \
             "WordNetFilter":RuleWordNetFilter} \
             # TODO: Add more...
    for rule in rule_lines:
        if rule.strip('\n').strip(' ') == '':
            continue
        (t,c) = rule.rstrip('\n').split('#')
        if t == 'Phon':
            (d,i) = c.split(':')
            (f,p) = d.split(',')
            (l,r) = i.split(',')
            entry = []
            entry.append(funcs[f])
            entry.append(p)
            entry.append(l.split(' '))
            entry.append(r.split(' '))
            res[0].append(tuple(entry))
        elif t == 'Word':
            entry = []
            entry.append(funcs[c])
            res[1].append(tuple(entry))
        elif t == 'Sent':
            entry = c.split(':')
            res[2][entry[0]] = entry[1]
    return res

# Creates a uppercase word set for filtering.
def CreateWordSet():
    res = []
    contractions = [\
        "'em", "ain't", "aren't", "can't", "can't've", \
        "'cause", "could've", "couldn't", "couldn't've", \
        "didn't", "doesn't", "don't", "hadn't", \
        "hadn't've", "hasn't", "haven't", "he'd", \
        "he'd've", "he'll", "he'll've", "he's", "how'd", \
        "how'd'y", "how'll", "how's", "I'd", "I'd've", \
        "I'll", "I'll've", "I'm", "I've", "isn't", "it'd", \
        "it'd've", "it'll", "it'll've", "it's", "let's", \
        "ma'am", "mayn't", "might've", "mightn't", \
        "mightn't've", "must've", "mustn't", "mustn't've", \
        "needn't", "needn't've", "o'clock", "oughtn't", \
        "oughtn't've", "shan't", "sha'n't", "shan't've", \
        "she'd", "she'd've", "she'll", "she'll've", \
        "she's", "should've", "shouldn't", "shouldn't've", \
        "so've", "so's", "that'd", "that'd've", "that's", \
        "there'd", "there'd've", "there's", "they'd", \
        "they'd've", "they'll", "they'll've", "they're", \
        "they've", "to've", "wasn't", "we'd", "we'd've", \
        "we'll", "we'll've", "we're", "we've", "weren't", \
        "what'll", "what'll've", "what're", "what's", \
        "what've", "when's", "when've", "where'd", \
        "where's", "where've", "who'll", "who'll've", \
        "who's", "who've", "why's", "why've", "will've", \
        "won't", "won't've", "would've", "wouldn't", \
        "wouldn't've", "y'all", "y'all'd", "y'all'd've", \
        "y'all're", "y'all've", "you'd", "you'd've",\
        "you'll", "you'll've", "you're", "you've"]
    res = res + nltk.corpus.words.words()
    res = res + contractions
    res = list(set(res))
    for i in range(len(res)):
        res[i] = res[i].upper()
    res = set(res)
    return res

# Initializes data needed for rule application (useful for
# reducing complexity).
def RulesBegin():
    RuleWordNetFilter.words = CreateWordSet()

# Clears initializes data for memory saving.
def RulesEnd():
    RuleWordNetFilter.words = []


class marksheet:

    def __init__(self):
        self.name = input("Enter name:")
        self.age = int(input("Enter Age:"))
        self.gender = input("Enter gender:")

    def display(self):
        print("\n\nName:",self.name)
        print("Age:",self.age)
        print("Gender:",self.gender)

class Marks:

    def __init__(self):
        self.Science = int(input("Enter marks of Science:"))
        self.Maths = int(input("Enter marks of Maths:"))
        self.Sanskrit = int(input("Enter marks of Sanskrit:"))

    def display(self):
        Total = self.Science + self.Maths + self.Sanskrit
        print("Total Marks:",Total)

class student(marksheet,Marks):

    def __init__(self):
        marksheet. __init__self()
        marks. __init__self()

m1=marksheet()
m2=Marks()
m1.display()
m2.display()


## Level Order Traversal - Using Queue
## Append only right node's value when on same level

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:

        if root==None:
            return []

        result = []
        queue = deque([root])

        while queue:
            size = len(queue)

            for i in range(size):
                root = queue.popleft()

                if i==0:
                    result.append(root.val)
                if root.right:
                    queue.append(root.right)
                if root.left:
                    queue.append(root.left)

        return result


#!/usr/bin/env python
# run:
# $ FLASK_APP=mini_app flask run
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from safrs import SAFRSBase, SAFRSAPI

db = SQLAlchemy()

class User(SAFRSBase, db.Model):
    """
        description: User description
    """

    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String)

def create_api(app, HOST="localhost", PORT=5000, API_PREFIX=""):
    api = SAFRSAPI(app, host=HOST, port=PORT, prefix=API_PREFIX)
    api.expose_object(User)
    user = User(name="test", email="email@x.org")
    print("Starting API: http://{}:{}/{}".format(HOST, PORT, API_PREFIX))

def create_app(config_filename=None):
    app = Flask("demo_app")
    app.config.update(SQLALCHEMY_DATABASE_URI="sqlite://")
    db.init_app(app)
    with app.app_context():
        db.create_all()
        create_api(app)
    return app

if __name__ == "__main__":
    app = create_app()
    app.run()


from changes import changelog
from . import BaseTestCase

class ChangeLogTestCase(BaseTestCase):

    def test_write_new_changelog(self):
        content = [
            'This is the heading\n\n',
            'This is the first line\n',
        ]

        with open(self.tmp_file, 'w') as existing_file:
            existing_file.writelines(content)

        changelog.write_new_changelog('test_app', self.tmp_file, 'Now this is')

        self.assertEquals(
            ''.join(content),
            ''.join(
                open(self.tmp_file).readlines()
            )
        )

        with open(self.tmp_file, 'w') as existing_file:
            existing_file.writelines(content)

        changelog.write_new_changelog(
            'test_app',
            self.tmp_file,
            'Now this is',
            dry_run=False
        )
        expected_content = [
            '# [Changelog](None/releases)\n',
            'Now this is\n',
            'This is the first line\n'
        ]
        self.assertEquals(
            ''.join(expected_content),
            ''.join(
                open(self.tmp_file).readlines()
            )
        )

    def test_changelog(self):
        pass