import pygame
from math import *
from OpenGL.GL import *

colors = [
  (0, 20, 10),
  (4, 91, 82),
  (219, 242, 38),
  (0, 0, 255),
  (255, 255, 255)
]
SKY = (50, 100, 200)
GROUND = (163, 152, 154)
TRANSPARENT = (152, 0, 136,255)
TRANSPARENT2 = (152, 0, 135,255)
TRANSPARENT3 = (151, 0, 136,255)

walls = {
    "1": pygame.image.load('./Proyecto/p4n.png'),
    "2": pygame.image.load('./Proyecto/p4n.png'),
    "3": pygame.image.load('./Proyecto/p3n.png'),
    "4": pygame.image.load('./Proyecto/p2N.png'),
    "5": pygame.image.load('./Proyecto/p1N.png'),
}
sprite1 = pygame.image.load('./Proyecto/espadasN.png')
sprite2 = pygame.image.load('./Proyecto/espada2N.png')

enemies = [
    {
        "x": 125,
        "y": 125,
        "sprite": sprite2,
        "Distance": False,
        "Taked": False,

    },
    {
         "x": 300,
         "y": 300,
         "sprite": sprite1,
         "Distance": False,
         "Taked": False,
     },
     {
         "x": 400,
         "y": 420,
         "sprite": sprite1,
         "Distance": False,
         "Taked": False,
     },
     {
         "x": 350,
         "y": 80,
         "sprite": sprite2,
         "Distance": False,
         "Taked": False,
     },

]

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

class Raycaster(object):
    def __init__ (self, screen):
        self.screen = screen
        x, y, self.width, self.height = screen.get_rect()
        self.blocksize = 50
        self.map = []
        self.player = {
            "x": int(self.blocksize + self.blocksize / 2),
            "y": int(self.blocksize + self.blocksize / 2),
            "fov": int(pi/3),
            "a": int(pi/3),
        }
        self.llaves = 0
        self.gameOver = False
        self.clear_z()

    def clear_z(self):
        self.zbuffer = [99999 for z in range (0,int(self.width/2))]

    def point(self, x, y, c = WHITE):
        self.screen.set_at((x, y), c)

    def block(self, x, y, wall):
        for i in range(x, x + self.blocksize):
            for j in range(y, y + self.blocksize):
                tx = int((i - x) * 128 / self.blocksize)
                ty = int((j - y) * 128 / self.blocksize)
                c = wall.get_at((tx, ty))
                self.point(i, j, c)

    def load_map(self, filename):
        with open(filename) as f:
            for line in f.readlines():
                self.map.append(list(line))

    def draw_map(self):
        for x in range(0, 500, self.blocksize):
            for y in range(0, 500, self.blocksize):
                i = int(x/self.blocksize)
                j = int(y/self.blocksize)
                if self.map[j][i] != ' ':
                    self.block(x, y, walls[self.map[j][i]])

    def draw_player(self):
        self.point(self.player["x"], self.player["y"])

    def render(self):
        self.draw_map()
        self.draw_player()
        density = 60
        for i in range(0, density):
            a = self.player["a"] - self.player["fov"] / 2 + self.player["fov"]*i/density
            d, c, tx = self.cast_ray(a)
        for i in range(0, 500):
            self.point(499, i)
            self.point(500, i)
            self.point(501, i)
        for i in range(0, int(self.width/2)):
            a = self.player["a"] - self.player["fov"] / 2 + self.player["fov"]*i/(self.width/2)
            d, c, tx = self.cast_ray(a)
            x = int(self.width/2) + i
            var = (d * cos(a - self.player["a"]))
            if var == 0:
                self.gameOver = True
                self.player['x'] = int(self.blocksize + self.blocksize / 2)
                self.player['y'] = int(self.blocksize + self.blocksize / 2)
            else:
                h = (self.height/(d * cos(a - self.player["a"]))) * self.height/10
                if self.zbuffer[i]  >= d:
                    self.draw_stake(x, h, c, tx)
                    self.zbuffer[i] = d

        for enemy in enemies:
            if enemy["Taked"] == False:
                    self.point(int(enemy["x"]), int(enemy["y"]),(255,0,0))
            else:
                pass

        for enemy in enemies:
                if enemy["Taked"] == False:
                    self.draw_sprite(enemy)
                else:
                    pass

    def draw_sprite(self,sprite):
        sprite_a = atan2(
            sprite["y"] - self.player["y"],
            sprite["x"] - self.player["x"],
        )

        #Distancia de la espada al jugador
        d = ((self.player["x"] - sprite["x"])**2 + (self.player["y"] - sprite["y"])**2)**0.5

        #Distancia de la espada al jugador
        if d < 65:
            self.change_sword(sprite)

        sprit_size = int((500/d) * (500/10))

        sprite_x = int(
            500 +
            (sprite_a - self.player["a"]) * 500/self.player["fov"] + sprit_size/2)

        sprite_y = int(500/2 - sprit_size/2)

        for x in range(sprite_x, sprite_x + sprit_size):
            for y in range(sprite_y, sprite_y + sprit_size):
                tx = int((x - sprite_x) * 128/sprit_size)
                ty = int((y - sprite_y) * 128/sprit_size)
                c = sprite["sprite"].get_at((tx,ty))

                if c != TRANSPARENT and c != TRANSPARENT2:
                    if (x > int(self.width/2) and x < self.width):
                        if self.zbuffer[x - 500] >= d:
                            self.point(x,y,c)
                            self.zbuffer[x - 500] = d

    def cast_ray(self, a):
        d = 0
        ox = self.player["x"]
        oy = self.player["y"]

        while True:
            x = int(ox + d*cos(a))
            y = int(oy + d*sin(a))

            i = int(x/self.blocksize)
            j = int(y/self.blocksize)

            if self.map[j][i] != ' ':
                hitx = x - i * self.blocksize
                hity = y - j * self.blocksize

                if 1 < hitx < self.blocksize-1:
                    maxhit = hitx
                else:
                    maxhit = hity

                tx = int(maxhit * 128 / self.blocksize)

                return d, self.map[j][i], tx

            self.point(x, y)

            d += 1

    def change_sword(self, sprite):
        sprite["Distance"] = True

    def draw_stake(self, x, h, c, tx):
        start_y = int(self.height/2 - h/2)
        end_y = int(self.height/2 + h/2)
        height = end_y - start_y

        for y in range(start_y, end_y):
            ty = int((y - start_y) * 128 / height)
            color = walls[c].get_at((tx, ty))
            self.point(x, y, color)

    def draw_image(self, imagen):
        for x in range(0,r.width):
            for y in range(0,r.height):
                r.point(x,y,imagen.get_at((x,y)))

    def get_sword(self):
        for enemy in enemies:
            if enemy["Taked"] == False and enemy['Distance'] == True:
                enemy["Taked"] = True
                self.llaves += 1
    def get_num_espadas(self):
        return self.llaves
    def update_fps(self, clock, font):
        fps = str(int(clock.get_fps()))
        fps_text = font.render(fps, 1, pygame.Color("coral"))
        return fps_text

pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('./Proyecto/got.mp3')
pygame.mixer.music.set_volume(0.2)
sword_sound = pygame.mixer.Sound('./Proyecto/SwordH.mp3')
steps = pygame.mixer.Sound('./Proyecto/Steps2.mp3')

screen = pygame.display.set_mode((1000, 500))
r = Raycaster(screen)

pygame.mixer.music.play()

imgload_page = pygame.image.load('./Proyecto/Cg.png')
img_selectlevel = pygame.image.load('./Proyecto/lvl.png')
img_victoria = pygame.image.load('./Proyecto/Finalg.png')
img_derrota = pygame.image.load('./Proyecto/derrota2.png')
img_controles = pygame.image.load('./Proyecto/controles.png')

clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 25)

select_level = False
controls_page = False
load_page = True

while load_page:
    r.draw_image(imgload_page)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                load_page = False
                select_level = True
            if event.key == pygame.K_r:
                load_page = False
                controls_page = True
while controls_page:
    r.draw_image(img_controles)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                controls_page = False
                select_level = True

while select_level:
    r.draw_image(img_selectlevel)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                load_page = False
                select_level = False
                r.load_map('./Proyecto/map.txt')
            if event.key == pygame.K_h:
                load_page = False
                select_level = False
                r.load_map('./Proyecto/map2.txt')

victoria = False
running = True
Fallo = False
while running:
    r.clear_z()
    screen.fill(BLACK, (0, 0, r.width/2, r.height))
    screen.fill(SKY, (r.width/2, 0, r.width, r.height/2))
    screen.fill(GROUND, (r.width/2, r.height/2, r.width, r.height/2))

    r.render()
    r.screen.blit(r.update_fps(clock,font),(510,0))
    clock.tick(60)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                pygame.mixer.Sound.play(steps)
                r.player["x"] += 10
                if r.gameOver == True:
                    running = False
                    Fallo = True

            if event.key == pygame.K_LEFT:
                pygame.mixer.Sound.play(steps)
                r.player["x"] -= 10
                if r.gameOver == True:
                    running = False
                    Fallo = True

            if event.key == pygame.K_UP:
                pygame.mixer.Sound.play(steps)
                r.player["y"] -= 10
                if r.gameOver == True:
                    running = False
                    Fallo = True

            if event.key == pygame.K_DOWN:
                pygame.mixer.Sound.play(steps)
                r.player["y"] += 10
                if r.gameOver == True:
                    running = False
                    Fallo = True

            if event.key ==pygame.K_p:
                pygame.mixer.music.pause()
            if event.key == pygame.K_r:
                pygame.mixer.music.unpause()

            if event.key == pygame.K_a:
                r.player["a"] += pi/10
            if event.key == pygame.K_d:
                r.player["a"] -= pi/10
            if event.key == pygame.K_SPACE:
                pygame.mixer.Sound.play(sword_sound)
                r.get_sword()
                llaves = r.get_num_espadas()
                if llaves == 4:
                    running = False
                    victoria = True

while victoria:
    r.draw_image(img_victoria)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                load_page = False
                select_level = True
while Fallo:
    r.draw_image(img_derrota)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                load_page = False
                select_level = True


# Plugin for handling OCBC Bank [SG] files

from bank_handler import BankHandler

class OCBC_Bank_SG(BankHandler):
    """Plugin for handling Oversea-Chinese Banking Corporation Singapore
    (OCBC SG) bank files"""

    def __init__(self, config_dict: dict):
        """
        :param config_dict: a dictionary of conf parameters
        """
        super().__init__(config_dict)
        self.name = "OCBC_Bank_SG"

    def _preprocess_file(self, file_path, plugin_args) -> str:
        """
        For every row that doesn't have a valid date field
        strip out separators and append to preceding row.
        Overwrite input file with modified output.
        :param file_path: path to file
        """
        # what do we actually want to do?
        header_rows = int(self.config_dict["header_rows"])
        footer_rows = int(self.config_dict["footer_rows"])

        # get total number of rows in transaction file using a generator
        with open(file_path) as row_counter:
            row_count = sum(1 for _ in row_counter)

        with open(file_path) as input_file:
            output_rows = []
            for rownum, row in enumerate(input_file):
                # strip any single quotes, e.g. if payee is MCDONALD'S
                row = row.replace("'", "")
                # append headers and footers without modification
                if rownum < header_rows or rownum > (row_count - footer_rows):
                    output_rows.append(row)
                    continue
                if row[0] == ",":
                    # join with the previous row but excluding the newline char
                    # of the previous row
                    output_rows[-1] = (
                        output_rows[-1][:-1] + "," + row.strip(" ,")
                    )
                else:
                    output_rows.append(row)

        # overwrite source file
        with open(file_path, "w") as output_file:
            for row in output_rows:
                output_file.write(row)
        return file_path

def build_bank(config):
    """This factory function is called from the main program,
    and expected to return a B2YBank subclass.
    Without this, the module will fail to load properly.

    :param config: dict containing all available configuration parameters
    :return: a B2YBank subclass instance
    """
    return OCBC_Bank_SG(config)


import cv2
from utils import _createTrackbar, min_RGB, max_RGB

class BinarisationAlgorithm():
    def __init__(self) -> None:
        self.cap = cv2.VideoCapture ("video\\Redlight.mp4")
        _createTrackbar()
        self.Binarissation_window()
        pass

    def Binarissation_window(self):
        while (True):
            _,frame=self.cap.read ()
            mask = cv2.inRange(frame, (min_RGB()), (max_RGB()))
            cv2.imshow('mask',mask)
            result = cv2.bitwise_and(frame, frame, mask = mask)
            cv2.imshow('result', result)
            if cv2.waitKey(1) == 27 :
                break
        self.cap.release ()
        cv2.destroyAllWindows

if __name__ == '__main__':
    BinarisationAlgorithm()


from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton

# FUNCTIONS INLINE BUTTONS - 'ORARIO'
def markup_orario_cc():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
            InlineKeyboardButton("Triennale", callback_data="o_cc_tr"),
            InlineKeyboardButton("Magistrale", callback_data="o_cc_mg"))
    return markup

def markup_orario_cc_data():
    return ["o_cc_tr", "o_cc_mg"]

########################################################################################################################
########################################################################################################################
def markup_orario_tr_dip():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("DEI", callback_data="o_dip_tr_dei"),
        InlineKeyboardButton("DMMM", callback_data="o_dip_tr_dmmm"),
        InlineKeyboardButton("DICATECh", callback_data="o_dip_tr_dicatech"),
        InlineKeyboardButton("DICAR", callback_data="o_dip_tr_dicar"),
        InlineKeyboardButton("Corsi Comuni", callback_data="o_corsicomuni"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_tr_dip_back"))
    return markup

def markup_orario_cc_tr_data():
    return ["o_dip_tr_dei", "o_dip_tr_dmmm", "o_dip_tr_dicatech", "o_dip_tr_dicar", "o_corsicomuni", "o_tr_dip_back"]

########################################################################################################################
def markup_orario_mg_dip():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("DEI", callback_data="o_dip_mg_dei"),
        InlineKeyboardButton("DMMM", callback_data="o_dip_mg_dmmm"),
        InlineKeyboardButton("DICATECh", callback_data="o_dip_mg_dicatech"),
        #InlineKeyboardButton("DICAR", callback_data="o_dip_mg_dicar"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_mg_dip_back"))
    return markup

def markup_orario_cc_mg_data():
    return ["o_dip_mg_dei", "o_dip_mg_dmmm", "o_dip_mg_dicatech", "o_dip_mg_dicar", "o_mg_dip_back"]

########################################################################################################################
########################################################################################################################
def markup_orario_tr_dei():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Elettronica e Telecomunicazioni", callback_data="o_dei_tr_tlc"),
        InlineKeyboardButton("Elettrica", callback_data="o_dei_tr_eta"),
        InlineKeyboardButton("Informatica e dell'Automazione", callback_data="o_dei_tr_inf"),
        InlineKeyboardButton("Sistemi Medicali", callback_data="o_dei_tr_sm"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_tr_dei_back"))
    return markup

def markup_orario_tr_dei_data():
    return ["o_dei_tr_tlc", "o_dei_tr_eta", "o_dei_tr_inf", "o_dei_tr_sm", "o_tr_dei_back"]

########################################################################################################################
def markup_orario_tr_dmmm():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Gestionale", callback_data="o_dmmm_tr_ges"),
        InlineKeyboardButton("Meccanica", callback_data="o_dmmm_tr_mec"),
        InlineKeyboardButton("Sistemi Aerospaziali", callback_data="o_dmmm_tr_aero"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_tr_dmmm_back"))
    return markup

def markup_orario_tr_dmmm_data():
    return ["o_dmmm_tr_ges", "o_dmmm_tr_mec", "o_dmmm_tr_aero", "o_tr_dmmm_back"]

########################################################################################################################
def markup_orario_tr_dicatech():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Costruzione e Gestione Ambientale", callback_data="o_dicatech_tr_cost"),
        InlineKeyboardButton("Edile", callback_data="o_dicatech_tr_edi"),
        InlineKeyboardButton("Civile e Ambientale", callback_data="o_dicatech_tr_cic"),
        InlineKeyboardButton("TA Civile e Ambientale", callback_data="o_dicatech_tr_cic_ta"),
        #InlineKeyboardButton("Ing. dell'Ambiente", callback_data="o_dicatech_tr_amb"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_tr_dicatech_back"))
    return markup

def markup_orario_tr_dicatech_data():
    return ["o_dicatech_tr_cost", "o_dicatech_tr_edi", "o_dicatech_tr_cic", "o_dicatech_tr_amb", "o_dicatech_tr_cic_ta", "o_tr_dicatech_back"]

########################################################################################################################
def markup_orario_tr_dicar():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Architettura", callback_data="o_dicar_tr_arch"),
        InlineKeyboardButton("Disegno Industriale", callback_data="o_dicar_tr_disindu"),
        InlineKeyboardButton("Indstrial Design", callback_data="o_dicar_tr_inddesign"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_tr_dicar_back"))
    return markup

def markup_orario_tr_dicar_data():
    return ["o_dicar_tr_arch", "o_dicar_tr_disindu", "o_dicar_tr_inddesign", "o_tr_dicar_back"]

########################################################################################################################
########################################################################################################################
def markup_orario_mg_dei():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Elettronica", callback_data="o_dei_mg_eto"),
        InlineKeyboardButton("Elettrica", callback_data="o_dei_mg_eta"),
        InlineKeyboardButton("Ing. dell'Automazione", callback_data="o_dei_mg_auto"),
        InlineKeyboardButton("Telecomunicazioni (EN)", callback_data="o_dei_mg_tlc"),
        InlineKeyboardButton("Informatica (EN)", callback_data="o_dei_mg_inf"),
        InlineKeyboardButton("Sistemi Medicali", callback_data="o_dei_mg_sm"),
        #InlineKeyboardButton("Trasformazione Digitale", callback_data="o_dei_mg_trdig"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_mg_dei_back"))
    return markup

def markup_orario_mg_dei_data():
    return ["o_dei_mg_eto", "o_dei_mg_eta", "o_dei_mg_auto", "o_dei_mg_tlc", "o_dei_mg_inf", "o_dei_mg_sm", "o_dei_mg_trdig", "o_mg_dei_back"]

########################################################################################################################
def markup_orario_mg_dmmm():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Energetica", callback_data="o_dmmm_mg_ene"),
        InlineKeyboardButton("Meccanica", callback_data="o_dmmm_mg_mec"),
        InlineKeyboardButton("TA Meccanica", callback_data="o_dmmm_mg_mec_ta"),
        InlineKeyboardButton("Mechanical Engineering", callback_data="o_dmmm_mg_mecen"),
        InlineKeyboardButton("Gestionale", callback_data="o_dmmm_mg_ges"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_mg_dmmm_back"))
    return markup

def markup_orario_mg_dmmm_data():
    return ["o_dmmm_mg_ene", "o_dmmm_mg_mec", "o_dmmm_mg_mec_ta", "o_dmmm_mg_mecen", "o_dmmm_mg_ges", "o_mg_dmmm_back"]

########################################################################################################################
def markup_orario_mg_dicatech():
    markup = InlineKeyboardMarkup()
    markup.row_width = 2
    markup.add(
        InlineKeyboardButton("Civile", callback_data="o_dicatech_mg_civ"),
        InlineKeyboardButton("Sistemi Edilizi", callback_data="o_dicatech_mg_sised"),
        InlineKeyboardButton("Ambiente e Territorio", callback_data="o_dicatech_mg_amb"),
        InlineKeyboardButton("TA Ambiente e Territorio", callback_data="o_dicatech_mg_amb_ta"),
        InlineKeyboardButton("Gestione Infrastrutture Civili", callback_data="o_dicatech_mg_infrciv"),
        InlineKeyboardButton("ðŸ”™ back", callback_data="o_mg_dicatech_back"))
    return markup

def markup_orario_mg_dicatech_data():
    return ["o_dicatech_mg_civ", "o_dicatech_mg_sised", "o_dicatech_mg_amb", "o_dicatech_mg_amb_ta", "o_dicatech_mg_infrciv", "o_mg_dicatech_back"]

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


from init import *

# Цикл игры
running = True
while running:
    # держим цикл на правильной скорости
    clock.tick(FPS)

    # Ввод процесса (события)
    for event in pygame.event.get():
        # проверить закрытие окна
        if event.type == pygame.QUIT:
            running = False

    # Обновление
    all_sprites.update()
    screen.fill(BLACK)

    # Визуализация (сборка)
    pygame.display.flip()

pygame.quit()


def nearest(items, pivot):
    """Find nearest value in array, including datetimes

    Args
    ----
    items: iterable
        List of values from which to find nearest value to `pivot`
    pivot: int or float
        Value to find nearest of in `items`

    Returns
    -------
    nearest: int or float
        Value in items nearest to `pivot`
    """
    return min(items, key=lambda x: abs(x - pivot))

def contiguous_regions(condition):
    """Finds contiguous True regions of the boolean array 'condition'.

    Args
    ----
    condition: numpy.ndarray, dtype bool
        boolean mask array, but can pass the condition itself (e.g. x > 5)

    Returns
    -------
    start_ind: numpy.ndarray, dtype int
        array with the start indices for each contiguous region
    stop_ind: numpy.ndarray, dtype int
        array with the stop indices for each contiguous region

    Notes
    -----
    This function is adpated from Joe Kington's answer on StackOverflow:
    http://stackoverflow.com/a/4495197/943773
    """
    import numpy

    if condition.ndim > 1:
        raise IndexError("contiguous_regions(): condition must be 1-D")

    # Find the indicies of changes in 'condition'
    idx = numpy.diff(condition).nonzero()[0]

    if condition[0]:
        # If the start of condition is True prepend a 0
        idx = numpy.r_[0, idx]

    if condition[-1]:
        # If the end of condition is True, append the length of the array
        idx = numpy.r_[idx, condition.size]  # Edit

    # Reshape the result into two columns
    idx.shape = (-1, 2)

    # We need to start things after the change in 'condition'. Therefore,
    # we'll shift the index by 1 to the right.
    start_ind = idx[:, 0] + 1
    # keep the stop ending just before the change in condition
    stop_ind = idx[:, 1]

    # remove reversed or same start/stop index
    good_vals = (stop_ind - start_ind) > 0
    start_ind = start_ind[good_vals]
    stop_ind = stop_ind[good_vals]

    return start_ind, stop_ind

def rm_regions(a, b, a_start_ind, a_stop_ind):
    """Remove contiguous regions in `a` before region `b`

    Boolean arrays `a` and `b` should have alternating occuances of regions of
    `True` values. This routine removes additional contiguous regions in `a`
    that occur before a complimentary region in `b` has occured

    Args
    ----
    a: ndarray
        Boolean array with regions of contiguous `True` values
    b: ndarray
        Boolean array with regions of contiguous `True` values
    a_start_ind: ndarray
        indices of start of `a` regions
    a_stop_ind: ndarray
        indices of stop of `a` regions

    Returns
    -------
    a: ndarray
        Boolean array with regions for which began before a complimentary
        region in `b` have occured
    """

    import numpy

    for i in range(len(a_stop_ind)):
        next_a_start = numpy.argmax(a[a_stop_ind[i] :])
        next_b_start = numpy.argmax(b[a_stop_ind[i] :])
        if next_b_start > next_a_start:
            a[a_start_ind[i] : a_stop_ind[i]] = False

        return a

def recursive_input(input_label, type_class):
    """Recursive user input prompter with type checker

    Args
    ----
    type_class: type
        name of python type (e.g. float, no parentheses)

    Returns
    -------
    output: str
        value entered by user converted to type `type_class`

    Note
    ----
    Use `ctrl-c` to exit input cycling
    """
    import sys

    type_str = str(type_class).split("'")[1]

    msg = "Enter {} (type `{}`): ".format(input_label, type_str)

    # Catch `Ctrl-c` keyboard interupts
    try:
        output = input(msg)
        print("")
        # Type class input, else cycle input function again
        try:
            output = type_class(output)
            return output
        except Exception:
            print("Input must be of type `{}`\n".format(type_str))
            return recursive_input(input_label, type_class)

    # Keyboard interrupt passed, exit recursive input
    except KeyboardInterrupt:
        return sys.exit()

def get_dir_indices(msg, dirs):
    """Return path(s) indices of directory list from user input

    Args
    ----
    msg: str
        String with message to display before pass selection input
    dir_list: array-like
        list of paths to be displayed and selected from

    Return
    ------
    input_dir_indices: array-like
        list of index positions of user selected path from input
    """

    # Get user input for paths to process
    usage = (
        "\nEnter numbers preceeding paths seperated by commas (e.g. "
        "`0,2,3`).\nTo select all paths type `all`.\nSingle directories "
        "can also be entered (e.g.  `0`)\n\n"
    )

    # Generate paths text to display
    dirs_str = ["{:2} {:60}\n".format(i, p) for i, p in enumerate(dirs)]
    dirs_str = "".join(dirs_str)

    # Concatenate `msg`, usage txt, and paths list for display before input
    input_dirs = recursive_input("".join([msg, usage, dirs_str, "\n"]), str)

    # Determine type of input
    if "," in input_dirs:
        input_dir_indices = [int(x.strip()) for x in input_dirs.split(",")]
    elif "all" in input_dirs:
        input_dir_indices = range(len(dirs))
    else:
        try:
            input_dir_indices = [int(input_dirs.strip())]
        except Exception:
            raise ValueError(
                "Could not determine input type for input: " "{}".format(input_dirs)
            )

    return input_dir_indices


"""open_programs URL Configuration

The `main_urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to main_urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to main_urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to main_urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
import permission
from ajax_select import urls as ajax_select_urls
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic.base import RedirectView
from persons.views import register
from rest_framework import routers
from rest_framework_jwt.views import refresh_jwt_token
from rest_framework_jwt.views import verify_jwt_token
from rest_framework_swagger.views import get_swagger_view

from .apps.api.views import *
from .apps.api_v11 import auth_serializers
from .apps.api_v11.views import *
from persons.views import change_person, get_user, change_password

from programs.views import ProgramBackup, RestoreBackup

permission.autodiscover()

router_10 = routers.DefaultRouter()
router_10.register(r'courses', CourseList)
router_10.register(r'courses_ids', CoursesIdList, 'Course')
router_10.register(r'sessions', SessionList)
router_10.register(r'persons', PersonList)
router_10.register(r'users', UserList)
router_10.register(r'competences', CompetenceList)
router_10.register(r'results', ResultList)
router_10.register(r'programs', ProgramList)
router_10.register(r'disciplines', DisciplineList)
router_10.register(r'modules', ModuleList)
router_10.register(r'types', TypeList)

router_11 = routers.DefaultRouter()
router_11.register(r'choice_group_types', ChoiceGroupTypeList)
router_11.register(r'choice_groups', ChoiceGroupList)
router_11.register(r'target_modules', TargetModulesList)
router_11.register(r'program_modules', ProgramModulesList)
router_11.register(r'program_competences', ProgramCompetenceList)
router_11.register(r'training_targets', TrainingTargetList)
router_11.register(r'users', UserList)
router_11.register(r'courses', CourseList)
router_11.register(r'persons', PersonList)
router_11.register(r'competences', CompetenceList)
router_11.register(r'results', ResultList)
router_11.register(r'disciplines', DisciplineList)
router_11.register(r'types', TypeList)
router_11.register(r'modules', ModuleList)
router_11.register(r'programs', ProgramList)
router_11.register(r'components', ComponentList)
router_11.register(r'componenttypes', ComponentTypeList)
router_11.register(r'diagrams', DiagramList)
router_11.register(r'technologies', TechnologyList)
router_11.register(r'training_terms', TrainingTermsList)
router_11.register(r'semesters', SemesterList)
router_11.register(r'variants', VariantList)

schema_view = get_swagger_view(title='Open programs')

main_urlpatterns = [
    url(r'^$', RedirectView.as_view(url='/constructor/', permanent=False), name='index'),

    url(r'^admin/', include('smuggler.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^ajax_select/', include(ajax_select_urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/v1/', include(router_10.urls, namespace='api')),
    url(r'^api/v11/', include(router_11.urls, namespace='api_v11')),
    url(r'^api/docs/', schema_view),
    url(r'^tinymce/', include('tinymce.urls')),
    url(r'^accounts/', include('allauth.urls')),

    url(r'^api/v11/api-token-auth/', auth_serializers.obtain_jwt_token),
    url(r'^api/v11/api-token-refresh/', refresh_jwt_token),
    url(r'^api/v11/api-token-verify/', verify_jwt_token),
]

if 'rosetta' in settings.INSTALLED_APPS:
    main_urlpatterns += [url(r'^rosetta/', include('rosetta.urls')),
                    url(r'^i18n/', include('django.conf.urls.i18n')),
                    ]

if settings.DEBUG is True:
    main_urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    main_urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#### APPS ####

main_urlpatterns += [
    url(r'^constructor/', include('open_programs.apps.constructor.urls')),
    url(r'^constructor_v2/', include('open_programs.apps.constructor_v2.urls')),
    url(r'^stat/', include('open_programs.apps.stat.urls')),
]

#### API rewrite
main_urlpatterns += [
    url(r'^api/v11/heartbeat/$', heartbeat, name="heartbeat"),
    url(r'^api/v11/get_program_choice_groups/(?P<program_id>.*)/$', get_choice_groups_by_program,
        name="get_choice_groups_by_program"),
    url(r'^api/v11/get_program_modules/(?P<program_id>.*)/$', get_program_modules,
        name="get_program_modules"),
    url(r'^api/v11/get_program_targets/(?P<program_id>.*)/$', get_targets_by_program,
        name="get_targets_by_program"),
    url(r'^api/v11/get_program_competences/(?P<program_id>.*)/$', get_competences_by_program,
        name="get_competences_by_program"),
    url(r'^api/v11/change_target_module/$', change_target_module, name="change_target_module"),
    url(r'^api/v11/change_choice_group/$', change_choice_group, name="change_choice_group"),
    url(r'^api/v11/change_competence/$', change_competence, name="change_competence"),

    url(r'^api/v11/get_program_disciplines/(?P<program_id>.*)/$', get_program_disciplines,
        name="get_program_disciplines"),

    url(r'^api/v11/get_program_discipline/(?P<program_id>.*)/(?P<discipline_id>.*)/$', get_program_discipline,
        name="get_program_discipline"),
    url(r'^api/v11/remove_discipline/$', remove_discipline,
        name="remove_discipline"),

    url(r'^api/v11/change_discipline_semester/$', change_discipline_semester,
        name="change_discipline_semester"),
    url(r'^api/v11/get_variants/(?P<program_id>.*)/(?P<discipline_id>.*)/$', get_variants,
        name="get_variants"),
    url(r'^api/v11/change_variant/$', change_variant, name="change_variant"),
    url(r'^api/v11/delete_variant/$', delete_variant, name="delete_variant"),
    url(r'^api/v11/create_variant/$', create_variant, name="create_variant"),
    url(r'^api/v11/add_default_variants/$', add_default_variants, name="add_default_variants"),

    url(r'^api/v11/new_trajectory/$', new_trajectory, name="new_trajectory"),
    url(r'^api/v11/save_trajectory/$', save_trajectory, name="save_trajectory"),
    url(r'^api/v11/get_trajectory_id/(?P<id>.*)/$', get_trajectory_id, name="get_trajectory"),
    url(r'^api/v11/get_trajectory_link/(?P<link>.*)/$', get_trajectory_link, name="get_link"),
    url(r'^api/v11/get_program_trajectory/(?P<program_id>.*)/$', get_program_trajectory,
        name="get_program_trajectory"),
    url(r'^api/v11/delete_trajectory/$', delete_trajectory, name="delete_trajectory"),
    url(r'^api/v11/copy_trajectory/$', copy_trajectory, name="copy_trajectory"),

    url(r'^api/v11/get_program_variants/(?P<program_id>.*)/$', get_program_variants,
        name="get_program_variants"),
    url(r'^api/v11/get_program_variants_constructor/(?P<program_id>.*)/$', get_program_variants_constructor,
        name="get_program_variants_constructor"),
    url(r'^api/v11/register', register, name="register"),
    url(r'^api/v11/change_person', change_person, name="change_person"),
    url(r'^api/v11/change_password', change_password, name="change_password"),
    url(r'^api/v11/get_user', get_user, name="get_user"),
    url(r'^api/v11/get_trajectories', get_trajectories, name="get_trajectories"),

    #### CMS API ####
    url(r'^api/v11/containers/$', get_containers, name="get_containers"),
    url(r'^api/v11/containers_by_type/(?P<slug>.*)/$', containers_by_type, name="containers_by_type"),
    url(r'^api/v11/container_by_slug/(?P<slug>.*)/$', container_by_slug, name="container_by_slug"),

    #### BACKUP ####
    url(r'^api/v11/backup/(?P<id>.*)/$', ProgramBackup.as_view(), name="program_backup"),
    url(r'^api/v11/restore/(?P<id>.*)/$', RestoreBackup.as_view(), name="restore_backup")

]

urlpatterns = [
    url(r'^oop/', include(main_urlpatterns)),
]


"""
Django settings for myblog project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&wv$(!h&vyu+k5cx2%mqw^&am83ssa4c(o0l4gs%_g)k+&rpru'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blogengine',
    'djangobower',
    'django_extensions',
    'django.contrib.sites',
    'django.contrib.flatpages',
    'django.contrib.syndication'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'myblog.urls'

WSGI_APPLICATION = 'myblog.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

SITE_ID = 1

INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
    'django_jenkins.tasks.run_pylint',
    'django_jenkins.tasks.with_coverage',
)
PROJECT_APPS = ['blogengine']

# Heroku config
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config(default="sqlite:///db.sqlite3")

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
STATIC_ROOT = 'staticfiles'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)


name="Ritik"
type="boy"
# a=f"This is {name}"   # use fstring

# but in old versions of python we use format

# a="This is {}".format(name)
# a="{} is a good {}".format(name,type)
a="{0} is a good {1}".format(name,type)    # give index according to your choice, starts from 0.
b="{1} is a good {0}".format(name,type)    # give index according to your choice, starts from 0.

print(a)
print(b)


def solution(n, words):
    answer = [0, 0]
    overlap = set([words[0]])

    last = words[0][-1]
    for idx in range(1, len(words)):
        # 중복 된 단어 검출 or 끝말잇기 불일치
        if (words[idx] in overlap) or last != words[idx][0]:
            answer = [idx % n + 1, idx // n + 1]
            break
        last = words[idx][-1]
        overlap.add(words[idx])
    return answer

if __name__ == "__main__":
    print(solution(3, ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"]))
    print(solution(5, ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"]))
    print(solution(2, ["hello", "one", "even", "never", "now", "world", "draw"]))

Programmers/Summer Winter Coding(2019)/영어 끝말잇기.py


def chickdog(head, leg):
    chick = int(0.5*(4*head - leg))
    dog = int(head - chick)
    if ( chick >= 0
        and dog >= 0
        and (chick + dog == head)
        and (2*chick + 4*dog == leg) ):
        return [chick, dog]
    else:
        return None


import myutils
from datetime import datetime
import sys
import os
import pickle
from keras.models import load_model
from gensim.models import Word2Vec, KeyedVectors
from keras.preprocessing import sequence
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
import tensorflow as tf
import numpy

#default mode / type of vulnerability
mode = "sql"

#get the vulnerability from the command line argument
if (len(sys.argv) > 1):
  mode = sys.argv[1]

model = load_model('model/LSTM_model_'+mode+'.h5',custom_objects={'f1_loss': myutils.f1_loss, 'f1':myutils.f1})

with open('data/' + mode + '_dataset_finaltest_X', 'rb') as fp:
  FinaltestX = pickle.load(fp)
with open('data/' + mode + '_dataset_finaltest_Y', 'rb') as fp:
  FinaltestY = pickle.load(fp)

now = datetime.now() # current date and time
nowformat = now.strftime("%H:%M")

#Prepare the data for the LSTM model

X_finaltest =  numpy.array(FinaltestX)
y_finaltest =  numpy.array(FinaltestY)

#in the original collection of data, the 0 and 1 were used the other way round, so now they are switched so that "1" means vulnerable and "0" means clean.

for i in range(len(y_finaltest)):
  if y_finaltest[i] == 0:
    y_finaltest[i] = 1
  else:
    y_finaltest[i] = 0

now = datetime.now() # current date and time
nowformat = now.strftime("%H:%M")

print(str(len(X_finaltest)) + " samples in the final test set.")

csum = 0
for y in y_finaltest:
  csum = csum+y

print("percentage of vulnerable samples: "  + str(int((csum / len(X_finaltest)) * 10000)/100) + "%")
print("absolute amount of vulnerable samples in test set: " + str(csum))

#padding sequences on the same length
max_length = 200
X_finaltest = sequence.pad_sequences(X_finaltest, maxlen=max_length)

yhat_classes = model.predict_classes(X_finaltest, verbose=0)
accuracy = accuracy_score(y_finaltest, yhat_classes)
precision = precision_score(y_finaltest, yhat_classes)
recall = recall_score(y_finaltest, yhat_classes)
F1Score = f1_score(y_finaltest, yhat_classes)

print("Accuracy: " + str(accuracy))
print("Precision: " + str(precision))
print("Recall: " + str(recall))
print('F1 score: %f' % F1Score)
print("\n")


"""
5. Longest Palindromic Substring
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
"""

class Solution:
    def longestPalindrome_old(self, s):
        """
        :type s: str
        :rtype: str
        """

        if len(set(s)) == 1:
            return s
        elif len(s) == 2 and s[0] != s[1]:
            return s[0]

        max_list = []
        for i in range(1, len(s)-1):
            left_index = i-1
            right_index = i+1

            tmp_lift = i
            tmp_right = i
            sem = False

            while left_index >= 0 and right_index < len(s):
                left = s[left_index]
                right = s[right_index]

                if left == right:
                    tmp_lift = left_index
                    tmp_right = right_index
                    sem = True
                elif left == s[tmp_lift] and not sem:
                    tmp_lift = left_index
                elif right == s[tmp_right] and not sem:
                    tmp_right = right_index
                else:
                    break

                left_index = tmp_lift - 1
                right_index = tmp_right + 1

            tmp_p = s[tmp_lift:tmp_right + 1]
            max_list = tmp_p if len(max_list) < len(tmp_p) else max_list

        return ''.join(max_list)

    def longestPalindrome(self, s):
        if not s:
            return 0
        elif len(s) == 1:
            return 1

        tmp_length = 1
        max_length = 1
        for p in range(1, len(s)-1):
            i = p - 1
            j = p + 1
            while i >= 0 and s[i] == s[p]:
                i -= 1
                tmp_length += 1
            while j < len(s) and s[j] == s[p]:
                j += 1
                tmp_length += 1
            while i >= 0 and j < len(s) and s[i] == s[j]:
                tmp_length += 2
                i -= 1
                j += 1
            max_length = max(max_length, tmp_length)
            tmp_length = 1
        return max_length

t1 = "222020221"
t2 = "aaaa"
t3 = "caba"
t4 = "abba"
t5 = "asdsa"
t6 = "abbd"

s = Solution()
for i in [t1,t2,t3,t4,t5,t6]:
    str = s.longestPalindrome_old(i)
    lens = s.longestPalindrome(i)
    print(len(str), lens)


import torch
from torch import nn
import torch.nn.functional as nnfunc

class Distillation(object):

    """
    Distillation loss class
    supports :param: method-->
        1. mse      : match yolo layer outputs
    """

    def __init__(self,method="mse"):
        if method=="mse":
            self.loss_fn = self.mse
        # elif method=="cfmse":
        #    self.loss_fn = self.cfmse
        # elif method=="cfmse2":
        #     self.loss_fn = self.cfmse2
        else:
            raise NotImplementedError

    def mse(self, predS, predT):
        """
        mse between predT & predS
        only works when Stu & Tea are same architecture
        """
        assert len(predT) == len(predS)
        dLoss = []
        for branchS, branchT in zip(predS, predT):
            dLoss.append(torch.mean((branchS - branchT)**2))
        dLoss = sum(dLoss)
        dLoss_items = torch.tensor((0.0, 0.0, 0.0, dLoss.item())).to(dLoss.device)
        return dLoss, dLoss_items.detach()


import pygame
from pygame.locals import *
from pygame.math import Vector2
from controllers.Button import Button
from controllers.PlayerManager import PlayerManager
from controllers.TowerManager import TowerManager
from controllers.EventManager import EventManager
from models.Money import Money
from models.constants import *
from models.Map import Path
from controllers.PlayerManager import PlayerManager

class GameManager:
    def __init__(self, screen):
        pygame.init()
        GameManager.screen = screen
        GameManager.player = PlayerManager()
        GameManager.clock = pygame.time.Clock()
        GameManager.deltaTime = 0
        GameManager.running = True
        GameManager.player = PlayerManager()
        GameManager.towerManager = TowerManager(self.player)
        GameManager.eventManager = EventManager(self.player)

        self.background = pygame.image.load("res/sprites/map.png")
        self.background = pygame.transform.scale(self.background, (1280, 720))

        self.backButton = Button("res/sprites/button/back.png", Rect(20, 20, 50, 50))
        self.backButton.bind(self.stop)

        self.listeButton = []

        self.listeButton.append(Button("res/sprites/button/archer_button.png", Rect(970, 600, 80, 80)))
        self.BindButton(0,GameManager.towerManager.createArcher)
        self.listeButton.append(Button("res/sprites/button/wizard_button.png", Rect(1060, 600, 80, 80)))
        self.BindButton(1,GameManager.towerManager.createWizard)
        self.listeButton.append(Button("res/sprites/button/golem_button.png", Rect(1150, 600, 80, 80)))
        self.BindButton(2,GameManager.towerManager.createGolem)

    def run(self):
        GameManager.running = True
        while GameManager.running:
            self.handleEvents()
            self.update()
            self.render()

    def handleEvents(self):
        for event in pygame.event.get():
            if(event.type == QUIT):
                GameManager.running = False
                pygame.quit()
            elif(event.type == MOUSEBUTTONDOWN):
                GameManager.towerManager.createTurret()

    def update(self):
        GameManager.deltaTime = GameManager.clock.tick(200) / 1000
        self.backButton.update()
        self.eventManager.update(self.deltaTime)
        self.towerManager.update(self.deltaTime, self.eventManager.enemiesAlive)
        self.player.money.update()
        self.backButton.update()

        for button in self.listeButton :
            button.update()

    def render(self):
        GameManager.screen.fill([255, 255, 255])
        GameManager.screen.blit(self.background, (0,0))

        self.backButton.render()

        self.eventManager.render(self.screen)
        self.towerManager.render(self.screen)
        self.player.money.render(self.screen)

        for button in self.listeButton:
            button.render()

        pygame.display.update()

    def stop(self):
        GameManager.running = False

    def BindButton(self, index:int, function):
        self.listeButton[index].bind(function)


#This file stores a collection of basic function used in a number of the accompanying notebooks.
#Some constants used throughout are also set here.

import numpy, astropy.io.fits

#Constants:
#Distance to HCG 16
dist = 55.2 #Mpc
#Error in distance to HCG 16
err_dist = 3.3 #Mpc
#Speed of light
c = 299792.458 #km/s
#HI line rest frequency
f0 = 1420.405751/1000. #GHz
#Hubble constant
H0 = 70. #km/s/Mpc
h = H0/100.
#Redshift of HCG 16 member galaxies (from optical lines)
v_grp = 3957. #km/s
v_hcg16a = 4073. #km/s
v_hcg16b = 3864. #km/s
v_hcg16c = 3849. #km/s
v_hcg16d = 3874. #km/s
v_hcg16n = 4045. #km/s #NGC 848
v_hcg16p = 3972. #km/s #PGC 8210

#Redshifts and velocity ranges from optical rotation curves
#Mendes de Oliveira+1998
m98_v_hcg16a_cen = 4040.
m98_v_hcg16a_min = -163.
m98_v_hcg16a_max = 174.
m98_v_hcg16b_cen = 3905.
m98_v_hcg16b_min = -77.
m98_v_hcg16b_max = 183.
m98_v_hcg16c_cen = 3850.
m98_v_hcg16c_min = -220.
m98_v_hcg16c_max = 225.
m98_v_hcg16d_cen = 3845.
m98_v_hcg16d_min = -78.
m98_v_hcg16d_max = 76.
#Rubin+1991
r91_v_hcg16a_cen = 4052.
r91_vmax_hcg16a = 250.
r91_v_hcg16b_cen = 3837.
r91_v_hcg16c_cen = 3858.
r91_v_hcg16d_cen = 3864.
r91_vmax_hcg16d = 70.

#Positions of HCG 16 members
ra_hcg16a = 32.352519
ra_hcg16b = 32.336845
ra_hcg16c = 32.4105329
ra_hcg16d = 32.428870
ra_hcg16n = 32.573518 #NGC 848
ra_hcg16p = 32.275081 #PGC 8210

dec_hcg16a = -10.135923
dec_hcg16b = -10.133093
dec_hcg16c = -10.1466869
dec_hcg16d = -10.184086
dec_hcg16n = -10.321447 #NGC 848
dec_hcg16p = -10.320226 #PGC 8210

#Functions
def gaussian(x, mu, sig):
    '''
    Gaussian with mean mu and standard deviation sig.

    Inputs:
        x: Independent variable.
        mu: Mean of Gaussian distribution.
        sig: Standard deviation of Gaussian.

    Outputs:
        y: Value of Gaussian distribution at x.
    '''

    return numpy.exp(-numpy.power((x - mu)/sig, 2.)/2.)

def gaussian2d(x, y, mux, muy, sigx, sigy):
    '''
    Two dimensional Gaussian with mean (mux,muy) and standard deviations sigx and sigy in the x and y directions respectively.

    Inputs:
        x: x coordinate.
        y: y coordinate.
        mux: Mean of Gaussian distribution in the x-direction.
        muy: Mean of Gaussian distribution in the y-direction.
        sigx: Standard deviation of Gaussian in the x-direction.
        sigy: Standard deviation of Gaussian in the y-direction.

    Outputs:
        val: Value of Gaussian distribution at x,y.
    '''

    return numpy.exp(-numpy.power((x - mux)/sigx, 2.)/2.)*numpy.exp(-numpy.power((y - muy)/sigy, 2.)/2.)

def v_rad(v_opt):
    '''
    Conversion from optical to radio velocity.

    Inputs:
        v_opt: Optical velocity [km/s].

    Outputs:
        v_rad: Radio velocity [km/s].
    '''

    return c*(1. - (1./(1.+(v_opt/c))))

def v_opt(v_rad):
    '''
    Conversion from radio to optical velocity.

    Inputs:
        v_rad: Radio velocity [km/s].

    Outputs:
        v_opt: Optical velocity [km/s].
    '''

    return c*((1./(1.-(v_rad/c))) - 1.)

def logMHI_pred(B_c,D,B_c_err,D_err):
    '''
    Predicts HI mass of a galaxy given its B-band luminosity following Jones et al. 2018, A&A 609A, 17J.

    Inputs:
        B_c = Extinction and k-corrected B-band apparent magnitude.
        D = Source luminoisty distance [Mpc].
        B_c_err = Error in B_c.
        D_err = Error in D [Mpc].

    Outputs:
        logMHI = Logarithm of the predicted HI mass [Msol].
        logMHI_err = Error in logMHI.
    '''

    logD = numpy.log10(D)
    logD_err = D_err/(D*numpy.log(10.))

    logLB = 10. + 2.*numpy.log10(D) + 0.4*(4.88-B_c)

    logMHI = 0.94*logLB + 0.18

    logMHI_err = numpy.sqrt(0.2**2. + (0.94**2.)*((0.4*B_c_err)**2. + (2.*logD_err)**2.))

    return logMHI,logMHI_err

def read_fitscube(filename,need_beam=False,widths=False,mask=False,verbose=False):
    '''
    Reads a fits cube that is RA, Dec, Vel and builds the axes.

    Inputs:
        filename = String indicating the full location of the fits file.
        need_beam = Boolean indicating whether to return beam dimensions.
        widths = Boolean indicating whether to return axes step sizes.
        verbose = Boolean indicating whether to print all output.

    Outputs:
        cube = The data values from the fits file.
        cube_ra = Right ascension axis values [deg].
        cube_dec = Declination axis values [deg].
        cube_vel = Velocity axis values [km/s].
        bmaj = (if need_beam) Beam major axis diameter [arcsec].
        bmin = (if need_beam) Beam major axis diameter [arcsec].
        pa = (if need_beam) Beam position angle [deg].
        beam_factor = (if need_beam) Ratio of beam area to pixel area.
        cube_dx = (if widths) RA axis step size [deg].
        cube_dy = (if widths) Dec axis step size [deg].
        cube_dv = (if widths) Velocity axis step size [km/s].
    '''

    cube_fits = astropy.io.fits.open(filename)

    cube = cube_fits[0].data
    cube_head = cube_fits[0].header

    cube_dx = cube_head['CDELT1']
    cube_dy = cube_head['CDELT2']
    cube_dv = cube_head['CDELT3']

    cube_ra = cube_head['CRVAL1'] + cube_dx * numpy.arange(1,1+cube_head['NAXIS1']) - cube_dx * cube_head['CRPIX1'] # RA
    cube_dec = cube_head['CRVAL2'] + cube_dy * numpy.arange(1,1+cube_head['NAXIS2']) - cube_dy * cube_head['CRPIX2'] # Dec
    cube_vel = cube_head['CRVAL3'] + cube_dv * numpy.arange(1,1+cube_head['NAXIS3']) - cube_dv * cube_head['CRPIX3']

    if 'm/s' == str.strip(cube_head['CUNIT3']) or 'M/S' == str.strip(cube_head['CUNIT3']):
        if verbose:
            print("Velocity units are m/s. Converting to km/s.")
        cube_vel = cube_vel/1000. #km/s
        cube_dv = cube_dv/1000. #km/s
    elif 'km/s' == str.strip(cube_head['CUNIT3']) or 'KM/S' == str.strip(cube_head['CUNIT3']):
        if verbose:
            print("Velocity units are km/s.")
        pass
    else:
        print("Warning: Velocity units not recognised.")
        print("Warning: Units listed as: "+cube_head['CUNIT3'])

    if 'OPT' in str(cube_head['CTYPE3']) or 'opt' in str(cube_head['CTYPE3']):
        if verbose:
            print("Velocity convention is optical.")
        pass
    elif 'RAD' in str(cube_head['CTYPE3']) or 'rad' in str(cube_head['CTYPE3']) or int(cube_head['VELREF']) > 256:
        if verbose:
            print("Velocity convention is radio. Converting to optical.")
        cube_vel = v_opt(cube_vel)
    else:
        print("Warning: Could not identify radio or optical velocity convention.")
        print("Warning: Convention listed as: "+cube_head['CTYPE3'])

    bmaj,bmin,pa = cube_head['BMAJ']*3600.,cube_head['BMIN']*3600., cube_head['BPA']
    pixel = cube_head['CDELT2']*3600.

    beam_factor = (numpy.pi*bmaj*bmin/(pixel**2.))/(4.*numpy.log(2.))

    cube_fits.close()

    if mask:
        cube = numpy.where(cube > 0, 1, 0)

    if need_beam and widths:
        return cube,cube_ra,cube_dec,cube_vel,bmaj,bmin,pa,beam_factor,cube_dx,cube_dy,cube_dv
    elif need_beam:
        return cube,cube_ra,cube_dec,cube_vel,bmaj,bmin,pa,beam_factor
    elif widths:
        return cube,cube_ra,cube_dec,cube_vel,cube_dx,cube_dy,cube_dv
    else:
        return cube,cube_ra,cube_dec,cube_vel

def mask_mom1(gal,level=0.2):
    '''
    Mask a moment 1 map using a given flux level in the moment 0 map of the same source.

    Inputs:
        gal = String of the root file name of the source e.g. 'HCG16a'.
        level = Level to mask at [Jy km/s per beam].

    Outputs:
        tmp.fits = Writes a temporary version of the (masked) moment 1 map.
    '''

    file0 = gal+'_mom0th.fits'
    file1 = gal+'_mom1st.fits'

    fits0 = astropy.io.fits.open(file0)
    mom0 = fits0[0].data

    fits1 = astropy.io.fits.open(file1)
    mom1 = fits1[0].data

    fits1[0].data = v_opt(numpy.where(numpy.logical_or(mom0 > level,numpy.isnan(mom0)),mom1,float('nan')))

    fits1.writeto('tmp.fits',overwrite=True,output_verify='warn')


from django.shortcuts import render, redirect

from NotesApp.Notes.forms import BaseNote
from NotesApp.Notes.models import Note

def disable_fields(form):
    for field in form.fields.values():
        field.widget.attrs['disabled'] = 'disabled'

def add_note(request):
    if request.method == "GET":
        form = BaseNote()

    else:
        form = BaseNote(request.POST)

        if form.is_valid():
            form.save()

            return redirect('create_profile')

    context = {
        'form': form,
    }

    return render(request, 'note-create.html', context)

def edit_note(request, pk):
    note = Note.objects.filter(pk=pk).get()

    if request.method == "GET":
        form = BaseNote(instance=note)

    else:
        form = BaseNote(request.POST, instance=note)

        if form.is_valid():
            form.save()

            return redirect('create_profile')

    context = {
        'note': note,
        'form': form,
    }

    return render(request, 'note-edit.html', context)

def delete_note(request, pk):
    note = Note.objects.filter(pk=pk).get()
    form = BaseNote(instance=note)

    if request.method == "GET":
        disable_fields(form)

    else:
        note.delete()

        return redirect('create_profile')

    context = {
        'note': note,
        'form': form,
    }

    return render(request, 'note-delete.html', context)

def details_note(request, pk):
    note = Note.objects.filter(pk=pk).get()

    context = {
        'note': note,
    }

    return render(request, 'note-details.html', context)

Python Web Basics Exam - 27 June 2021/NotesApp/Notes/views.py


# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 10:44:39 2020
@author:DataScientist
if you have any question My Email is:
gheffari.abdelfattah@gmail.com

"""

from keras import backend as K

def recall_m(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

def precision_m(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

def f1_m(y_true, y_pred):
    precision = precision_m(y_true, y_pred)
    recall = recall_m(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))


from ideasdk.protocols import SocaPubSubProtocol, SubscriptionListener

from blinker import signal
from typing import Optional

class SocaPubSub(SocaPubSubProtocol):
    def __init__(self, topic: str, logger=None):
        self._signal = signal(topic)
        self._logger = logger

    def publish(self, sender: str, **kwargs):
        self._signal.send(sender, **kwargs)

    def subscribe(self, listener: SubscriptionListener, sender: Optional[str] = None):
        if self._logger:
            self._logger.debug(f'subscribe - topic: {self._signal.name}, listener: {listener}')

        if sender is None:
            self._signal.connect(listener)
        else:
            self._signal.connect(listener, sender=sender)

    def unsubscribe(self, listener: SubscriptionListener, sender: Optional[str] = None):
        if self._logger:
            self._logger.debug(f'unsubscribe - topic: {self._signal.name}, listener: {listener}')

        if sender is None:
            self._signal.disconnect(listener)
        else:
            self._signal.disconnect(listener, sender=sender)


"""
LCM of More Than Three Numbers
Create a function that takes an array of more than three numbers as an argument and returns the Least Common Multiple (LCM).

Examples
lcm_of_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ➞ 2520

lcm_of_list([13, 6, 17, 18, 19, 20, 37]) ➞ 27965340

lcm_of_list([44, 64, 12, 17, 65]) ➞ 2333760
Notes
The LCM is the smallest positive number that is a multiple of two or more numbers.
"""

def lcm_of_list(numbers):

    a=sorted(list(set(numbers)), reverse = True)
    if a==[1]: return [1]
    pf=[]  #Prime Factorization of an Integer
    for i in a:
        if i>1:
            numbers = i
            k=[]
            for i in range(2,numbers+1):
                while numbers>1:
                    if numbers%i == 0:
                        numbers = numbers /i
                        k.append(i)
                    else:
                        break
            pf.append(k)
    pf2=pf[0]
    for i in pf:
        for j in i:
            if pf2.count(j)< i.count(j): pf2.append(j)

    result=1
    for i in pf2: result = result*i

    return (result)
#lcm_of_list([1]) #, 1)
#lcm_of_list([5, 5, 5]) #, 5)
#lcm_of_list([67, 34, 12, 3, 2]) #, 13668)
#lcm_of_list([79, 18, 7, 3, 1]) #, 9954)
#lcm_of_list([10, 20, 30, 40, 50]) #, 600)
#lcm_of_list([2, 3, 5, 7, 11, 13, 17]) #, 510510)
#lcm_of_list([91, 92, 93, 94, 95]) #, 3476431140)
#lcm_of_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) #, 2520)
#lcm_of_list([13, 6, 17, 18, 19,20, 37]) #, 27965340)
#lcm_of_list([44, 64, 12, 17, 65]) #, 2333760)
lcm_of_list([200, 30, 18, 11, 8, 64, 34]) #, 2692800)


import tensorflow as tf
import os

class GetData:
    def __init__(self):
        self.N_KOSPI_TRAIN = 738498
        self.N_KOSPI_TEST = 280398
        self.N_KOSDAQ_TRAIN = 1232292
        self.N_KOSDAQ_TEST = 442590
    # tfrecord file을 data로 parsing해주는 function
    def _parse_function(self, tfrecord_serialized):
        features = {
            "class_label": tf.io.FixedLenFeature([], tf.float32),
            "high_label": tf.io.FixedLenFeature([], tf.float32),
            "close_label": tf.io.FixedLenFeature([], tf.float32),
            "arr": tf.io.FixedLenFeature([], tf.string),
            "info": tf.io.FixedLenFeature([], tf.string),
            "var": tf.io.FixedLenFeature([], tf.string),
        }
        parsed_features = tf.io.parse_single_example(tfrecord_serialized, features)

        arr = tf.io.decode_raw(parsed_features["arr"], tf.float32)
        info = tf.io.decode_raw(parsed_features["info"], tf.float32)
        var = tf.io.decode_raw(parsed_features["var"], tf.float32)

        arr = tf.cast(arr, tf.float32)  # n,2(min,day),24,5
        info = tf.cast(info, tf.float32)  # n,2(min,day),24,6
        var = tf.cast(var, tf.float32)  # n,11

        arr = tf.reshape(arr, (2, 24, 5))
        info = tf.reshape(info, (2, 24, 6))

        min_arr, day_arr = tf.split(arr, [1, 1], axis=0)
        min_info, day_info = tf.split(info, [1, 1], axis=0)

        enc_data = tf.reshape(
            tf.concat([day_info, day_arr], axis=-1), (24, 11)
        )  # 24,11
        dec_data = tf.reshape(tf.concat([min_info, min_arr], axis=-1), (24, 11))

        data = tf.concat([enc_data, dec_data, var[tf.newaxis, :]], axis=0)  # 49,11

        class_label = tf.cast(parsed_features["class_label"], tf.float32)
        high_label = tf.cast(parsed_features["high_label"], tf.float32)
        close_label = tf.cast(parsed_features["close_label"], tf.float32)

        return data, class_label, high_label, close_label

    def DataSet(self, train_batch=512, test_batch=5000):
        cur_dir = os.curdir
        tfr_dir = os.path.join(cur_dir, "tfrecord")

        kospi_tfr_train_dir = os.path.join(tfr_dir, "kospi/cls_train.tfr")
        kospi_tfr_test_dir = os.path.join(tfr_dir, "kospi/cls_test.tfr")

        ## kospi train dataset 만들기
        kospi_train_dataset = tf.data.TFRecordDataset(kospi_tfr_train_dir)
        kospi_train_dataset = kospi_train_dataset.map(
            self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
        )
        kospi_train_dataset = (
            kospi_train_dataset.shuffle(self.N_KOSPI_TRAIN,seed=2020)
            .prefetch(tf.data.experimental.AUTOTUNE)
            .batch(train_batch)
        )

        kospi_test_dataset = tf.data.TFRecordDataset(kospi_tfr_test_dir)
        kospi_test_dataset = (
            kospi_test_dataset.map(
                self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .shuffle(self.N_KOSPI_TEST,seed=2020)
            .batch(test_batch)
        )

        kosdaq_tfr_train_dir = os.path.join(tfr_dir, "kosdaq/cls_train.tfr")
        kosdaq_tfr_test_dir = os.path.join(tfr_dir, "kosdaq/cls_test.tfr")

        ## kosdaq train dataset 만들기
        kosdaq_train_dataset = tf.data.TFRecordDataset(kosdaq_tfr_train_dir)
        kosdaq_train_dataset = kosdaq_train_dataset.map(
            self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
        )
        kosdaq_train_dataset = (
            kosdaq_train_dataset.shuffle(self.N_KOSDAQ_TRAIN,seed=2020)
            .prefetch(tf.data.experimental.AUTOTUNE)
            .batch(train_batch)
        )

        kosdaq_test_dataset = tf.data.TFRecordDataset(kosdaq_tfr_test_dir)
        kosdaq_test_dataset = (
            kosdaq_test_dataset.map(
                self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
            )
            .shuffle(self.N_KOSDAQ_TEST,seed=2020)
            .batch(test_batch)
        )
        return (
            kospi_train_dataset,
            kospi_test_dataset,
            kosdaq_train_dataset,
            kosdaq_test_dataset,
        )
    def AllTestSet(self):
        cur_dir = os.curdir
        tfr_dir = os.path.join(cur_dir, "tfrecord")

        kospi_tfr_train_dir = os.path.join(tfr_dir, "kospi/cls_train.tfr")
        kospi_tfr_test_dir = os.path.join(tfr_dir, "kospi/cls_test.tfr")

        kospi_test_dataset = tf.data.TFRecordDataset(kospi_tfr_test_dir)
        kospi_test_dataset = kospi_test_dataset.map(
            self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
        ).batch(self.N_KOSPI_TEST)

        kosdaq_tfr_test_dir = os.path.join(tfr_dir, "kosdaq/cls_test.tfr")

        kosdaq_test_dataset = tf.data.TFRecordDataset(kosdaq_tfr_test_dir)
        kosdaq_test_dataset = kosdaq_test_dataset.map(
            self._parse_function, num_parallel_calls=tf.data.experimental.AUTOTUNE
        ).batch(self.N_KOSDAQ_TEST)
        return (
            kospi_test_dataset,
            kosdaq_test_dataset,
        )


# Take the scraped PPC data and try to import it into PopIt.
#
# It looks for someone with the same name by searching PopIt, and, if
# matches are found, asks the user whether they're the same person.
# This decision is recorded in a JSON file so you should only need to
# make that choice once.
#
# TODO: add a --noinput option, which won't ask for input, but instead
# output text and return an error; this will be useful for running
# this job from cron - if you get an email from cron, you'll need to
# run the script manually to make those decisions.

from __future__ import print_function, unicode_literals

from optparse import make_option
import os
from os.path import join, exists
import re
import json

from django.core.management.base import BaseCommand
from django.conf import settings

import requests

from candidates.views.version_data import get_change_metadata

from compat import input

from ..images import get_file_md5sum

party_slug_to_popit_party = {
    'labour': {
        'name': 'Labour Party',
        'id': 'party:53',
    },
    'conservatives': {
        'name': 'Conservative Party',
        'id': 'party:52',
    },
    'libdem': {
        'name': 'Liberal Democrats',
        'id': 'party:90',
    }
}

constituency_corrections = {
    'Berwick': 'Berwick-upon-Tweed',
    'Chester': 'City of Chester',
    'Cotswolds': 'The Cotswolds',
    'Dover and Deal': 'Dover',
    'Harborough, Oadby and Wigston': 'Harborough',
    'Hull North': 'Kingston upon Hull North',
    'Hull West and Hessle': 'Kingston upon Hull West and Hessle',
    'Isle of Wright': 'Isle of Wight',
    'Liverpool, Wavetree': 'Liverpool, Wavertree',
    'Liverpool Wavetree': 'Liverpool, Wavertree',
    'Mid-Norfolk': 'Mid Norfolk',
    'Richmond': 'Richmond (Yorks)',
    'Sittingbourne and Sheppy': 'Sittingbourne and Sheppey',
    'Stratford-upon-Avon': 'Stratford-on-Avon',
    'West Cornwall and Scilly': 'St Ives',
    'Weston Super Mare': 'Weston-Super-Mare',
    'Canterbury and Whitstable': 'Canterbury',
    'Brent Central - Liberal Democrat Race Equality Champion': 'Brent Central',
    'Coatbridge, Chryston, Bellshill': 'Coatbridge, Chryston and Bellshill',
    'East Kilbride': 'East Kilbride, Strathaven and Lesmahagow',
    'Newcastle under Lyme': 'Newcastle-under-Lyme',
    'North Northamptonshire': 'Northampton South',
}

def cons_key(s):
    return re.sub(r',', '', s).lower()

class UnknownConstituencyException(Exception):
    pass

def get_constituency_from_name(constituency_name, constituency_lookup):
    name = re.sub(r'\xA0', ' ', constituency_name)
    name = re.sub(r' & ', ' and ', name)
    name = re.sub(r'(?i)candidate for ', '', name)
    name = constituency_corrections.get(name, name)
    try:
        mapit_data = constituency_lookup[cons_key(name)]
    except KeyError:
        message = "Unknown constituency; {0} - consider adding a correction for {1}"
        raise UnknownConstituencyException(message.format(
            cons_key(name), name
        ))
    post_id = str(mapit_data['id'])
    return {
        'post_id': post_id,
        'name': mapit_data['name'],
        'mapit_url': 'http://mapit.mysociety.org/area/{0}'.format(post_id),
    }

ppc_data_directory = join(
    settings.BASE_DIR,
    'data',
    'UK-Political-Parties',
    'ppcs',
    'json'
)

human_decisions_filename = join(
    settings.BASE_DIR,
    'data',
    'human-ppc-decisions.json'
)

def get_human_decisions():
    with open(human_decisions_filename) as f:
        return json.load(f)

def write_human_decisions(human_decisions):
    output = json.dumps(human_decisions, indent=4, sort_keys=True)
    output = re.sub(r'(?ms)\s*$', '', output)
    with open(human_decisions_filename, 'w') as f:
        f.write(output)

def record_human_decision(ppc_dict, popit_person_id, same):
    human_decisions = get_human_decisions()
    human_decisions.append({
        'same_person': same,
        'ppc': ppc_dict,
        'popit_person_id': popit_person_id,
    })
    write_human_decisions(human_decisions)

def get_human_decision(ppc_data):
    fields_to_match = ['party_slug', 'constituency', 'name']
    matching_decisions = []
    for decision in get_human_decisions():
        if all(decision['ppc'][k] == ppc_data[k] for k in fields_to_match):
            matching_decisions.append(decision)
    return matching_decisions

def merge_person_data(old_data, new_data):
    data = old_data.copy()
    standing_in = data.get('standing_in', {})
    party_memberships = data.get('party_memberships', {})
    standing_in.update(new_data.get('standing_in', {}))
    party_memberships.update(new_data.get('party_memberships', {}))
    data.update(new_data)
    data['standing_in'] = standing_in
    data['party_memberships'] = party_memberships
    return data

def get_ppc_url_from_popit_result(popit_result):
    links = popit_result.get('links', [])
    for link in links:
        if link.get('note') == 'party PPC page':
            return link.get['url']
    return None

def key_value_appeared_in_previous_version(key, value, versions):
    for version in versions:
        value_from_old_version = version['data'].get(key)
        if value_from_old_version == value:
            return True
    else:
        return False

class Command(BaseCommand):
    help = "Import scraped PPC data"

    option_list = BaseCommand.option_list + (
        make_option('--check', action='store_true', dest='check', help='Check constituency names'),
    )

    # Currently unused:
    #
    #     "region",
    #     "full_url",
    #     "path",
    #     "phone",
    #     "slug",
    #     "address",
    #     "current_mp",
    #     "blog_url",
    #     "campaign_url",
    #     "biography_url",

    def get_person_data_from_ppc(self, ppc_data):
        return {
            'name': ppc_data.get('name', ''),
            'email': ppc_data.get('email', ''),
            'birth_date': None,
            'twitter_username': ppc_data.get('twitter_username', ''),
            'facebook_personal_url': ppc_data.get('facebook_url', ''),
            'homepage_url': ppc_data.get('homepage_url', ''),
            'party_ppc_page_url': ppc_data.get('full_url', ''),
            'standing_in': {
                '2015': ppc_data['constituency_object'],
            },
            'party_memberships': {
                '2015': ppc_data['party_object'],
            }
        }

    def upload_person_image(self, person_id, image_filename, original_url):
        # Find the md5sum of the image filename, to use as an ID:
        md5sum = get_file_md5sum(image_filename)
        image_upload_url = "{0}/{1}/persons/{2}/image".format(
            self.api.get_url(), self.api.get_api_version(), person_id
        )
        source = 'Via the official party PPC page, based on {0}'.format(original_url)
        with open(image_filename, 'rb') as f:
            requests.post(
                image_upload_url,
                headers={
                    'Apikey': self.api.api_key
                },
                files={
                    'image': f
                },
                data={
                    'notes': 'md5sum:' + md5sum,
                    'source': source,
                    'mime_type': 'image/png',
                }
            )

    def update_popit_person(self, popit_person_id, ppc_data, image_filename):
        from candidates.models import PopItPerson
        from ..images import image_uploaded_already
        # Get the existing data first:
        person_data, _ = self.get_person(popit_person_id)
        previous_versions = person_data.pop('versions')
        new_person_data = self.get_person_data_from_ppc(ppc_data)
        # Remove any empty keys, we don't want to overwrite exiting
        # data with nothing:
        keys = new_person_data.keys()
        warnings = []
        for key in keys:
            if not new_person_data[key]:
                del new_person_data[key]
            # Also make sure that we don't overwrite any existing
            # fields that are filled in with different values:
            if key not in ('standing_in', 'party_memberships'):
                new_person_data_value = new_person_data.get(key)
                person_data_value = person_data.get(key)
                if person_data_value and new_person_data_value and new_person_data_value != person_data_value:
                    if key_value_appeared_in_previous_version(
                        key,
                        new_person_data_value,
                        previous_versions
                    ):
                        warning_message = "[{0}] it looks as if a previous "
                        warning_message += "version had {1}, so not "
                        warning_message += "overwriting the current value {2}"
                        warnings.append(warning_message.format(
                            key,
                            new_person_data_value,
                            person_data_value
                        ))
                        del new_person_data[key]
                    else:
                        warnings.append("[{0}] replacing      {1}".format(key, person_data_value))
                        warnings.append("[{0}] with new value {1}".format(key, new_person_data_value))
        if warnings:
            print("Warnings for person/{0} {1}".format(
                popit_person_id, person_data['name']
            ).encode('utf-8'))
            for warning in warnings:
                print("  ...", warning.encode('utf-8'))
        merged_person_data = merge_person_data(person_data, new_person_data)
        change_metadata = get_change_metadata(
            None,
            'Updated candidate from official PPC data ({0})'.format(ppc_data['party_slug']),
        )
        person = PopItPerson.create_from_reduced_json(merged_person_data)
        person.record_version(change_metadata)
        person_id = person.save_to_popit(self.api)
        if image_filename:
            if image_uploaded_already(self.api.persons, person_id, image_filename):
                print("That image has already been uploaded!")
            else:
                print("Uploading image...")
                self.upload_person_image(person_id, image_filename, ppc_data['image_url'])
        person.invalidate_cache_entries()
        return person_id

    def add_popit_person(self, ppc_data, image_filename):
        from candidates.models import PopItPerson
        change_metadata = get_change_metadata(
            None,
            'Created new candidate from official PPC data ({0})'.format(ppc_data['party_slug']),
        )
        person_data = self.get_person_data_from_ppc(ppc_data)
        person = PopItPerson.create_from_reduced_json(person_data)
        person.record_version(change_metadata)
        person_id = person.save_to_popit(self.api)
        if image_filename:
            self.upload_person_image(person_id, image_filename, ppc_data['image_url'])
        person.invalidate_cache_entries()
        return person_id

    def already_added_for_2015(self, ppc_data, popit_result):
        '''True if ppc_data matches popit_result, and is already marked as standing

        This method returns True if popit_result seems to be the same
        person referred to as ppc_data and that person's already
        marked as standing in 2015 (in the right constituency). It
        returns None if popit_result is malformed or they've been
        since marked as "known not to be standing in 2015". Otherwise,
        this returns False.'''
        standing_in = popit_result.get('standing_in')
        # Due to this PopIt bug https://github.com/mysociety/popit/issues/710
        # we sometimes end up with this malformed standing_in:
        if standing_in is None:
            return None
        standing_in_2015 = standing_in.get('2015', {})
        # If standing_in_2015 is None, then they were added but
        # someone has since marked them as not standing; return None
        # and deal with that case specially:
        if standing_in_2015 is None:
            return None
        # Now just check if their name, party and constituency in 2015
        # match:
        popit_constituency_name_2015 = standing_in_2015.get('name')
        popit_party_id_2015 = popit_result['party_memberships'].get('2015', {}).get('id')
        return (ppc_data['name'] == popit_result['name'] and
                ppc_data['party_object']['id'] == popit_party_id_2015 and
                ppc_data['constituency_object']['name'] == popit_constituency_name_2015)

    def already_matched_to_a_person(self, ppc_data, popit_person_id):
        decisions = get_human_decision(ppc_data)
        for decision in decisions:
            if popit_person_id == decision['popit_person_id']:
                return decision['same_person']
        return None

    def decision_from_user(self, ppc_data, popit_result):
        # Ask whether the PPC is the same as this person from the
        # PopIt search results:
        print("--------------------------------------------------------")
        print("Is this PPC ...")
        print("        Name:", ppc_data['name'].encode('utf-8'))
        if 'email' in ppc_data:
            print("        Email:", ppc_data['email'])
        print("        Party:", ppc_data['party_slug'])
        print("        Constituency:", ppc_data['constituency'])
        if 'full_url' in ppc_data:
            print("        PPC URL:", ppc_data['full_url'])
        print("... the same as this person from PopIt:")
        print("        PopIt URL:", popit_result['html_url'])
        print("        Name:", popit_result['name'].encode('utf-8'))
        if 'email' in popit_result:
            print("        Email:", popit_result['email'])
        for year in popit_result['party_memberships']:
            print("        Party in {0}: {1}".format(
                year, popit_result['party_memberships'][year]['name']
            ))
        for year in popit_result['standing_in']:
            print("        Constituency in {0}: {1}".format(
                year, popit_result['standing_in'][year]['name']
            ))
        response = ''
        while response.lower() not in ('y', 'n'):
            response = input('Are they the same? (y/Y/n/N) ')
            response = response.lower().strip()
            if response == 'y':
                return True
            elif response == 'n':
                return False

    def handle_person(self, ppc_data, image_filename):
        from candidates.popit import get_search_url
        print("PPC ({party_slug}): {name}".format(**ppc_data).encode('utf-8'))
        # Search PopIt for anyone with the same name. (FIXME: we
        # should make this a bit fuzzier when the PopIt API
        # supports that.)
        person_search_url = get_search_url(
            'persons', '"' + ppc_data['name'] + '"'
        )
        r = requests.get(
            person_search_url
        )
        add_new_person = True
        for result in r.json()['result']:
            # FIXME: With the current code, updating Elasticsearch
            # fails because it rejects the empty string as a null date
            # value. To just get this working, GET the person directly
            # so the information's defintely up to date.
            result = self.api.persons(result['id']).get()['result']
            # We don't need past versions of the person or their
            # memberships, and it's unnecessary verbose to record them
            # with decisions.
            del result['versions']
            del result['memberships']
            popit_person_id = result['id']

            message = "  Considering PopIt person search result {0}"
            print(message.format(popit_person_id))

            added_for_2015 = self.already_added_for_2015(ppc_data, result)
            if added_for_2015 is None:
                add_new_person = False
                print("    already_added_for_2015 returned None, so ignoring")
                print("    !!! CHECK THIS MANUALLY !!!")
                break
            elif added_for_2015:
                # Then just update that person with the possibly
                # updated scraped data:
                add_new_person = False
                print("    matched a 2015 candidate, so updating that")
                self.update_popit_person(popit_person_id, ppc_data, image_filename)
                break
            else:
                # Do we already have a decision about whether this PPC is
                # the same as another from 2010?
                decision = self.already_matched_to_a_person(ppc_data, popit_person_id)
                if decision is None:
                    print("    no previous decision found, so asking")
                    # We have to ask the user for a decision:
                    if self.decision_from_user(ppc_data, result):
                        print("      updating, and recording the decision that they're a match")
                        add_new_person = False
                        self.update_popit_person(popit_person_id, ppc_data, image_filename)
                        record_human_decision(ppc_data, popit_person_id, True)
                        break
                    else:
                        print("      recording the decision that they're not a match")
                        record_human_decision(ppc_data, popit_person_id, False)
                else:
                    # Otherwise we'd previously decided that they're
                    # the same person, so just update that person.
                    print("    there was a previous decision found")
                    if decision:
                        print("      the previous decision was that they're a match, so updating")
                        add_new_person = False
                        self.update_popit_person(popit_person_id, ppc_data, image_filename)
                        break
        if add_new_person:
            new_person_id = self.add_popit_person(ppc_data, image_filename)
            print("  Added them as a new person ({0})".format(new_person_id))

    def handle(self, **options):
        from candidates.election_specific import AREA_DATA

        constituency_lookup = {
            cons_key(k): v for k, v in
            AREA_DATA.areas_by_name[('WMC', '22')].items()
        }

        for party_slug in sorted(os.listdir(ppc_data_directory)):
            json_directory = join(
                ppc_data_directory,
                party_slug
            )
            for leafname in sorted(os.listdir(json_directory)):
                if not leafname.endswith('.json'):
                    continue
                filename = join(json_directory, leafname)
                image = re.sub(r'\.json$', '-cropped.png', filename)
                if not exists(image):
                    image = None
                print('===============================================================')
                print("filename:", filename)
                with open(filename) as f:
                    ppc_data = json.load(f)
                ppc_data['party_slug'] = party_slug
                ppc_data['party_object'] = party_slug_to_popit_party[party_slug]
                ppc_data['constituency_object'] = get_constituency_from_name(
                    ppc_data['constituency'],
                    constituency_lookup
                )
                if options['check']:
                    continue
                self.handle_person(ppc_data, image)


import os
import warnings
import pandas as pd
import pytorch_lightning as pl
from data import VehicleDataModule
from argparse import ArgumentParser
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.utils import shuffle
from utils import get_model, get_dataset_counts_info, preprocess_csv
from config import BATCH_SIZE, DATA_PATH, NUM_CLASSES

warnings.filterwarnings('ignore')

if __name__ == '__main__':
    parser = ArgumentParser()
    parser = pl.Trainer.add_argparse_args(parser)
    parser.add_argument('--model', type=str, required=True, help='Model name (resnet18|resnet34|resnet50|efficientnet')
    parser.add_argument('--epoch_num', type=int, required=True, help='Epoch num')
    parser.add_argument('--data_path', type=str, default=DATA_PATH, help='Path to data directory')
    parser.add_argument('--tune', type=bool, default=False, help='Tune model before training (find LR and batch size )')
    parser.add_argument('--log_dir', type=str, default='default', help='Log directory name')
    parser.add_argument('--batch_size', type=int, default=BATCH_SIZE, help='Batch size')
    parser.add_argument('--checkpoints', type=str, required=True, help='Directory name where to save checkpoints')
    args = parser.parse_args()

    X_train = pd.read_csv(os.path.join(DATA_PATH, 'train_labels.csv'))
    X_test = pd.read_csv(os.path.join(DATA_PATH, 'test_labels.csv'))

    X_train = preprocess_csv(X_train)
    X_test = preprocess_csv(X_test)

    X_train = shuffle(X_train)
    X_test = shuffle(X_test)

    X_train.to_csv('train.csv', index=False)
    X_test.to_csv('test.csv', index=False)
    get_dataset_counts_info(X_train, X_test)

    model = get_model(args.model, NUM_CLASSES)

    dm = VehicleDataModule(data_path='train.csv', batch_size=BATCH_SIZE)

    logger = TensorBoardLogger(save_dir=os.getcwd(), name='logs')
    checkpoint_callback = ModelCheckpoint(
        monitor='val_loss',
        dirpath=os.path.join(os.getcwd(), args.checkpoints),
        filename=f'{args.model}' + '-{epoch:02d}-{val_loss:.2f}',
        save_top_k=1,
        mode='min',
        verbose=True
    )

    early_stoping_callback = EarlyStopping('val_loss', patience=5)
    trainer = pl.Trainer(accelerator='gpu', gpus=1, devices=-1, max_epochs=args.epoch_num)
    trainer.logger = logger
    trainer.callbacks = [checkpoint_callback, early_stoping_callback]
    trainer.fit(model=model, datamodule=dm)

    print('Best model with loss {:.4f} located in {}'.format(checkpoint_callback.best_model_score,
                                                             checkpoint_callback.best_model_path))

    trainer.test(model=model, datamodule=dm)


#! /Users/xiaotongli/anaconda3/bin/python
# -*- coding: utf-8 -*-
# @Time    : 9/28/18 10:57 PM
# @Author  : Xiaotong Li
# @School  : University of California, Santa Cruz
# @FileName: autocomplete_System.py
# @Software: PyCharm

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        # Time complexity: O(min(a,b)*b)
        # Space complexity: O(1)
        if len(a) == 0: return b
        if len(b) == 0: return a
        # recursive from the last element
        if a[-1] == '1' and b[-1] == '1':
            return self.addBinary(self.addBinary(a[0:-1], b[0:-1]), '1') + '0'
        elif a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[-1], b[-1]) + '0'
        else:
            return self.addBinary(a[-1], b[-1]) + '1'


import math
import pygame
import pygame.locals
import sys
import numpy as np
import Box2D
from Box2D.b2 import *
from Box2D import *

from armpart import ArmPart

from Tool import Tool

class Arm:

    def __init__(self, basex, basey, length1, length2):
        self.bbox_scale = 1.0
        self.nsteps = 50
        self.link1 = ArmPart(length1, scale=1.0)
        self.link2 = ArmPart(length2, scale=1.0)

        self.basex = basex
        self.basey = basey

        self.l2_angle = 2.5

    def createBodies(self, world):
        self.link1.pos = [ (self.basex, self.basey) ]
        self.link2.pos = [ (self.basex+self.link1.length-20, self.basey-10) ]

        vertices1 = [(-self.link1.length/2.0, -self.link1.line_width/2.0), (self.link1.length/2.0, -self.link1.line_width/2.0), (self.link1.length/2.0, self.link1.line_width/2.0), (-self.link1.length/2.0, self.link1.line_width/2.0)]
        vertices2 = [(-self.link2.length/2.0, -self.link2.line_width/2.0), (self.link2.length/2.0, -self.link2.line_width/2.0), (self.link2.length/2.0, self.link2.line_width/2.0), (-self.link2.length/2.0, self.link2.line_width/2.0)]

        rotated_vertices2 = []
        for vertex in vertices2:
            new_vertex = (((vertex[0] - (vertices2[0][0])) * math.cos(self.l2_angle)) - ((vertex[1] - ((vertices2[3][1]-vertices2[0][1])/2)) * math.sin(self.l2_angle)) + (vertices2[0][0]), \
                          ((vertex[0] - (vertices2[0][0])) * math.sin(self.l2_angle)) + ((vertex[1] - ((vertices2[3][1]-vertices2[0][1])/2)) * math.cos(self.l2_angle)) + ((vertices2[3][1]-vertices2[0][1])/2) )

            rotated_vertices2.append( new_vertex )

        self.link1.createBody(world, vertices1, "link1", density=1.5)
        self.link2.createBody(world, rotated_vertices2, "link2", density=1.0)

        self.set_pivot_positions()

        self.pivot1 = world.CreateKinematicBody(position=self.pivot_position1)
        circle=b2CircleShape(pos=self.pivot1.position, radius=1.0)
        self.pivot1.CreateFixture(shape=circle, density=0.0, friction=0.0)
        self.pivot1.userData = "pivot1"

        self.joint1 = world.CreateRevoluteJoint(bodyA=self.pivot1, bodyB=self.link1.body, anchor=self.pivot1.position, enableMotor=True, maxMotorTorque=100000000, motorSpeed=0.0)
        self.joint2 = world.CreateRevoluteJoint(bodyA=self.link1.body, bodyB=self.link2.body, anchor=self.pivot_position2, enableMotor=True, maxMotorTorque=10000000, motorSpeed=0.0, enableLimit=True, lowerAngle=-5.5, upperAngle=0.2)

        self.tool = Tool(self.pivot_position3[0], self.pivot_position3[1], world, 100.0)
        self.joint3 = world.CreateRevoluteJoint(bodyA=self.link2.body, bodyB=self.tool.body1, anchor=self.pivot_position3, enableMotor=True, maxMotorTorque=10000000, motorSpeed=0.0, enableLimit=True, lowerAngle=-math.pi/4.0, upperAngle=(3.0/4.0)*math.pi)

    def set_pivot_positions(self):
        self.pivot_position1 = (self.basex-self.link1.length/2.0, self.basey)

        self.pivot_position2 = (self.pivot_position1[0]+(self.link1.length * math.cos(self.link1.body.angle)), \
                                                         self.pivot_position1[1]+(self.link1.length * math.sin(self.link1.body.angle)))

        self.pivot_position3 = (self.pivot_position2[0]+((self.link2.length-2) * math.cos(self.l2_angle))+15, \
                                                         self.pivot_position2[1]+((self.link2.length-2) * math.sin(self.l2_angle)))

    def move_arm_absolute(self, theta1, theta2):
        self.link1.rotation = theta1
        self.link2.rotation = theta2

        self.link1.pos = [(self.basex, self.basey), \
                        (self.basex + self.link1.length * math.cos(self.link1.rotation), self.basey + self.link1.length * math.sin(self.link1.rotation))
                        ]
        self.link2.pos = [self.link1.pos[1], \
                        (self.link1.pos[1][0] + self.link1.length * math.cos(self.link1.rotation) + self.link2.length * math.cos(self.link1.rotation + self.link2.rotation), self.link1.pos[1][1] + self.link1.length * math.sin(self.link1.rotation) + self.link2.length * math.sin(self.link1.rotation + self.link2.rotation)) \
                        ]

    def inverse_kinematics(self, desired_x, desired_y):
        #c2 needs to be in [-1,1], otherwise point is outside reachable workspace
        c2 = (desired_x**2 + desired_y**2 - self.link1.length**2 - self.link2.length**2) / (2*self.link1.length * self.link2.length)
        if c2 < -1 or c2 > 1:
            return None, None

        s2 = -math.sqrt(1 - c2**2)

        theta2 = math.atan2(s2, c2)
        theta1 = math.atan2(desired_y, desired_x) - math.atan2(self.link2.length * s2, self.link1.length + self.link2.length * c2)

        return theta1, theta2