import pygame
from pygame.locals import *
pygame.init()

OKNO_SIRKA = 800
OKNO_VYSKA = 600

CERNA = (0,0,0)
CERVENA = (255,0,0)

TIHOVE_ZRYCHLENI_VE_HRE = 10

pozice_font = pygame.font.Font(None, 25)

class Hrac:
    def __init__(self, zadane_jmeno, zadana_sirka, zadana_pozice_x, zadana_pozice_y, barva):
        # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # desítková soustava
        # 0 1 2 3 4 5 6 7 8 9 A B C D E F # šestnáctková soustava
        #    IIII - jednotková soustava (unární)

        self.jmeno = zadane_jmeno
        self.prumer = zadana_sirka
        self.pozice_x = zadana_pozice_x
        self.pozice_y = zadana_pozice_y
        self.barva = barva
        self.rychlost_x = 0
        self.rychlost_y = 0

        # Zapouzdření
    @property  # Getter (i v jiných jazycích)
    def pozice_y(self):
        return self.__pozice_y

    @pozice_y.setter  # Setter (i v jiných jazycích)
    def pozice_y(self, nova_hodnota):
        if nova_hodnota < 0 + self.prumer // 2:
            self.__pozice_y = 0 + self.prumer // 2
        elif nova_hodnota > OKNO_VYSKA - self.prumer // 2:
            self.__pozice_y = OKNO_VYSKA - self.prumer // 2
        else:
            self.__pozice_y = nova_hodnota

    @property  # Getter (i v jiných jazycích)
    def pozice_x(self):
        return self.__pozice_x

    @pozice_x.setter  # Setter (i v jiných jazycích)
    def pozice_x(self, nova_hodnota):
        if nova_hodnota < 0 + self.prumer // 2:
            self.__pozice_x = 0 + self.prumer // 2
        elif nova_hodnota > OKNO_SIRKA - self.prumer // 2:
            self.__pozice_x = OKNO_SIRKA - self.prumer // 2
        else:
            self.__pozice_x = nova_hodnota

    def pohni_se(self, za_jakou_dobu):
        # s = s0 + v*t
        self.pozice_x = self.pozice_x + (self.rychlost_x * za_jakou_dobu // 1000)  # cas je vzdy jeden frame
        self.pozice_y = self.pozice_y - (self.rychlost_y * za_jakou_dobu // 1000)
        self.rychlost_y = self.rychlost_y - TIHOVE_ZRYCHLENI_VE_HRE

    def skok(self):
        self.rychlost_x = 1
        self.rychlost_y = 10

    def zobraz(self, platno_kam):
        kolecko_obdelnik = pygame.draw.circle(platno_kam, self.barva, [self.pozice_x, self.pozice_y], self.prumer // 2,
                                              0)
        # Doděláme - zobrazuje text
        # text = pygame.font.render('x: {} y: {}'.format(CarPos[0], CarPos[1]), True, black, white)
        # textRect = text.get_rect()
        # textRect.center = (display_width // 2, 20)
        # platno_kam.blit(text, textRect)
        return kolecko_obdelnik

    def pohyb_vpravo(self):
        self.pozice_x += 10  # self.pozice_x = self.pozice_x + 10
        self.rychlost_x = 0

    def pohyb_vlevo(self):
        self.pozice_x -= 10
        self.rychlost_x = 0

    def pohyb_nahoru(self):
        self.pozice_y -= 10
        self.rychlost_y = 0

    def pohyb_dolu(self):
        self.pozice_y += 10
        self.rychlost_y = 0

platno_hlavni = pygame .display.set_mode((OKNO_SIRKA, OKNO_VYSKA))
pygame.display.set_caption('Krouzek - plosinovka')

mraky = pygame.image.load("Images/mrak.jpg").convert()
mraky = pygame.transform.scale(mraky, (OKNO_SIRKA, OKNO_VYSKA))

# >>> Funkce convert() upravi data tak, aby je Pygame mohl rychle vykreslovat -> tedy ji chceme používat :-)
auto = pygame.image.load("Images/car.png").convert_alpha()
auto_obdelnik = auto.get_rect()
auto = pygame.transform.scale(auto, (auto_obdelnik[2]//5, auto_obdelnik[3]//5))

hrac1 = Hrac("Franta", 100, 200, 400, (0,0,0))
hrac2 = Hrac("Tonda", 200, 400, 600, (255,0,0))

# Nakresleni zacatku hry
platno_hlavni.blit(mraky, (0, 0))

hrac1_obdelnik = hrac1.zobraz(platno_hlavni)
#hrac2_obdelnik = hrac2.zobraz(platno_hlavni)

auto_obdelnik = platno_hlavni.blit(auto, dest=(50, 400), area=None)

text = pozice_font.render('x: {} y: {}'.format(hrac1.pozice_x, hrac1.pozice_y), True, CERNA, None)
textRect = text.get_rect()
textRect.center = (OKNO_SIRKA // 2, textRect[2])  # textRect[2] výška obdélníku
textRect_toRemove = platno_hlavni.blit(text, dest=textRect)

naposledy_jsem_kreslil_v = pygame.time.get_ticks()

hodiny = pygame.time.Clock()
fps = 20
# key_interval = 500//fps
# pygame.key.set_repeat(key_interval, key_interval)
running = True
while running:
    # Ukladá si do fronty všechny události a zpracuje je ve chvíli, kdy doběhne na tento řádek (tedy i ty, které se staly kdykoliv v průběhu programu)
    udalosti = pygame.event.get()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # elif event.type == pygame.KEYDOWN:
            # if event.key == K_d:
            #    kolecko_stred[0] = kolecko_stred[0] + posun_kolecka
            # elif event.key == K_a:
            #    kolecko_stred[0] = kolecko_stred[0] - posun_kolecka
            # elif event.key == K_s:
            #    kolecko_stred[1] = kolecko_stred[1] + posun_kolecka
            # elif event.key == K_w:
            #    kolecko_stred[1] = kolecko_stred[1] - posun_kolecka

        # Ziskam aktualne stisknute klavesy (stisknute ve chvili, kdy je program na tomto řádku)
    stisknute_klavesy = pygame.key.get_pressed()  # [K_Q:False K_W:False K_E:True K_R:False K_esc:false]
    if stisknute_klavesy[K_d]:  # True == True -> True    False == True -> False --> Záleží jen na prvním
        hrac1.pohyb_vpravo()
        # hrac2.pohyb_vpravo()
    if stisknute_klavesy[K_a]:
        hrac1.pohyb_vlevo()
        # hrac2.pohyb_vlevo()
    if stisknute_klavesy[K_s]:
        hrac1.pohyb_dolu()
        # hrac2.pohyb_dolu()
    if stisknute_klavesy[K_w]:
        hrac1.pohyb_nahoru()
        # hrac2.pohyb_nahoru()
    if stisknute_klavesy[K_q]:
        hrac1.skok()

    # hrac1.pozice_y = -25  # -> Spustí funkci pozice_y(self, nova_hodnota): která je @pozice_y.setter
    # 1) Existuje proměná hrac1.pozice_y ? Ne
    #       Co teda existuje ? I) Existuje funkce pozice_y() jako @pozice_y.setter
    #                          II) Existuje to, co jsem vyrobil ve funkci pozice_y() -> takže u nás proměnná __pozice_y
    #       Co k čertu znamenají ty __ ? Proměnná je schovaná -> nemůžu jí číst ani do ní zapisovat mimo třídu ve které existuje

    # print(hrac1.pozice_y) # -> Spustí funkci pozice_y(self): která je @property

    # print(pygame.time.get_ticks())
    aktualni_cas = pygame.time.get_ticks()
    kolik_casu_ubehlo = aktualni_cas - naposledy_jsem_kreslil_v
    naposledy_jsem_kreslil_v = aktualni_cas

    hrac1.pohni_se(kolik_casu_ubehlo)

    text = pozice_font.render('x: {} y: {}'.format(hrac1.pozice_x, hrac1.pozice_y), True, CERNA, None)
    textRect = text.get_rect()
    textRect.center = (OKNO_SIRKA // 2, textRect[2])  # textRect[2] výška obdélníku
    platno_hlavni.blit(mraky, dest=textRect_toRemove, area=textRect_toRemove)
    textRect_toRemove = platno_hlavni.blit(text, dest=textRect)

    ax1 = auto_obdelnik[0]
    ax2 = auto_obdelnik[0] + auto_obdelnik[2]

    # print(hrac1_obdelnik)
    hx1 = hrac1_obdelnik[0]
    hx2 = hrac1_obdelnik[0] + hrac1_obdelnik[2]

    if (hx1 >= ax1 and hx1 <= ax2) or (hx2 >= ax1 and hx2 <= ax2) or (hx1 < ax1 and hx2 > ax2):
            hrac1.barva = CERVENA
    else:
        hrac1.barva = CERNA

        # # zmena smeru pohybu
        # if (kolecko_stred[0] + kolecko_polomer >= okno_sirka) or (kolecko_stred[0] - kolecko_polomer <= 0):
        #     posun_kolecka = -posun_kolecka

    # pracuje s autem
    platno_hlavni.blit(mraky, dest=auto_obdelnik, area=auto_obdelnik)  # "ctrl+C ctrl+V"
    auto_obdelnik = platno_hlavni.blit(auto, dest=(50, 400), area=None)  # Vloží celý (area=None) obrázek auto do platno_hlavni na pozici (50, 200)

    # pracuje s koleckem
    platno_hlavni.blit(platno_hlavni, dest=hrac1_obdelnik, area=hrac1_obdelnik)  # "ctrl+C ctrl+V"
    kolecko_obdelnik = hrac1.zobraz(platno_hlavni)

    #platno_hlavni.blit(mraky, dest=hrac2_obdelnik, area=hrac2_obdelnik)  # "ctrl+C ctrl+V"
    #hrac2_obdelnik = hrac2.zobraz(platno_hlavni)

    hodiny.tick(fps)
    pygame.display.flip()  # překreslí celý obraz
    # pygame.display.display(oblast_se_zmenou)

pygame.quit()


# -*- coding:utf-8 -*-
import sys
sys.path.append("../src")
from screen_processor import MapleScreenCapturer
import cv2, time, imutils, math
import numpy as np
cap = MapleScreenCapturer()
from win32gui import SetForegroundWindow

x, y, w, h = 450, 180, 500, 130
ds = None
while True:
    img = cap.capture(set_focus=False)
    img_arr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    final_img = imutils.resize(img_arr, width = 200)
    cv2.imshow("s to save image", final_img)
    inp = cv2.waitKey(1)

    if inp == ord("s"):
        SetForegroundWindow(cap.ms_get_screen_hwnd())
        time.sleep(0.3)
        ds = cap.capture(set_focus=False)
        ds = cv2.cvtColor(np.array(ds), cv2.COLOR_RGB2BGR)
        ds = ds[y:y + h, x:x + w]
        print("saved")

    elif inp == ord("q"):
        cv2.destroyAllWindows()
        break
    elif inp == ord("r"):
        ds = cv2.imread("validation_rgb.png")
        print("read data")

display = ds.copy()
gray = display.copy()
gray = cv2.cvtColor(gray, cv2.COLOR_BGR2HSV)
# Maximize saturation
gray[:, :, 1] = 255
gray[:, :, 2] = 255
gray = cv2.cvtColor(gray, cv2.COLOR_HSV2BGR)
gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
cv2.imwrite("validation_rgb.png", display)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,1, gray.shape[0]/8 , param1=100, param2=30,minRadius=18, maxRadius=30)
circle_roi = []
if circles is not None:
    circles = np.round(circles[0, :]).astype("int")
    for (x, y, r) in circles:
        print(x, y, r)
        cropped = gray[max(0,int(y-60/2)):int(y+60/2), max(0,int(x-60/2)):int(x+60/2)]
        cropped = cv2.Canny(cropped, threshold1=60, threshold2=180)
        cropped_color = display[max(0,int(y-60/2)):int(y+60/2), max(0,int(x-60/2)):int(x+60/2)]
        cv2.circle(gray, (x, y), r, (0, 255, 0), 2)
        #cv2.circle(display, (x, y), r, (0, 255, 0), 2)
        circle_roi.append([cropped, (x, y), cropped_color])

cv2.imshow("", display)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow("", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
circle_roi = sorted(circle_roi, key=lambda x: x[1][0])

for circ in circle_roi:
    circ_img = circ[0]
    _, contours, _ = cv2.findContours(circ_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    """for cnt in contours:
        approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
        if len(approx) >= 20:
            cv2.drawContours(circ[2],[cnt], -1,(0,255,0), 1)"""

    lines = cv2.HoughLinesP(circ[0],1,np.pi/180, 10,minLineLength=5)
    line_data = []
    for line in lines:
        x1, y1, x2, y2 = line[0].tolist()
        if x2 == x1 or y2 == y1:
            slope = 0
        else:
            slope = (y2-y1)/(x2-x1)
        line_data.append([x1,y1,x2,y2, slope])
        #cv2.line(circ[2], (x1, y1), (x2, y2), (0, 255, 0), 1)

    for line in line_data:
        for other_line in line_data:
            dist = []

            processed_slope = line[4] * other_line[4]
            if processed_slope <= 0:
                copied = circ[2].copy()
                cv2.line(copied, (line[0], line[1]),(line[2], line[3]), (0, 255, 0), 1)
                cv2.line(copied, (other_line[0], other_line[1]), (other_line[2], other_line[3]), (255, 0, 0), 1)
                #cv2.imshow(str(processed_slope), imutils.resize(copied, width=400))
                #cv2.waitKey(0)
                #cv2.destroyAllWindows()
    cv2.imshow("contours", imutils.resize(circ[2], width=400))
    cv2.imshow("canny",imutils.resize(circ[0], width=400))
    cv2.waitKey(0)


""" Module for converting masks to stacked image

    Args:
        -p (pattern): searching pattern
        -b (batch): batch process, thisjob and totaljob
        -m (mask): mask source, e.g. fmask
        -R (recursive): recursive when seaching files
        --overwrite: overwrite or not
        ori: origin
        des: destination

"""
import os
import sys
import argparse

from osgeo import gdal

from ...io import mn2ln, bit2mask, mask2array, hdr2geo, stackGeo, array2stack
from ...common import constants as cons
from ...common import log, get_files, manage_batch

def mask_to_stack(pattern, ori, des, _source, overwrite=False, recursive=False,
                    batch=[1,1]):
    """ converting masks to stacked images

    Args:
        pattern (str): searching pattern, e.g. HLS*hdf
        ori (str): place to look for inputs
        des (str): place to save outputs
        _source (str): mask source, e.g. fmask, maja, lasrc
        overwrite (bool): overwrite or not
        recursive (bool): recursive when searching file, or not
        batch (list, int): batch processing, [thisjob, totaljob]

    Returns:
        0: successful
        1: error due to des
        2: error when searching files
        3: found no file

    """
    # check if output exists, if not try to create one
    if not os.path.exists(des):
        log.warning('{} does not exist, trying to create one.'.format(des))
        try:
            os.makedirs(des)
        except:
            log.error('Cannot create output folder {}'.format(des))
            return 1

    # locate files
    log.info('Locating files...'.format(ori))
    try:
        mask_list = get_files(ori, pattern, recursive)
        n = len(mask_list)
    except:
        log.error('Failed to search for {}'.format(pattern))
        return 2
    else:
        if n == 0:
            log.error('Found no {}'.format(pattern))
            return 3
        else:
            log.info('Found {} files.'.format(n))

    # handle batch processing
    if batch[1] > 1:
        log.info('Handling batch process...')
        mask_list = manage_batch(mask_list, batch[0], batch[1])
        n = len(mask_list)
        log.info('{} files to be processed by this job.'.format(n))

    # loop through all files
    count = 0
    log.info('Start processing files...')
    for mask in mask_list:
        log.info('Processing {}'.format(mask[1]))
        if _source == 'lasrc':
            geo = hdr2geo('{}.hdr'.format(os.path.join(mask[0], mask[1])))
        else:
            geo = stackGeo(os.path.join(mask[0], mask[1]))
        res = int(geo['geotrans'][1])
        array = mask2array(os.path.join(mask[0], mask[1]), _source)
        array = bit2mask(array, _source)
        if array2stack(array, geo, '{}.tif'.format(os.path.join(des,
                        mn2ln(mask[1], _source, res))),
                        ['{} {}m'.format(_source, res)], cons.MASK_NODATA,
                        gdal.GDT_Int16, overwrite) == 0:
            count += 1

    # done
    log.info('Process completed.')
    log.info('Successfully processed {}/{} files.'.format(count, n))
    return 0

if __name__ == '__main__':
    # parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--pattern', action='store', type=str,
                        dest='pattern', default='HLS*hdf',
                        help='searching pattern')
    parser.add_argument('-b', '--batch', action='store', type=int, nargs=2,
                        dest='batch', default=[1,1],
                        help='batch process, [thisjob, totaljob]')
    parser.add_argument('-m', '--mask', action='store', type=str, dest='mask',
                        default='fmask', help='mask source')
    parser.add_argument('-R', '--recursive', action='store_true',
                        help='recursive or not')
    parser.add_argument('--overwrite', action='store_true',
                        help='overwrite or not')
    parser.add_argument('ori', default='./', help='origin')
    parser.add_argument('des', default='./', help='destination')
    args = parser.parse_args()

    # check arguments
    if not 1 <= args.batch[0] <= args.batch[1]:
        log.error('Invalid batch inputs: [{}, {}]'.format(args.batch[0],
                    args.batch[1]))
        sys.exit(1)

    # print logs
    log.info('Start converting mask to stack...')
    log.info('Running job {}/{}'.format(args.batch[0], args.batch[1]))
    log.info('Looking for {}'.format(args.pattern))
    log.info('In {}'.format(args.ori))
    log.info('Saving in {}'.format(args.des))
    log.info('Mask generated by {}.'.format(args.mask))
    if args.recursive:
        log.info('Recursive seaching.')
    if args.overwrite:
        log.info('Overwriting old files.')

    # run function to convert masks
    mask_to_stack(args.pattern, args.ori, args.des, args.mask, args.overwrite,
                        args.recursive, args.batch)


from lex import *
from parse import *
import sys

def main():
    if len(sys.argv) != 2:
        sys.exit("Erro: Precisamos de um arquivo como argumento.")
    with open(sys.argv[1], 'r') as inputFile:
        input = inputFile.read()

    lexer = Lexer(input)
    parser = Parser(lexer)
    parser.parse()
    print("Terminamos.")

main()


import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt

class Autoencoder_CNN(nn.Module):
    def __init__(self):
        super(Autoencoder_CNN, self).__init__()
        # N, 784
        self.encoder = nn.Sequential(
            nn.Conv2d(1, 16, 3, stride=2, padding=1), # N, 16, 14, 14
            nn.ReLU(),
            nn.Conv2d(16, 32, 3, stride=2, padding=1), # N 32, 7, 7
            nn.ReLU(),
            nn.Conv2d(32, 64, 7),  # N, 64, 1, 1
        )

        self.decoder = nn.Sequential(
            nn.ConvTranspose2d(64, 32, 7),
            nn.ReLU(),
            nn.ConvTranspose2d(32, 16, 3, stride=2, padding=1, output_padding=1),
            nn.ReLU(),
            nn.ConvTranspose2d(16, 1, 3, stride=2, padding=1, output_padding=1),
            nn.Sigmoid()
        )

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

if __name__ == "__main__":
    transform = transforms.ToTensor()
    # transform = transforms.Compose([
    #     transforms.ToTensor(),
    #     transforms.Normalize((0.5), (0.5))
    # ])
    mnist_data = datasets.MNIST(root='../data',
                                train=True,
                                download=True,
                                transform=transform
                                )

    data_loader = torch.utils.data.DataLoader(dataset=mnist_data,
                                              batch_size=4,
                                              shuffle=True)

    # This is to check image data.
    # dataiter = iter(data_loader)
    # images, labels = dataiter.next()
    # print(torch.min(images), torch.max(images))

    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    print(device)
    model = Autoencoder_CNN().to(device)
    criterion = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
    print(model)

    num_epochs = 10
    outputs = []
    for epoch in range(num_epochs):
        for (img, _) in data_loader:
            # img = img.reshape(-1, 28*28).to(device)
            img = img.to(device)
            recon = model(img)
            loss = criterion(recon, img)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        print(f"Epoch:{epoch+1}, Loss:{loss.item():.4f}")
        outputs.append((epoch, img, recon))

    for k in range(0, num_epochs, 4):
        plt.figure(figsize=(9, 2))
        plt.gray()
        imgs = outputs[k][1].detach().cpu().numpy()
        recon = outputs[k][2].detach().cpu().numpy()
        for i, item in enumerate(imgs):
            if i >= 9:
                break
            plt.subplot(2, 9, i+1)
            # item = item.reshape(-1, 28, 28)
            plt.imshow(item[0])

        for i, item in enumerate(recon):
            if i >= 9:
                break
            plt.subplot(2, 9, 9+i+1)
            # item = item.reshape(-1, 28, 28)
            plt.imshow(item[0])
    plt.show()


# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------

from msrest.serialization import Model

class AuthorizationGrant(Model):
    """AuthorizationGrant.

    :param grant_type:
    :type grant_type: object
    """

    _attribute_map = {
        'grant_type': {'key': 'grantType', 'type': 'object'}
    }

    def __init__(self, grant_type=None):
        super(AuthorizationGrant, self).__init__()
        self.grant_type = grant_type


# Copyright (c) 2019  Red Hat, Inc.
#
# 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.
#
# Written by Jan Kaluza <jkaluza@redhat.com>

from unittest.mock import patch, MagicMock

import freshmaker
from freshmaker.errata import ErrataAdvisory
from freshmaker.events import (ErrataAdvisoryStateChangedEvent,
                               ManualRebuildWithAdvisoryEvent)
from freshmaker.handlers.bob import RebuildImagesOnImageAdvisoryChange
from freshmaker import models, db, conf
from tests import helpers

class RebuildImagesOnImageAdvisoryChangeTest(helpers.ModelsTestCase):

    def setUp(self):
        super(RebuildImagesOnImageAdvisoryChangeTest, self).setUp()

        self.event = ErrataAdvisoryStateChangedEvent(
            "123",
            ErrataAdvisory(123, "RHBA-2017", "SHIPPED_LIVE", [],
                           security_impact="",
                           product_short_name="product"))
        self.handler = RebuildImagesOnImageAdvisoryChange()
        self.db_event = models.Event.get_or_create(
            db.session, self.event.msg_id, self.event.search_key,
            self.event.__class__)

    def test_can_handle(self):
        self.event.advisory.content_types = ["docker"]
        ret = self.handler.can_handle(self.event)
        self.assertTrue(ret)

    def test_can_handle_manual_event(self):
        event = ManualRebuildWithAdvisoryEvent(
            "123",
            ErrataAdvisory(123, "RHBA-2017", "SHIPPED_LIVE", ["docker"],
                           security_impact="",
                           product_short_name="product"),
            [])
        ret = self.handler.can_handle(event)
        self.assertTrue(ret)

    def test_can_handle_non_docker_advisory(self):
        self.event.advisory.content_types = ["rpm"]
        ret = self.handler.can_handle(self.event)
        self.assertFalse(ret)

    @patch.object(freshmaker.conf, 'handler_build_allowlist', new={
        'RebuildImagesOnImageAdvisoryChange': {
            "image": {"advisory_state": "SHIPPED_LIVE"}
        }
    })
    @patch("freshmaker.handlers.bob.RebuildImagesOnImageAdvisoryChange."
           "rebuild_images_depending_on_advisory")
    def test_handler_allowed(self, rebuild_images):
        self.event.advisory.state = "NEW_FILES"
        self.handler.handle(self.event)
        rebuild_images.assert_not_called()

        self.event.advisory.state = "SHIPPED_LIVE"
        self.handler.handle(self.event)
        rebuild_images.assert_called_once()

    @patch("freshmaker.errata.Errata.get_docker_repo_tags")
    @patch("freshmaker.pulp.Pulp.get_docker_repository_name")
    @patch("freshmaker.handlers.bob."
           "rebuild_images_on_image_advisory_change.requests.get")
    @patch.object(freshmaker.conf, 'bob_auth_token', new="x")
    @patch.object(freshmaker.conf, 'bob_server_url', new="http://localhost/")
    def test_rebuild_images_depending_on_advisory(
            self, requests_get, get_docker_repository_name,
            get_docker_repo_tags):
        get_docker_repo_tags.return_value = {
            'foo-container-1-1': {'foo-526': ['5.26', 'latest']},
            'bar-container-1-1': {'bar-526': ['5.26', 'latest']}}
        get_docker_repository_name.side_effect = [
            "scl/foo-526", "scl/bar-526"]

        resp1 = MagicMock()
        resp1.json.return_value = {
            "message": "Foobar",
            "impacted": ["bob/repo1", "bob/repo2"]}
        resp2 = MagicMock()
        resp2.json.return_value = {
            "message": "Foobar",
            "impacted": ["bob/repo3", "bob/repo4"]}
        requests_get.side_effect = [resp1, resp2]

        self.handler.rebuild_images_depending_on_advisory(self.db_event, 123)

        get_docker_repo_tags.assert_called_once_with(123)
        get_docker_repository_name.assert_any_call("bar-526")
        get_docker_repository_name.assert_any_call("foo-526")
        requests_get.assert_any_call(
            'http://localhost/update_children/scl/foo-526',
            headers={'Authorization': 'Bearer x'},
            timeout=conf.requests_timeout)
        requests_get.assert_any_call(
            'http://localhost/update_children/scl/bar-526',
            headers={'Authorization': 'Bearer x'},
            timeout=conf.requests_timeout)

        db.session.refresh(self.db_event)

        self.assertEqual(self.db_event.state, models.EventState.COMPLETE.value)

        builds = set([b.name for b in self.db_event.builds])
        self.assertEqual(builds, set(['scl/foo-526', 'scl/bar-526',
                                      'bob/repo1', 'bob/repo2',
                                      'bob/repo3', 'bob/repo4']))
        for build in self.db_event.builds:
            if build in ['bob/repo1', 'bob/repo2']:
                self.assertEqual(build.dep_on.name == "scl/foo-526")
            elif build in ['bob/repo3', 'bob/repo4']:
                self.assertEqual(build.dep_on.name == "scl/bar-526")

    @patch("freshmaker.errata.Errata.get_docker_repo_tags")
    @patch("freshmaker.pulp.Pulp.get_docker_repository_name")
    @patch("freshmaker.handlers.bob."
           "rebuild_images_on_image_advisory_change.requests.get")
    @patch.object(freshmaker.conf, 'bob_auth_token', new="x")
    @patch.object(freshmaker.conf, 'bob_server_url', new="http://localhost/")
    def test_rebuild_images_depending_on_advisory_unknown_advisory(
            self, requests_get, get_docker_repository_name,
            get_docker_repo_tags):
        get_docker_repo_tags.return_value = None
        self.handler.rebuild_images_depending_on_advisory(self.db_event, 123)

        get_docker_repo_tags.assert_called_once_with(123)
        get_docker_repository_name.assert_not_called()
        requests_get.assert_not_called()

    @patch("freshmaker.errata.Errata.get_docker_repo_tags")
    @patch("freshmaker.pulp.Pulp.get_docker_repository_name")
    @patch("freshmaker.handlers.bob."
           "rebuild_images_on_image_advisory_change.requests.get")
    @patch.object(freshmaker.conf, 'bob_auth_token', new="x")
    @patch.object(freshmaker.conf, 'bob_server_url', new="http://localhost/")
    def test_rebuild_images_depending_on_advisory_dry_run(
            self, requests_get, get_docker_repository_name,
            get_docker_repo_tags):
        get_docker_repo_tags.return_value = {
            'foo-container-1-1': {'foo-526': ['5.26', 'latest']}}
        get_docker_repository_name.return_value = "scl/foo-526"
        self.handler.force_dry_run()
        self.handler.rebuild_images_depending_on_advisory(self.db_event, 123)

        get_docker_repo_tags.assert_called_once_with(123)
        get_docker_repository_name.assert_called_once_with("foo-526")
        requests_get.assert_not_called()


import pygame
import colours
import paddle
import ball

# Variables
running = True
game_state = "menu"
winning_player = None
left_score = 0
right_score = 0

screen_size = (800, 600)
screen_title = "Pong"
indent = 50

# Initialisation
pygame.init()
main_display = pygame.display.set_mode(screen_size)
pygame.display.set_caption(screen_title)
clock = pygame.time.Clock()
game_ball = ball.Ball(main_display, screen_size[0] / 2, screen_size[1] / 2)
player_right = paddle.Paddle(main_display, \
                        screen_size[0] - (indent + paddle.Paddle.width), \
                        (screen_size[1] / 2) - (paddle.Paddle.height - 2))
player_left = paddle.Paddle(main_display, \
                        (indent + paddle.Paddle.width), \
                        (screen_size[1] / 2) - (paddle.Paddle.height - 2))

# Text
font = pygame.font.SysFont(None, 72)

start_game_text = font.render("Start Game", True, colours.white, colours.black)
start_text_x = (screen_size[0] / 2) - (start_game_text.get_width() / 2)
start_text_y = (screen_size[1] / 3) - (start_game_text.get_height() / 2)
start_button = pygame.Rect(start_text_x, start_text_y, start_game_text.get_width(), start_game_text.get_height())

quit_text = font.render("Quit", True, colours.white, colours.black)
quit_text_x = (screen_size[0] / 2) - (quit_text.get_width() / 2)
quit_text_y = (2 * screen_size[1] / 3) - (quit_text.get_height() / 2)
quit_button = pygame.Rect(quit_text_x, quit_text_y, quit_text.get_width(), quit_text.get_height())

score_indent = 75

# Functions
def held_keys(keys):
    if keys[pygame.K_w]:
        player_right.move_up()

    if keys[pygame.K_s]:
        player_right.move_down()

    if keys[pygame.K_UP]:
        player_left.move_up()

    if keys[pygame.K_DOWN]:
        player_left.move_down()

def mouse_clicked(position):
    global game_state

    if(game_state == "menu"):
        if(start_button.collidepoint(position)):
            game_state = "playing"
        elif(quit_button.collidepoint(position)):
            pygame.quit()
            quit()

def reset_ball():
    global game_ball
    game_ball = ball.Ball(main_display, screen_size[0] / 2, screen_size[1] / 2)

def score(player):
    global left_score
    global right_score
    global game_ball

    if player == player_left:
        left_score += 1
        reset_ball()
    if player == player_right:
        right_score += 1
        reset_ball()

def check_ball_collision():
    global game_state
    global winning_player

    # Check if hit a paddle
    # TODO Deal with when the ball hits top/bottom of paddle
    if(game_ball.rect.colliderect(player_right.rect) or game_ball.rect.colliderect(player_left.rect)):
        game_ball.reflect_x()

    # Bounce if hit top/bottom
    if not((game_ball.rect.top) > 0 and (game_ball.rect.bottom) < screen_size[1]):
        game_ball.reflect_y()

    # Check if ball went out of screen
    if(game_ball.rect.left >= screen_size[0]):
        score(player_left)

    if(game_ball.rect.right <= 0):
        score(player_right)

def update_screen():
    if(game_state == "menu"):
        main_display.fill(colours.black)
        main_display.blit(start_game_text, start_button)
        main_display.blit(quit_text, quit_button)

        pygame.display.flip()

    if(game_state == "playing"):
        global right_score
        global left_score

        main_display.fill(colours.black)
        player_right.draw()
        player_left.draw()
        check_ball_collision()

        left_score_text = font.render(str(left_score), True, colours.white, colours.black)
        left_score_x = (screen_size[0] / 3) - (left_score_text.get_width() / 2)
        left_score_y = score_indent
        left_score_rect = pygame.Rect(left_score_x, left_score_y, left_score_text.get_width(), left_score_text.get_height())
        main_display.blit(left_score_text, left_score_rect)

        right_score_text = font.render(str(right_score), True, colours.white, colours.black)
        right_score_x = (2 * screen_size[0] / 3) - (right_score_text.get_width() / 2)
        right_score_y = score_indent
        right_score_rect = pygame.Rect(right_score_x, right_score_y, right_score_text.get_width(), right_score_text.get_height())
        main_display.blit(right_score_text, right_score_rect)

        game_ball.update_position()
        game_ball.draw()
        pygame.display.flip()

    if(game_state == "win"):
        game_win(winning_player)

# Main Game Loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_clicked(pygame.mouse.get_pos())

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                reset_ball()
                left_score = 0
                right_score = 0
                game_state = "menu"

    held_keys(pygame.key.get_pressed())

    update_screen()
    clock.tick(60)

pygame.quit()
quit()


from Order import *
from datetime import date
from datetime import datetime

def revenue_report(user):
    list_of_order = load_orders()

    today = date.today()
    date1 = datetime.strptime(str(today), "%Y-%m-%d")

    list_of_revenue = {'store_1': 0, 'store_2': 0, 'store_3': 0, 'store_4': 0, 'store_5': 0, 'store_6': 0, 'store_7': 0,
                       'store_8': 0, 'store_9': 0, 'store_10': 0}

    for order in list_of_order:
        date2 = order.get_date()
        date3 = datetime.strptime(str(date2), "%d-%m-%Y")
        if date3.month + 1 == date1.month:
            list_of_revenue['store_' + order.get_store_id()] += order.get_total_price()

    print("    ********** Welcome " + user.get_emp_name() + " **********    ")
    print("--- Account type: " + user.get_emp_type())
    print("--- Store ID: " + str(user.get_emp_store_no()))
    print("\n")

    print(">>You are currently at Revenue Report page")
    print("\n")
    for x, y in list_of_revenue.items():
        print(x, y)
    print()
    print("\n")

if __name__ == '__main__':
    revenue_report()


"""
This module parses a csv file with with varying  delimiters
"""

import sys
import datetime

def main():
    """
    Main Method to read file and then ask user to query specific record
    """
    records = []        # a list containing all csv file records
    file = open('appointments_peoples_community_clinic.txt')
    count = 0       # counter to count number of records not lines in file
    for line in file:
        values = line.split('\t\t')     # file contains two tabs separated values
        if values[1].isdigit():     # actual records start with a "Per Nbr" attr which is a digit
            birth_date = values[5].split('/')
            appt_date = values[6].split('/')
            birth_date = datetime.date(int(birth_date[2]), int(birth_date[0]), int(birth_date[1]))
            appt_date = datetime.date(int(appt_date[2]), int(appt_date[0]), int(appt_date[1]))
            records.append({'Per Nbr': int(values[1]),
                            'Pat Name': values[2],
                            'Hm Phone': values[3],
                            'Day Phone': values[4],
                            'Birth Dt': birth_date,
                            'Appt Dt': appt_date,
                            'Beg Tm': values[7],
                            'Event': values[8],
                            'Sts': values[9],
                            'Res Name': values[10],
                            'Language': values[12],
                            'Department': values[13]})
            count += 1

    print('Total Rcords: {}'.format(count))     # print total number of actual records
    #   list of attributes in the given file
    attrs = ['Per Nbr', 'Pat Name', 'Hm Phone', 'Day Phone', 'Birth Dt', 'Appt Dt',
             'Beg Tm', 'Event', 'Sts', 'Res Name', 'Language', 'Department']
    loop = True
    prompt = sys.stdin
    while loop:     # keep on asking until user asks to stop entering q
        print('enter record number (from 0, {}) or q to exit : '.format(count - 1))
        num = prompt.readline().rstrip()
        if num == 'q':      # check if user wants to quit
            loop = False
            print('Thank You.')
        elif num.isdigit() and -1 < int(num) < count:
            for i, name in enumerate(attrs):
                print(name, i)
            print('Enter attribute number : ')
            index = prompt.readline().rstrip()

            if index.isdigit() and -1 < int(index) < len(attrs) - 1:
                print('\t\t{} : {}    ({})'
                      .format(attrs[int(index)], records[int(num)][attrs[int(index)]], type(records[int(num)][attrs[int(index)]])))
        else:
            print('Invalid Input')

if __name__ == '__main__':
    main()


#calss header
class _SUSPENSION():
	def __init__(self,):
		self.name = "SUSPENSION"
		self.definitions = [u'the act of stopping something happening, operating, etc. for a period of time: ', u'a punishment in which a person is temporarily not allowed to work, go to school, or take part in an activity: ', u'equipment attached to the wheels of a vehicle that reduces the uncomfortable effects of going over road surfaces that are not even', u'a liquid in which small pieces of solid are contained, but not dissolved: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'nouns'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


import pprint
from test_junkie.runner import Runner
from tests.QualityManager import QualityManager
from tests.junkie_suites.AfterClassExceptionSuite import AfterClassExceptionSuite

runner = Runner([AfterClassExceptionSuite])
runner.run()
results = runner.get_executed_suites()

pprint.pprint(results[0].metrics.get_metrics())
for test in results[0].get_test_objects():
    print(test.get_function_name())
    pprint.pprint(test.metrics.get_metrics())

def test_class_metrics():

    metrics = results[0].metrics.get_metrics()
    QualityManager.check_class_metrics(metrics,
                                       expected_beforeclass_exception_count=1,
                                       expected_beforeclass_exception_object=None,
                                       expected_beforeclass_performance_count=1,

                                       expected_afterclass_exception_count=1,
                                       expected_afterclass_exception_object=Exception,
                                       expected_afterclass_performance_count=1)

def test_test_metrics():

    assert results[0].get_test_objects()
    for test in results[0].get_test_objects():

        metrics = test.metrics.get_metrics()["None"]["None"]
        QualityManager.check_test_metrics(metrics)


"""
Plotagem do caminho de cada bola calculada
pela rotina 'get_speed_ginput.py'
"""

import os
import numpy as np
import matplotlib.pyplot as plt
import cv2

plt.close('all')

pathname = 'fig/frames/'

pos = np.loadtxt('ball_01_pos.txt')

listfiles = np.sort(os.listdir(pathname))

# lista com posicoes
# pos = []

cont = 0
for filename in listfiles[50::10]:

	print (filename)

	img = cv2.imread(pathname + filename)

	cont += 1

	# l, c = pos[:cont]

	plt.figure(figsize=(12,8))
	plt.imshow(img)
	plt.plot(pos[:cont,0], pos[:cont,1], '-*')

	plt.savefig('fig/teste/%s' %filename)

# pos1 = np.array(pos)

plt.close('all')
plt.show()
# np.savetxt('ball_01_pos.txt', pos1, fmt='%i')


"""
Написать функцию host_ping(), в которой с помощью утилиты ping будет
проверяться доступность сетевых узлов. Аргументом функции является список,
в котором каждый сетевой узел должен быть представлен именем хоста или
ip-адресом. В функции необходимо перебирать ip-адреса и проверять их
доступность с выводом соответствующего сообщения («Узел доступен»,
«Узел недоступен»). При этом ip-адрес сетевого узла должен создаваться
с помощью функции ip_address().
"""

import subprocess
import os
import chardet
from ipaddress import ip_address
from pprint import pprint

HOST_LIST = ['10.0.0.1', '8.8.8.8', '192.168.0.1', '5.61.239.21', 'yandex.ru',
             '194.58.97.31']
result = {'Доступные узлы': '', 'Недоступные узлы': ''}

DNULL = open(os.devnull, 'w')  # заглушка, чтобы поток не выводился на экран

def is_ip_adress(ip):
    """
    Проверка на корректность IP-адресо
    :param ip: IP
    :return: ipv4: полученный ip адрес из переданного значения
        Exception: ошибка при невозможности получения ip адреса из значения
    """
    try:
        ipv4 = ip_address(ip)
    except ValueError:
        raise Exception("Некорректный ip адрес")
    return ipv4

def host_ping(host_list, get_list=False):
    for host in host_list:
        try:
            ipv4 = is_ip_adress(host)
        except Exception:
            print(f'{host} - доменное имя')
            ipv4 = host
        # ping_test = subprocess.Popen(['ping -с 1', str(ipv4)], stdout=DNULL)
        ping_test = subprocess.Popen(
            ['ping', '-n', '1', str(ipv4)], stdout=subprocess.PIPE)
        DATA = ping_test.stdout.read()
        RES = chardet.detect(DATA)
        print_res = DATA.decode(RES['encoding'])

        if print_res.find("потеряно = 0") != -1:
            result['Доступные узлы'] += f'{str(ipv4)}, '
            res_string = f'{str(ipv4)} - Узел доступен'
        else:
            result['Недоступные узлы'] += f'{ipv4}, '
            res_string = f'{str(ipv4)} - Узел недоступен'
        if not get_list:  # если результаты не надо добавлять в словарь,
            # значит отображать их в консоли
                print(res_string)
    if get_list:  # если требуется вернуть словарь (для задачи 3),
        # то возвращаем
        return result

if __name__ == '__main__':
    host_ping(HOST_LIST)
    pprint(result)


import json

##Month conversion dict
monthConv = {"JAN":"01","FEB":"02","MAR":"03", "APR":"04","MAY":"05", "JUN":"06", "JUL":"07","SEP":"09","Oct":"10","NOV":"11","DEC":"12"}
monthConv["AUG"]= "08"

totalList = []
with open('exportdict_new.json') as json_data:
    d = json.load(json_data)
with open('exportqty.json') as json_data:
    e = json.load(json_data)
    for key in d.keys():
        totalDict = {}
        pricedata = d[key]
        qtydata = e[key]
        for country in pricedata:
            if country['cat'] == "Total":
                totalDict['date']= key[3:7]+str(monthConv[key[0:3]])
                totalDict['value'] = country['val']
                for country in qtydata:
                    if country['cat'] == "Total":
                        totalDict['qty'] = country['val']
        totalList.append(totalDict.copy())
with open('monthlyTotal.json', 'w') as fp:
    json.dump(totalList, fp, sort_keys=True, indent=4)


dict = {'Sizmo5nov': 111, 'ndoeqfzbdoqf': 22, 'ndoeqfzbdoqf': 233,'ndoefbo11qwzf': 4, 'ndozef2boqf': 235, 'nd3zoefboqf': 655, 'ndoe4fboqf': 5647, 'ndoef62cboqf': 7345, 'ndo67efcboqf': 327, 'ndo2ec4boqf': 7324, 'ndo32efcboqf': 13220 }
print ("Dict : ", dict)

print("Department name : ")
for key in dict:
    print (key)

name = input("Input department name  : ")
if name == 'all':
    l = 0
    for key in dict:
        l = l + dict[key]
    print(l)
elif name == 'Sizmo5nov' or 'ndoeqfzbdoqf' or 'ndoefbo11qwzf' or 'ndoef62cboqf' or 'ndo2ec4boqf' or 'ndoe4fboqf':
    print("Department consisit : ", dict[name])

name_update_department = input("Name update department  : ")
number_people = input("New number people  : ")
dict[name_update_department]= number_people
print ("Update dict : ", dict)

add_new_department = input("Name add department  : ")
number_people = input("New number people  : ")
dict[add_new_department]= number_people
print ("With new department : ", dict)


import random
import time
from threading import Thread

class WaitForUserInput(Thread):
    def run(self):
        # your original code
        a = random.randint(0, 9)
        ans = 2 * a
        q = ""
        q = int(input("Calculate 2 * %d\n" % a))
        # added these lines of code from my side :)
        if q == ans:
            print('You did it!')

def print_message():
    print("You can do it")
    time.sleep(3)

if __name__ == '__main__':
    waiting_for_input = WaitForUserInput()
    waiting_for_input.start()

    while waiting_for_input.is_alive():
        print_message()


# Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.

"""Lease management for machines leased from the Machine Provider.

Keeps a list of machine types which should be leased from the Machine Provider
and the list of machines of each type currently leased.

Swarming integration with Machine Provider
==========================================

handlers_backend.py contains a cron job which looks at each machine type and
ensures the number of active lease requests is equal to the target size
specified by the machine type.

A lease request is considered active as soon as it is initiated. It remains
active while the lease request is pending and even after it is fulfilled. A
lease request is considered no longer active once the request is denied or
the machine used to fulfill the request is reclaimed.

This scheme ensures that we never have more machines of a given type than we
want

Each machine type is stored as a MachineType entity which describes the machine
in terms of Machine Provider Dimensions (not to be confused with Swarming's own
bot dimensions) as well as a target size which describes the number of machines
of this type we want connected at once.

handlers_backend.py calls generate_lease_requests (below) to generate a number
of lease requests equal to the target size minus the current number of active
leases, then performs the RPC to send these requests to the Machine Provider,
and finally it calls update_leases (below) with the results of the lease
request to associate the new active leases with the machine type.

In principle, the entire operation on a single machine type needs to happen
transactionally so we don't make duplicate requests and end up with more
machines than the target size wants. However, in practice we need the RPC
to be outside the transaction because it may be slow and it may need to be
retried, which could cause the entire transaction to time out without logging
the result of the call. Therefore the procedure is broken up into two
transactions with an RPC in between.

With the transaction broken into two, the choice of request ID is the only way
to prevents duplicate lease requests (e.g. if generate_lease_requests runs twice
before update_leases gets to run). Machine Provider supports idempotent RPCs
so long as the client-generated request ID is the same.

Therefore, we ensure generate_lease_requests always generates lease requests
with the same request ID until update_lease is called. This is done by keeping a
count of the number of requests generated so far. If the request count is n,
generate_lease_requests will always generate requests with IDs n + 1, n + 2, ...
up to n + target size - current size, where current size is the number of
currently active lease requests.

update_lease takes the RPC result and updates the pending request entries.

TODO(smut): Consider request count overflow.
"""

import datetime
import logging

from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop

from components import machine_provider
from components import utils
from server import bot_management

class MachineLease(ndb.Model):
  """A lease request for a machine from the Machine Provider.

  Standalone MachineLease entities should not exist in the datastore.
  """
  # Request ID used to generate this request.
  client_request_id = ndb.StringProperty(required=True)
  # Hostname of the machine currently allocated for this request.
  hostname = ndb.StringProperty()
  # Request hash returned by the server for the request for this machine.
  request_hash = ndb.StringProperty()
  # DateTime indicating lease expiration time.
  lease_expiration_ts = ndb.DateTimeProperty()

class MachineType(ndb.Model):
  """A type of machine which should be leased from the Machine Provider.

  Key:
    id: A human-readable name for this machine type.
    kind: MachineType. Is a root entity.
  """
  # Current number of active leases.
  current_size = ndb.ComputedProperty(lambda self: len(self.leases))
  # Description of this machine type for humans.
  description = ndb.StringProperty(indexed=False)
  # Whether or not to attempt to lease machines of this type.
  enabled = ndb.BooleanProperty(default=True)
  # Duration to lease each machine for.
  lease_duration_secs = ndb.IntegerProperty(indexed=False)
  # List of active lease requests.
  leases = ndb.LocalStructuredProperty(MachineLease, repeated=True)
  # machine_provider.Dimensions describing the machine.
  mp_dimensions = msgprop.MessageProperty(
      machine_provider.Dimensions, indexed=False)
  # Number of bots pending deletion.
  num_pending_deletion = ndb.ComputedProperty(
      lambda self: len(self.pending_deletion))
  # List of hostnames whose leases have expired and should be deleted.
  pending_deletion = ndb.StringProperty(indexed=False, repeated=True)
  # Last request number used.
  request_count = ndb.IntegerProperty(default=0, required=True)
  # Request ID base string.
  request_id_base = ndb.StringProperty(indexed=False, required=True)
  # Target number of machines of this type to have leased at once.
  target_size = ndb.IntegerProperty(indexed=False, required=True)

def clean_up_bots():
  """Cleans up expired leases."""
  # Maximum number of in-flight ndb.Futures.
  MAX_IN_FLIGHT = 50

  bot_ids = []
  deleted = {}
  for machine_type in MachineType.query(MachineType.num_pending_deletion > 0):
    logging.info(
        'Deleting bots: %s', ', '.join(sorted(machine_type.pending_deletion)))
    bot_ids.extend(machine_type.pending_deletion)
    deleted[machine_type.key] = machine_type.pending_deletion

  # Generate a few asynchronous requests at a time in order to
  # prevent having too many in-flight ndb.Futures at a time.
  futures = []
  while bot_ids:
    num_futures = len(futures)
    if num_futures < MAX_IN_FLIGHT:
      keys = [bot_management.get_info_key(bot_id)
              for bot_id in bot_ids[:MAX_IN_FLIGHT - num_futures]]
      bot_ids = bot_ids[MAX_IN_FLIGHT - num_futures:]
      futures.extend(ndb.delete_multi_async(keys))

    ndb.Future.wait_any(futures)
    futures = [future for future in futures if not future.done()]

  if futures:
    ndb.Future.wait_all(futures)

  # There should be relatively few MachineType entitites, so
  # just process them sequentially.
  # TODO(smut): Parallelize this.
  for machine_key, hostnames in deleted.iteritems():
    successfully_deleted = []
    for hostname in hostnames:
      if bot_management.get_info_key(hostname).get():
        logging.error('Failed to delete BotInfo: %s', hostname)
      else:
        successfully_deleted.append(hostname)
    logging.info('Deleted bots: %s', ', '.join(sorted(successfully_deleted)))
    _clear_bots_pending_deletion(machine_key, hostnames)

@ndb.transactional
def _clear_bots_pending_deletion(machine_type_key, hostnames):
  """Clears the list of bots pending deletion.

  Args:
    machine_type_key: ndb.Key for a MachineType instance.
    hostnames: List of bots pending deletion.
  """
  machine_type = machine_type_key.get()
  if not machine_type:
    logging.error('MachineType no longer exists: %s', machine_type_key.id())
    return

  num_pending_deletion = len(machine_type.pending_deletion)
  machine_type.pending_deletion = [
      host for host in machine_type.pending_deletion if host not in hostnames]
  if len(machine_type.pending_deletion) != num_pending_deletion:
    machine_type.put()

@ndb.transactional
def generate_lease_requests(machine_type_key, swarming_server):
  """Generates lease requests.

  The list includes new requests to lease machines up to the targeted
  size for the given machine type as well as requests to get the status
  of pending lease requests.

  Args:
    machine_type_key: ndb.Key for a MachineType instance.
    swarming_server: URL for the Swarming server to connect to.

  Returns:
    A list of lease requests.
  """
  machine_type = machine_type_key.get()
  if not machine_type:
    logging.warning('MachineType no longer exists: %s', machine_type_key.id())
    return []

  expired_requests = _clean_up_expired_leases(machine_type)
  lease_requests = _generate_lease_request_status_updates(
      machine_type, swarming_server)

  if not machine_type.enabled:
    logging.warning('MachineType is not enabled: %s\n', machine_type.key.id())
    return lease_requests
  if machine_type.current_size >= machine_type.target_size:
    logging.info(
        'MachineType %s is at capacity: %d/%d',
        machine_type.key.id(),
        machine_type.current_size,
        machine_type.target_size,
    )
    return lease_requests

  new_requests = _generate_lease_requests_for_new_machines(
      machine_type, swarming_server)

  if new_requests or expired_requests:
    machine_type.put()
    lease_requests.extend(new_requests)

  return lease_requests

def _clean_up_expired_leases(machine_type):
  """Cleans up expired leases.

  Prunes expired leases from machine_type.leases,
  but does not write the result to the datastore.

  Args:
    machine_type: MachineType instance.

  Returns:
    A list of leases that were removed.
  """
  active = []
  expired = []

  for request in machine_type.leases:
    if request.hostname and request.lease_expiration_ts <= utils.utcnow():
      logging.warning(
          'Request ID %s expired:\nHostname: %s\nExpiration: %s',
          request.client_request_id,
          request.hostname,
          request.lease_expiration_ts,
      )
      expired.append(request.hostname)
    else:
      active.append(request)

  machine_type.leases = active
  machine_type.pending_deletion.extend(expired)
  return expired

def _generate_lease_request_status_updates(machine_type, swarming_server):
  """Generates status update requests for pending lease requests.

  Args:
    machine_type: MachineType instance.
    swarming_server: URL for the Swarming server to connect to.

  Returns:
    A list of lease requests.
  """
  lease_requests = []
  for request in machine_type.leases:
    if not request.hostname:
      # We don't know the hostname yet, meaning this request is still pending.
      lease_requests.append(machine_provider.LeaseRequest(
          dimensions=machine_type.mp_dimensions,
          duration=machine_type.lease_duration_secs,
          on_lease=machine_provider.Instruction(
              swarming_server=swarming_server),
          request_id=request.client_request_id,
      ))
  return lease_requests

def _generate_lease_requests_for_new_machines(machine_type, swarming_server):
  """Generates requests to lease machines up to the target.

  Extends machine_type.leases by the number of new lease requests generated,
  but does not write the result to the datastore.

  Args:
    machine_type: MachineType instance.
    swarming_server: URL for the Swarming server to connect to.

  Returns:
    A list of lease requests.
  """
  lease_requests = []
  request_number = machine_type.request_count
  for _ in xrange(machine_type.target_size - machine_type.current_size):
    request_number += 1
    request_id = '%s-%d' % (machine_type.request_id_base, request_number)
    lease_requests.append(machine_provider.LeaseRequest(
        dimensions=machine_type.mp_dimensions,
        duration=machine_type.lease_duration_secs,
        on_lease=machine_provider.Instruction(swarming_server=swarming_server),
        request_id=request_id,
    ))
    machine_type.leases.append(MachineLease(client_request_id=request_id))
  machine_type.request_count = request_number
  return lease_requests

@ndb.transactional
def update_leases(machine_type_key, responses):
  """Updates the states of leases of the given machine types.

  Args:
    machine_type_key: ndb.Key for a MachineType instance.
    responses: machine_provider.BatchedLeaseResponse instance.
  """
  machine_type = machine_type_key.get()
  if not machine_type:
    logging.warning('MachineType no longer exists: %s', machine_type_key)
    return

  lease_request_map = {
      request.client_request_id: request for request in machine_type.leases
  }
  for response in responses.get('responses', []):
    request_id = response['client_request_id']
    request = lease_request_map.get(request_id)
    if not request:
      logging.error('Unknown request ID: %s', request_id)
      continue

    if response.get('error'):
      error = machine_provider.LeaseRequestError.lookup_by_name(
          response['error'])
      if error in (
          machine_provider.LeaseRequestError.DEADLINE_EXCEEDED,
          machine_provider.LeaseRequestError.TRANSIENT_ERROR,
      ):
        # Retryable errors. Just try again later.
        logging.warning(
            'Request not processed, trying again later: %s', request_id)
      else:
        # TODO(smut): Handle specific errors.
        logging.warning(
            'Error %s for request ID %s',
            response['error'],
            request_id,
        )
        lease_request_map.pop(request_id)
    else:
      request.request_hash = response['request_hash']
      state = machine_provider.LeaseRequestState.lookup_by_name(
          response['state'])
      if state == machine_provider.LeaseRequestState.DENIED:
        logging.warning('Request ID denied: %s', request_id)
        lease_request_map.pop(request_id)
      elif state == machine_provider.LeaseRequestState.FULFILLED:
        if response.get('hostname'):
          logging.info(
              'Request ID %s fulfilled:\nHostname: %s\nExpiration: %s',
              request_id,
              response['hostname'],
              response['lease_expiration_ts'],
          )
          request.hostname = response['hostname']
          request.lease_expiration_ts = datetime.datetime.utcfromtimestamp(
              int(response['lease_expiration_ts']))
        else:
          # Lease expired. This shouldn't happen, because it means we had a
          # pending request which was fulfilled and expired before we were
          # able to check its status.
          logging.warning('Request ID fulfilled and expired: %s', request_id)
          lease_request_map.pop(request_id)
      else:
        # Lease request isn't processed yet. Just try again later.
        logging.info(
            'Request ID %s in state: %s', request_id, response['state'])

  machine_type.leases = sorted(
      lease_request_map.values(), key=lambda lease: lease.client_request_id)
  machine_type.put()


#  File: Train.py

#  Description: Using the tools that come with the turtle graphics package, this program draws a fairly detailed train

#  Student Name: Blake Kappel

#  Student UT EID: bak792

#  Course Name: CS 313E

#  Unique Number: 51730

#  Date Created: 2/20/2015

#  Date Last Modified: 2/21/2015

########################################################################

import turtle, math

# Draws a line, give 2 sets coordinates
def drawLine (ttl, x1, y1, x2, y2):
  ttl.penup()
  ttl.goto (x1, y1)
  ttl.pendown()
  ttl.goto (x2, y2)
  ttl.penup()

# Differs from drawRectangle by filling in the shape with color
def fillRectangle (ttl, x, y, side1, side2):
  ttl.penup()
  ttl.goto(x, y)
  ttl.begin_fill()
  ttl.pendown()
  ttl.forward(side1)
  ttl.right(90)
  ttl.forward(side2)
  ttl.right(90)
  ttl.forward(side1)
  ttl.right(90)
  ttl.forward(side2)
  ttl.right(90)
  ttl.end_fill()

# Draws rectangle
def drawRectangle (ttl, x, y, side1, side2):
  ttl.penup()
  ttl.goto(x, y)
  ttl.pendown()
  ttl.forward(side1)
  ttl.right(90)
  ttl.forward(side2)
  ttl.right(90)
  ttl.forward(side1)
  ttl.right(90)
  ttl.forward(side2)
  ttl.right(90)

# Train tracks function
def drawTracks(ttl, x = -350, y = -300, length = 700, numNotch = 13, lenNotch = 30, widNotch = 5):
  ttl.penup()
  ttl.goto(x, y)
  ttl.pendown()
  ttl.fd(length)
  ttl.penup()
  ttl.goto(x, y - 20)
  ttl.pendown()
  ttl.fd(length)
  inc = length // numNotch
  for i in range (numNotch):
    drawRectangle(ttl, (x + 10) + (i * inc), y - 20, lenNotch, widNotch)

# Draws the wheels
def drawWheel(ttl, x, y, outRadius, midRadius, inRadius):
  ttl.penup()
  ttl.goto(x, y)
  ttl.pendown()
  ttl.circle(outRadius)
  ttl.penup()
  ttl.goto(x, y + (outRadius - midRadius))
  ttl.pendown()
  ttl.circle(midRadius)
  ttl.penup()
  ttl.goto(x, y + (outRadius - inRadius))
  xCor, yCor = ttl.xcor(), ttl.ycor() # x and y for spokes later
  ttl.pendown()
  ttl.circle(inRadius)
  ttl.penup()

  # Spokes
  length = midRadius - inRadius
  angle = 0
  while (angle < 360):
    ttl.penup()
    ttl.goto(xCor, yCor)
    # first line
    ttl.right(85)
    ttl.pendown()
    ttl.fd(length)
    # second line
    ttl.penup()
    ttl.goto(xCor, yCor)
    ttl.right(10)
    ttl.pendown()
    ttl.fd(length)
    # 45 degree circle segment
    ttl.penup()
    ttl.goto(xCor,yCor)
    ttl.left(95)
    ttl.circle(inRadius, 45)
    xCor, yCor = ttl.xcor(), ttl.ycor()
    angle += 45

# Draws cab part of train
def drawCab(ttl, x, y, wheelRadius):
  ttl.penup()
  ttl.goto(x, y)
  ttl.pendown()
  width = wheelRadius * 2 + wheelRadius
  ttl.forward(width)
  ttl.right(90)
  ttl.fd(325)
  inc = wheelRadius // 2 - 5
  ttl.right(90)
  ttl.fd(inc)
  ttl.right(90)
  ttl.circle(wheelRadius + (inc//2), 180,)
  ttl.right(90)
  ttl.fd(inc)
  ttl.right(90)
  ttl.fd(325)
  ttl.right(90)
  ttl.fd(25)

  # Windows and top part of cab
  drawRectangle(ttl, ttl.xcor() -50, ttl.ycor() + 10, width + 75, 10)
  ttl.fillcolor('gray')
  fillRectangle(ttl, ttl.xcor() +50, ttl.ycor() - 30, 75, 100)
  fillRectangle(ttl, ttl.xcor() + 100, ttl.ycor(), 75, 100)

# Main body of train
def drawBody(ttl, x, y, wheelRadius):
  ttl.penup()
  ttl.goto(x, y)
  ttl.pendown()
  length = wheelRadius * 4 + 130
  ttl.forward(length)
  ttl.right(90)
  ttl.fd(275)
  inc = wheelRadius // 2 - 5
  ttl.right(90)
  ttl.fd(inc)
  ttl.right(90)
  ttl.circle(wheelRadius + (inc//2), 180,)
  ttl.right(90)
  ttl.fd(inc)
  ttl.right(90)
  ttl.circle(wheelRadius + (inc//2), 180)
  ttl.right(90)
  ttl.fd(inc)
  ttl.right(90)
  ttl.fd(275)
  ttl.right(90)
  ttl.fd(25)

# Draws rivets using dot built-infunction, horizontally
def drawRivetsHorizontal(ttl, x, y, limit, space):
  length = 0
  while (length < limit):
    length += space
    x += space
    ttl.penup()
    ttl.goto(x, y)
    ttl.pendown()
    ttl.dot(8, 'black')

# Draws rivets vertically
def drawRivetsVertical(ttl, x, y, limit, space):
  length = 0
  while (length < limit):
    length += space
    y += space
    ttl.penup()
    ttl.goto(x, y)
    ttl.pendown()
    ttl.dot(8, 'black')

# Draws a 4-point figure, used for trapezoid figures
def drawTrap(ttl, x1, y1, x2, y2, x3, y3, x4, y4):
  ttl.penup()
  ttl.goto(x1, y1)
  drawLine(ttl, x1, y1, x2, y2)
  drawLine(ttl, x2, y2, x3, y3)
  drawLine(ttl, x3, y3, x4, y4)
  drawLine(ttl, x4, y4, x1, y1)

def main():

  turtle.title('Choo-choo')
  turtle.setup(800, 800, 0, 0)
  ttl = turtle.Turtle()
  ttl.speed(0)
  ttl.pensize(3)

  drawTracks(ttl, -350, -200, 700)

  ttl.color('red')
  drawWheel(ttl, -250, -200, 75, 55, 10)
  drawWheel(ttl, -13, -200, 70, 50, 9)
  drawWheel(ttl, 190, -200, 70, 50, 9)

  ttl.color('blue')
  drawCab(ttl, -350, 200, 75)

  drawBody(ttl, -105, 150, 70)

  drawRectangle(ttl, -25, 170, 75, 20)
  drawRectangle(ttl, -10, 180, 45, 10)

  drawRectangle(ttl, 305, 100, 20, 100)
  drawRectangle(ttl, 325, 75, 10, 50)

  drawLine(ttl, -130, 25, 305, 25)
  drawLine(ttl, -130, 5, 305, 5)

  drawRivetsHorizontal(ttl, -130, 15, 425, 10)

  drawLine(ttl, -30, 150, -30, 25)
  drawLine(ttl, -50, 150, -50, 25)

  drawRivetsVertical(ttl, -40, 25, 115, 10)

  drawLine(ttl, 180, 150, 180, 25)
  drawLine(ttl, 200, 150, 200, 25)

  drawRivetsVertical(ttl, 190, 25, 115, 10)

  drawTrap(ttl, 305, -100, 355, -100, 380, -150, 305, -150)
  drawTrap(ttl, 170, 150, 150, 250, 230, 250, 210, 150)
  drawTrap(ttl, 150, 250, 160, 275, 220, 275, 230, 250)

  turtle.done()

main()


import itertools
import time
import django.test
from six.moves import range
from six.moves import zip

from otree import constants_internal
import otree.common_internal
from otree.common_internal import id_label_name

from otree.common import Currency as c
from otree.db import models
from otree.models_concrete import ParticipantToPlayerLookup
from otree.models.session import Session
from otree.models.varsmixin import ModelWithVars

class Participant(ModelWithVars):

    class Meta:
        ordering = ['pk']
        app_label = "otree"
        index_together = ['session', 'mturk_worker_id', 'mturk_assignment_id']

    exclude_from_data_analysis = models.BooleanField(
        default=False, doc=(
            "if set to 1, the experimenter indicated that this participant's "
            "data points should be excluded from the data analysis (e.g. a "
            "problem took place during the experiment)"
        )
    )

    session = models.ForeignKey(Session)
    time_started = models.DateTimeField(null=True)
    user_type_in_url = constants_internal.user_type_participant
    mturk_assignment_id = models.CharField(
        max_length=50, null=True)
    mturk_worker_id = models.CharField(max_length=50, null=True)
    mturk_reward_paid = models.BooleanField(default=False)
    mturk_bonus_paid = models.BooleanField(default=False)

    start_order = models.PositiveIntegerField(db_index=True)

    # unique=True can't be set, because the same external ID could be reused
    # in multiple sequences. however, it should be unique within the sequence.
    label = models.CharField(
        max_length=50, null=True, doc=(
            "Label assigned by the experimenter. Can be assigned by passing a "
            "GET param called 'participant_label' to the participant's start "
            "URL"
        )
    )

    _index_in_subsessions = models.PositiveIntegerField(default=0, null=True)

    _index_in_pages = models.PositiveIntegerField(default=0, db_index=True)

    id_in_session = models.PositiveIntegerField(null=True)

    def _id_in_session(self):
        """the human-readable version."""
        return 'P{}'.format(self.id_in_session)

    _waiting_for_ids = models.CharField(null=True, max_length=300)

    code = models.RandomCharField(
        length=8, db_index=True,
        doc=(
            "Randomly generated unique identifier for the participant. If you "
            "would like to merge this dataset with those from another "
            "subsession in the same session, you should join on this field, "
            "which will be the same across subsessions."
        )
    )

    last_request_succeeded = models.BooleanField(
        verbose_name='Health of last server request'
    )

    visited = models.BooleanField(
        default=False, db_index=True,
        doc="""Whether this user's start URL was opened"""
    )

    ip_address = models.GenericIPAddressField(null=True)

    # stores when the page was first visited
    _last_page_timestamp = models.PositiveIntegerField(null=True)

    _last_request_timestamp = models.PositiveIntegerField(null=True)

    is_on_wait_page = models.BooleanField(default=False)

    # these are both for the admin
    # In the changelist, simply call these "page" and "app"
    _current_page_name = models.CharField(max_length=200, null=True,
                                          verbose_name='page')
    _current_app_name = models.CharField(max_length=200, null=True,
                                         verbose_name='app')

    # only to be displayed in the admin participants changelist
    _round_number = models.PositiveIntegerField(
        null=True
    )

    _current_form_page_url = models.URLField()

    _max_page_index = models.PositiveIntegerField()

    _is_auto_playing = models.BooleanField(default=False)

    def _start_auto_play(self):
        self._is_auto_playing = True
        self.save()

        client = django.test.Client()

        if not self.visited:
            client.get(self._start_url(), follow=True)

    def _stop_auto_play(self):
        self._is_auto_playing = False
        self.save()

    def _current_page(self):
        return '{}/{} pages'.format(
            self._index_in_pages, self._max_page_index
        )

    def get_players(self):
        """Used to calculate payoffs"""
        lst = []
        app_sequence = self.session.config['app_sequence']
        for app in app_sequence:
            models_module = otree.common_internal.get_models_module(app)
            players = models_module.Player.objects.filter(
                participant=self
            ).order_by('round_number')
            lst.extend(list(players))
        return lst

    def status(self):
        if not self.visited:
            return 'Not visited yet'

        # check if they are disconnected
        max_seconds_since_last_request = max(
            constants_internal.form_page_poll_interval_seconds,
            constants_internal.wait_page_poll_interval_seconds,
        ) + 10  # for latency
        if self._last_request_timestamp is None:
            # it shouldn't be None, but sometimes is...race condition?
            time_since_last_request = 0
        else:
            time_since_last_request = (
                time.time() - self._last_request_timestamp
            )
        if time_since_last_request > max_seconds_since_last_request:
            return 'Disconnected'
        if self.is_on_wait_page:
            if self._waiting_for_ids:
                return 'Waiting for {}'.format(self._waiting_for_ids)
            return 'Waiting'
        return 'Playing'

    def _pages(self):
        from otree.views.concrete import WaitUntilAssignedToGroup

        pages = []
        for player in self.get_players():
            app_name = player._meta.app_config.name
            views_module = otree.common_internal.get_views_module(app_name)
            subsession_pages = (
                [WaitUntilAssignedToGroup] + views_module.page_sequence
            )
            pages.extend(subsession_pages)
        return pages

    def _pages_as_urls(self):
        return [
            View.url(self, index) for index, View in enumerate(self._pages())
        ]

    def _url_i_should_be_on(self):
        if self._index_in_pages <= self._max_page_index:
            return self._pages_as_urls()[self._index_in_pages]
        else:
            if self.session.mturk_HITId:
                assignment_id = self.mturk_assignment_id
                if self.session.mturk_sandbox:
                    url = (
                        'https://workersandbox.mturk.com/mturk/externalSubmit'
                    )
                else:
                    url = "https://www.mturk.com/mturk/externalSubmit"
                url = otree.common_internal.add_params_to_url(
                    url,
                    {
                        'assignmentId': assignment_id,
                        'extra_param': '1'  # required extra param?
                    }
                )
                return url
            from otree.views.concrete import OutOfRangeNotification
            return OutOfRangeNotification.url(self)

    def build_participant_to_player_lookups(self, num_pages_in_each_app):

        def pages_for_player(player):
            return num_pages_in_each_app[player._meta.app_config.name]

        indexes = itertools.count()

        ParticipantToPlayerLookup.objects.bulk_create([
            ParticipantToPlayerLookup(
                participant_pk=self.pk,
                page_index=page_index,
                app_name=player._meta.app_config.name,
                player_pk=player.pk,
            )
            for player in self.get_players()
            for _, page_index in zip(
                range(pages_for_player(player) + 1),
                indexes
            )
            # +1 is for WaitUntilAssigned...
        ])

        self._max_page_index = next(indexes) - 1
        self.save()

    def __unicode__(self):
        return self.name()

    def _start_url(self):
        return '/InitializeParticipant/{}'.format(self.code)

    @property
    def payoff(self):
        return sum(player.payoff or c(0) for player in self.get_players())

    def payoff_in_real_world_currency(self):
        return self.payoff.to_real_world_currency(
            self.session
        )

    def payoff_from_subsessions(self):
        """Deprecated on 2015-05-07.
        Remove at some point.
        """
        return self.payoff

    def money_to_pay(self):
        return (
            self.session.config['participation_fee'] +
            self.payoff.to_real_world_currency(self.session)
        )

    def total_pay(self):
        return self.money_to_pay()

    def payoff_is_complete(self):
        return all(p.payoff is not None for p in self.get_players())

    def name(self):
        return id_label_name(self.pk, self.label)


from pyswip import *

prolog = Prolog()
prolog.consult('noahs_problem.pl')
step = Functor('step', 1)
num_possible = Functor('possible_stairs', 2)

def staircase(top_stair, possible_steps):
    for s in possible_steps:
        prolog.assertz(f'step({s})')

    Possiblities = Variable()

    q = prolog.query(f'possible_stairs({top_stair}, Possiblities)')
    val = next(q)['Possiblities']
    q.close()

    for s in possible_steps:
        prolog.retract(f'step({s})')

    return val


from django.core.exceptions import ObjectDoesNotExist
from bitrix_data.models import BitrixProject, BitrixTask, BitrixUser

def get_user_id(user_id):
    try:
        user = BitrixUser.objects.get(user_id=user_id)
    except ObjectDoesNotExist:
        user = BitrixUser.objects.get(user_id=1)
    return user

def get_group_id(group_id):
    try:
        group = BitrixProject.objects.get(project_id=group_id)
    except ObjectDoesNotExist:
        group = BitrixProject.objects.get(project_id=0)
    return group


# Copyright 2017 AT&T Intellectual Property.  All other rights reserved.
#
# 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.
from datetime import timedelta

import airflow
import failure_handlers
from airflow import DAG
from airflow.operators import ConcurrencyCheckOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.subdag_operator import SubDagOperator

from armada_deploy_site import deploy_site_armada
from deckhand_get_design import get_design_deckhand
from drydock_deploy_site import deploy_site_drydock
from validate_site_design import validate_site_design
"""
update_site is the top-level orchestration DAG for updating a site using the
Undercloud platform.

TODO: We will disable pre-flight checks for now and will revisit it at
      a later date. The pre-flight checks will be more targeted in the
      case of 'update_site' and will include specific checks on things
      like coredns, calico and ceph.
"""

ARMADA_BUILD_DAG_NAME = 'armada_build'
DAG_CONCURRENCY_CHECK_DAG_NAME = 'dag_concurrency_check'
DECKHAND_GET_DESIGN_VERSION = 'deckhand_get_design_version'
DRYDOCK_BUILD_DAG_NAME = 'drydock_build'
PARENT_DAG_NAME = 'update_site'
VALIDATE_SITE_DESIGN_DAG_NAME = 'validate_site_design'

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(1),
    'email': [''],
    'email_on_failure': False,
    'email_on_retry': False,
    'provide_context': True,
    'retries': 0,
    'retry_delay': timedelta(seconds=30),
}

dag = DAG(PARENT_DAG_NAME, default_args=default_args, schedule_interval=None)
"""
Define push function to store the content of 'action' that is
defined via 'dag_run' in XCOM so that it can be used by the
Operators
"""

def xcom_push(**kwargs):
    # Pushes action XCom
    kwargs['ti'].xcom_push(key='action',
                           value=kwargs['dag_run'].conf['action'])

action_xcom = PythonOperator(
    task_id='action_xcom', dag=dag, python_callable=xcom_push)

concurrency_check = ConcurrencyCheckOperator(
    task_id=DAG_CONCURRENCY_CHECK_DAG_NAME,
    on_failure_callback=failure_handlers.step_failure_handler,
    dag=dag)

get_design_version = SubDagOperator(
    subdag=get_design_deckhand(
        PARENT_DAG_NAME, DECKHAND_GET_DESIGN_VERSION, args=default_args),
    task_id=DECKHAND_GET_DESIGN_VERSION,
    on_failure_callback=failure_handlers.step_failure_handler,
    dag=dag)

validate_site_design = SubDagOperator(
    subdag=validate_site_design(
        PARENT_DAG_NAME, VALIDATE_SITE_DESIGN_DAG_NAME, args=default_args),
    task_id=VALIDATE_SITE_DESIGN_DAG_NAME,
    on_failure_callback=failure_handlers.step_failure_handler,
    dag=dag)

drydock_build = SubDagOperator(
    subdag=deploy_site_drydock(
        PARENT_DAG_NAME, DRYDOCK_BUILD_DAG_NAME, args=default_args),
    task_id=DRYDOCK_BUILD_DAG_NAME,
    on_failure_callback=failure_handlers.step_failure_handler,
    dag=dag)

armada_build = SubDagOperator(
    subdag=deploy_site_armada(
        PARENT_DAG_NAME, ARMADA_BUILD_DAG_NAME, args=default_args),
    task_id=ARMADA_BUILD_DAG_NAME,
    on_failure_callback=failure_handlers.step_failure_handler,
    dag=dag)

# DAG Wiring
concurrency_check.set_upstream(action_xcom)
get_design_version.set_upstream(concurrency_check)
validate_site_design.set_upstream(get_design_version)
drydock_build.set_upstream(validate_site_design)
armada_build.set_upstream(drydock_build)


from threading import Timer
import json

import cherrypy
from ws4py.websocket import WebSocket
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from syfra.api.clock import Clock

rt = None

class WebSocketHandler(WebSocket):

    def opened(self):
        """
        When opening a connection, we associate
        a client object with an AuthRoutine which the
        representation depends on the memory address of
        the client object.

        str(AuthRoutine) == AuthRoutine_str(id(client))
        Example: AuthRoutine_177770001

        Each client can access and modify its own data
        specifying the AuthRoutine which was communicated
        to them after the connexion.
        """
        auth_routine = rt.AuthRoutineClass(self, rt)
        rt.setClient(self, auth_routine)
        rt.registerRoutine(auth_routine)
        rt.registerModel(rt.ClientModelClass(self))

    def received_message(self, msg):
        try:
            dct = json.loads(str(msg))
        except ValueError:
            self.send("Bad msg")
            return

        r = dct["routine"]
        routines = rt.getRoutines()
        if r in routines:
            rt.executeRoutine(r, dct["data"])
            rt.setClient(self, routines[r])

    def closed(self, code, reason="No reason"):
        self.rt.removeClient(self)

class WebSocketApp(object):

    def __init__(self, host, port, clock):
        self.host = host
        self.port = port
        self.scheme = 'ws'
        self.clock = Clock(clock, WebSocketApp.replicate)
        self.clock.start()

    @staticmethod
    def replicate():
        rt.replicate()

    @cherrypy.expose
    def index(self):
        return "nothing here"

    @cherrypy.expose
    def ws(self):
        cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))

def start_server(host, port, rt_instance, clock):

    global rt
    rt = rt_instance

    cherrypy.config.update({'server.socket_port': port})
    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()
    cherrypy.quickstart(WebSocketApp(host, port, clock), '', config={
        '/ws': {
            'tools.websocket.on': True,
            'tools.websocket.handler_cls': WebSocketHandler
        },
    })


"""详情页测试案例"""
import unittest
from pprint import pprint

import requests

from wenshu_utils.document.parse import parse_detail
from wenshu_utils.wzws.decrypt import decrypt_wzws

class DetailPageTestCase(unittest.TestCase):
    def setUp(self):
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
        })

        self.error_msg = "请开启JavaScript并刷新该页"

    def tearDown(self):
        self.session.close()

    def test_detail_page(self):
        url = "http://wenshu.court.gov.cn/CreateContentJS/CreateContentJS.aspx"
        params = {
            "DocID": "a8b745f3-43ac-402c-99bf-68b9a9cae635",
        }
        response = self.session.get(url, params=params)
        text = response.content.decode()

        if self.error_msg in text:
            retry = 3
            for _ in range(retry):
                redirect_url = decrypt_wzws(text)
                response = self.session.get(redirect_url)
                text = response.content.decode()
                if self.error_msg not in text:
                    break
            else:
                self.fail("连续{}次获取数据失败".format(retry))

        group_dict = parse_detail(response.text)
        pprint(group_dict)

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


#!/usr/bin/env python3

import unittest

import itermae

import regex
from Bio import SeqIO

class TestItermae(unittest.TestCase):

    def setUp(self):
        self.input_fastq = "example-data/test.fastq"

    def test_MatchScores(self):
        this = itermae.MatchScores(1,2,3)
        self.assertEqual(this.substitutions,1)
        self.assertEqual(this.insertions,2)
        self.assertEqual(this.deletions,3)
        self.assertEqual(this.flatten(),"1_2_3")

    def test_GroupStats(self):
        this = itermae.GroupStats(5,15)
        self.assertEqual(this.start,5)
        self.assertEqual(this.end,15)
        self.assertEqual(this.length,10)
        self.assertEqual(this.flatten(),"5_15_10")

    def test_SeqHolder_initial(self):
        input_seqs = SeqIO.parse(self.input_fastq,"fastq")
        for i in input_seqs:
            this = itermae.SeqHolder(i,verbosity=3)
            self.assertEqual(this.verbosity,3)
            self.assertDictEqual(this.match_scores,{})
            self.assertDictEqual(this.group_stats,{})
            self.assertEqual(this.seqs['dummyspacer'].seq,'X')
            self.assertEqual(this.seqs['dummyspacer'].id,'dummyspacer')

    def test_SeqHolder_matchAndFilter(self):
        input_seqs = SeqIO.parse(self.input_fastq,"fastq")
        filter_results = []
        outputs = []
        reports = []
        for i in input_seqs:
            this = itermae.SeqHolder(i,verbosity=0)
            this.apply_operation('a','input',
                regex.compile("(?P<sample>[ATCG]{5})(?P<fixed1>GTCCACGAGGTC){e<=2}(?P<rest>TCT.*){e<=1}",
                    regex.BESTMATCH) )
            this.apply_operation('b','rest',
                regex.compile("(?P<tag>TCT){e<=1}(?P<strain>[ATCG]{10,26})CGTACGCTGCAGGTCGAC",
                    regex.BESTMATCH) )
            this.apply_operation('c','rest',
                regex.compile("(?P<fixed2>CGTACGCTGCAGGTC)(?<UMItail>GAC[ATCG]G[ATCG]A[ATCG]G[ATCG]G[ATCG]G[ATCG]GAT){s<=2}",
                    regex.BESTMATCH) )
            this.apply_operation('a','UMItail',
                regex.compile("(GAC(?P<umi1>[ATCG])G(?<umi2>[ATCG])A(?<umi3>[ATCG])G(?<umi4>[ATCG])G(?<umi5>[ATCG])G(?<umi6>[ATCG])G){e<=2}",
                    regex.BESTMATCH) )
            filter_results.append(
                this.apply_filters(['sample.length == 5 and rest.start >= 15'])
                )
            try:
                this_output = this.build_output(
                        "input.id+'_'+sample.seq+'_'+umi1.seq+umi2.seq+umi3.seq",
                        "strain" )
                outputs.append( ( this_output.id, this_output.seq ) )
                reports.append(this.format_report("pass",this_output.seq,
                        filter_results))
            except:
                outputs.append(None)
                reports.append(this.format_report("fail",this.seqs['input'],
                        filter_results))
        self.assertListEqual(filter_results,[[True],[True],[False],[True]])
        self.assertListEqual(outputs,[None,None,None,
                ('NB501157:100:H5J5LBGX2:1:11101:10000:19701_CTACT_GAG',
                    'GATGCACTGCGTTCCATGTT')
                ])

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


from torch.utils.data import Dataset
import numpy as np
import pickle
import os
from CustomCorpus import corpus as cc
import argparse

class TrigramsDataset(Dataset):
    def __init__(self, params):
        self.params = params
        self.context_ids = None
        self.target_ids = None
        self.sentences = ''
        self.vocab = None
        self.word_to_ix = {}
        assert (params.clean_dir is not None), "Must include a clean corpus parameter."
        self.sentences = load_corpus(params.clean_dir)
        self.prepare_trigrams()

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

    def __getitem__(self, idx):
        context = self.context_ids.iloc(idx)
        target = self.target_ids.iloc(idx)
        sample = {'context': context, 'target': target}
        return sample

    def prepare_trigrams(self, clip=False):
        # build a list of tuples.  Each tuple is ([ word_i-2, word_i-1 ], target word)
        trigrams = [([self.sentences[i], self.sentences[i + 1]], self.sentences[i + 2])
                    for i in range(len(self.sentences) - 2)]

        self.vocab = set(self.sentences)
        self.word_to_ix = {word: i for i, word in enumerate(self.vocab)}

        context_idxs = np.zeros([len(trigrams), 2], dtype=np.long)
        target_idxs = np.zeros([len(trigrams), 1], dtype=np.long)

        i = 0
        for context, target in trigrams:
            # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words
            # into integer indices and wrap them in variables)
            ids = [self.word_to_ix[w] for w in context]
            context_idxs[i, 0] = ids[0]
            context_idxs[i, 1] = ids[1]
            target_idxs[i, 0] = [self.word_to_ix[target]][0]
            i += 1

        if not clip:
            self.context_ids = context_idxs
            self.target_ids = target_idxs
        else:
            self.context_ids = context_idxs[0:clip]
            self.target_ids = target_idxs[0:clip]

def load_corpus(in_clean, in_root=None, in_reload=False):
    # This tests for a clean file.  If it does not exist, it asserts that the directory
    # is at least accessible to save a clean file in.
    if not os.path.exists(in_clean):
        # in_reload = True
        assert (os.path.exists(os.path.dirname(in_clean))), "%s does not exist. Please check for the" \
                                                            " file and reload from the root directory" \
                                                            " using --reload and --root." % in_clean

        print("Could not load corpus from %s. Creating corpus." % in_clean)
        beigebooks = cc.Corpus()
        beigebooks.set_root(in_root)
        beigebooks.load_corpus()
        beigebooks.cleanse()
        sentences = beigebooks.return_documents(style='JOINED')
        pickle.dump(sentences, open(in_clean, 'wb'))
        print("Corpus saved to %s" % in_clean)

        return sentences
    # This tests for a clean file and will use the file if the reload flag is not set
    # to True, meaning reload from the corpus
    elif os.path.exists(in_clean) and not in_reload:
        print("Loading corpus from %s" % in_clean)
        sentences = pickle.load(open(in_clean, 'rb'))
        return sentences

    elif in_reload:
        print("in_root: ", repr(in_root))
        print(type(in_root))
        assert (os.path.exists(in_root)), 'the root directory is not provided or invalid. A' \
                                          ' valid root must be provided if reloading data from the corpus.' \
                                          ' Root passed is \n%s' % in_root
        return False

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--root', dest='root_dir', default=None,
                        help='the root directory of the corpus')
    parser.add_argument('--clean', dest='clean_dir',  required=True,
                        help='the directory to save the cleansed text to or load from')
    parser.add_argument('--reload', dest='reload', action='store_true')
    return parser.parse_args()

""" Call this main function directly from the command line to recreate the corpus file. You
    do not need to call it every time only when there is new data in the corpus or the
    corpus.pkl file does not exists.  The corpus.pkl file is the cleansed corpus.
"""
if __name__ == '__main__':
    params = get_args()

    corpus = load_corpus(in_root=params.root_dir, in_clean=params.clean_dir)


import json
import re
from collections import defaultdict
from math import log2

class BigramHMM:
    def __init__(self, training_data, k=0.01):
        self.unk_threshold = 2
        self.k = k
        self.training_data = self.tokenize_file(training_data)
        self.training_data = self.replace_word_classes(self.training_data)
        self.vocab = self._build_vocab()
        self.training_data = self.trim_low_freq(self.training_data)
        self.tag_counts = self._build_tag_counts()
        self.tags = list(self.tag_counts.keys() - ['<s>'])
        self.number_of_tags = len(self.tags)
        self.bigram_tag_counts = self._build_bigram_tag_counts()
        self.emission_counts = self._build_emission_counts()

    @staticmethod
    def tokenize_file(filename):
        with open(filename) as f:
            sequences = f.readlines()

        sequences = [json.loads(s) for s in sequences]
        # sequences will be a list (all tag sequences) of lists (individual sequences) of lists (word and tag)
        return sequences

    @staticmethod
    def replace_word_classes(sequences):
        # create closed vocab by replacing #, @, and urls with tokens. trim low freq words.
        url_pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
        for i in range(len(sequences)):
            for j in range(len(sequences[i])):
                sequences[i][j][0] = sequences[i][j][0].lower()
                word = sequences[i][j][0]
                if word.startswith('@'):
                    sequences[i][j][0] = '<@>'
                if word.startswith('#'):
                    sequences[i][j][0] = '<#>'
                if url_pattern.match(word):
                    sequences[i][j][0] = '<url>'

        return sequences

    def _build_vocab(self):
        word_counts = defaultdict(int)
        vocab = set()

        for seq in self.training_data:
            for word, tag in seq:
                word_counts[word] += 1

        for i in range(len(self.training_data)):
            for j in range(len(self.training_data[i])):
                word = self.training_data[i][j][0]
                if word_counts[word] > self.unk_threshold:
                    vocab.add(word)

        return vocab

    def trim_low_freq(self, sequences):
        for i in range(len(sequences)):
            for j in range(len(sequences[i])):
                word = sequences[i][j][0]
                if word not in self.vocab:
                    sequences[i][j][0] = '<unk>'

        return sequences

    def _build_tag_counts(self):
        tag_counts = defaultdict(int)
        # add a start tag for each sentence
        tag_counts['<s>'] = len(self.training_data)
        for seq in self.training_data:
            for word, tag in seq:
                tag_counts[tag] += 1

        return tag_counts

    def _build_bigram_tag_counts(self):
        bigram_tag_counts = defaultdict(lambda: defaultdict(int))
        for seq in self.training_data:
            tags = list(zip(*seq))[1]
            # add values for (<start>, tag1)
            bigram_tag_counts['<s>'][tags[0]] += 1
            for tag1, tag2 in zip(tags, tags[1:]):
                bigram_tag_counts[tag1][tag2] += 1

        return bigram_tag_counts

    def _build_emission_counts(self):
        emission_counts = defaultdict(lambda: defaultdict(int))
        for seq in self.training_data:
            for word, tag in seq:
                emission_counts[tag][word] += 1

        return emission_counts

    def compute_transmission_mle(self, tag1, tag2):
        return (self.bigram_tag_counts[tag1][tag2] + self.k) / (self.tag_counts[tag1] + self.k * self.number_of_tags)

    def compute_emission_mle(self, tag, word):
        return (self.emission_counts[tag][word] + self.k) / (
                    self.tag_counts[tag] + self.k * len(self.vocab))

    def generate_tag_sequence(self, sentence):
        # sentence should be a list of words

        # first value refs tag column, second value refs word row
        v_matrix = [[0] * len(sentence) for _ in range(self.number_of_tags)]
        bp_matrix = [[0] * len(sentence) for _ in range(self.number_of_tags)]

        for i, tag in enumerate(self.tags):
            trans_prob = log2(self.compute_transmission_mle('<s>', tag))
            emi_prob = log2(self.compute_emission_mle(tag, sentence[0]))
            v_matrix[i][0] = trans_prob + emi_prob
            bp_matrix[i][0] = -1

        # start filling it the matrix at observation 1 since we initialized 0 above
        for i, word in enumerate(sentence[1:], 1):
            for j, current_tag in enumerate(self.tags):
                current_maxprob = float('-inf')
                current_maxbp = -1
                emi_prob = log2(self.compute_emission_mle(current_tag, word))
                for k, prev_tag in enumerate(self.tags):
                    prev_v = v_matrix[k][i - 1]
                    trans_prob = log2(self.compute_transmission_mle(prev_tag, current_tag))
                    current_v = prev_v + emi_prob + trans_prob
                    if current_v > current_maxprob:
                        current_maxprob = current_v
                        current_maxbp = k
                v_matrix[j][i] = current_maxprob
                bp_matrix[j][i] = current_maxbp

        # need a tag-index map to decode
        index_tag_map = defaultdict(str)
        for i, tag in enumerate(self.tags):
            index_tag_map[i] = tag

        # the best path will start at max v_matrix tag for the last sentence
        bestpathprob = float('-inf')
        start_pointer = -1
        next_pointer = -1
        tag_sequence = []
        for i, tag in enumerate(self.tags):
            if v_matrix[i][len(sentence) - 1] > bestpathprob:
                bestpathprob = v_matrix[i][len(sentence) - 1]
                start_pointer = i
                next_pointer = bp_matrix[i][len(sentence) - 1]

        tag_sequence.append(index_tag_map[start_pointer])
        # bestpathpointer gives the tag of the last word in the sentence, follow backpointers to get tag seq
        for i in range(len(sentence) - 2, -1, -1):
            tag_sequence.append(index_tag_map[next_pointer])
            next_pointer = bp_matrix[next_pointer][i]

        return tag_sequence[::-1]

    def compute_accuracy(self, filename):
        error_count = 0
        observation_count = 0
        data = self.tokenize_file(filename)
        data = self.replace_word_classes(data)
        data = self.trim_low_freq(data)

        for seq in data:
            sentence = list(zip(*seq))[0]
            actual_tags = list(zip(*seq))[1]
            predicted_tags = self.generate_tag_sequence(sentence)
            for actual, predicted in zip(actual_tags, predicted_tags):
                if actual != predicted:
                    if actual != predicted:
                        error_count += 1
                observation_count += 1

        return (observation_count - error_count) / observation_count