from random import randint
import sqlite3

class BankingDatabase:
    db_file = '../card.s3db'
    sql_create_card_table = """CREATE TABLE IF NOT EXISTS card (
                        id INTEGER PRIMARY KEY AUTOINCREMENT
                        , number TEXT NOT NULL
                        , pin TEXT
                        , balance INTEGER DEFAULT 0
                                    );"""

    def __init__(self):
        self.db_conn = None
        self.cur = None
        self.db_init()
        self.db_create_tables()

    def db_init(self):
        try:
            self.db_conn = sqlite3.connect(self.db_file)
            self.cur = self.db_conn.cursor()
        except sqlite3.Error as e:
            print(e)

    def db_create_tables(self):
        """ This method includes all the tables that should be created in card.s3db
        """
        self.create_table(self.db_conn, self.sql_create_card_table)

    @staticmethod
    def create_table(db_conn, create_table_sql):
        try:
            c = db_conn.cursor()
            c.execute(create_table_sql)
            db_conn.commit()
        except sqlite3.Error as e:
            print(e)

    def db_insert_account_num(self, acc_num, pin):
        try:
            with self.db_conn:
                self.cur.execute("INSERT INTO card(number, pin) VALUES (:number, :pin)",
                                 {'number': acc_num, 'pin': pin})
        except sqlite3.IntegrityError as e:
            print(e)

    def db_get_card_pin(self, card_num):
        with self.db_conn:
            self.cur.execute("SELECT pin FROM card WHERE number=:number", {'number': card_num})
            return self.cur.fetchone()

    def db_get_card_balance(self, card_num):
        with self.db_conn:
            self.cur.execute("SELECT balance FROM card WHERE number=:number", {'number': card_num})
            return self.cur.fetchone()

    def db_add_income_to_balance(self, card, income):
        with self.db_conn:
            self.cur.execute("UPDATE card SET balance = balance + ? WHERE number = ?", (income, card))

    def db_remove_account(self, card_number):
        with self.db_conn:
            self.cur.execute("DELETE FROM card WHERE number = ?", (card_number,))

class CustomerInfo:
    # POJO
    def __init__(self):
        self.account_number = None
        self.card_number = None
        self.card_pin = None
        self.current_balance = 0

class BankingConsoleInterface:
    start_menu = f'1. Create an account \n2. Log into account \n0. Exit'
    login_menu = f'1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit'
    bank_iin = 400000  # Issuer Identification Number (IIN)

    def __init__(self):
        self.db = BankingDatabase()
        self.customer = CustomerInfo()
        self.show_start_menu()

    def show_start_menu(self):
        print(self.start_menu)
        try:
            global menu_option
            menu_option = int(input())
        except ValueError:
            print('\nPlease, choose one of the existing Menu options\n')
            self.show_start_menu()

        if menu_option == 1:
            self.db.db_insert_account_num(self.generate_account_number(), self.generate_card_pin())
            print(
                f'\nYour card has been created\nYour card number:\n{self.customer.card_number}\nYour card PIN:\n{self.customer.card_pin}\n')
            self.show_start_menu()
        elif menu_option == 2:
            self.log_in()
        elif menu_option == 0:
            self.db.cur.close()
            self.db.db_conn.close()
            print('\nBye!')
        else:
            print('\nPlease, choose one of the existing Menu options\n')
            self.show_start_menu()

    def generate_account_number(self):
        # TODO: move simple generators to class BankingUtils
        self.customer.account_number = self.concatenate_integers(self.bank_iin, randint(100000000, 200000000))
        self.customer.card_number = self.concatenate_integers(self.customer.account_number,
                                                              self.return_checksum(self.customer.account_number))
        return self.customer.card_number

    @staticmethod
    def concatenate_integers(num1, num2):
        num1 = str(num1)
        num2 = str(num2)
        num1 += num2
        return int(num1)

    @staticmethod
    def return_checksum(account_num):
        counter = 0
        for i, value in enumerate(list(str(account_num)), start=1):
            if i % 2 == 0:
                counter += int(value)
            elif int(value) * 2 > 9:
                counter += (int(value) * 2) - 9
            else:
                counter += (int(value) * 2)
        return 10 - (counter % 10) if (counter % 10) > 0 else 0

    def generate_card_pin(self):
        self.customer.card_pin = str(randint(0000, 9999)).zfill(4)
        return self.customer.card_pin

    def log_in(self):
        self.customer.card_number = input('Enter your card number:\n').strip()
        self.customer.card_pin = input('Enter your PIN:\n').strip()
        try:
            if self.db.db_get_card_pin(self.customer.card_number) is None:
                print('\nWrong card number or PIN!\n')
                self.show_start_menu()
            elif self.db.db_get_card_pin(self.customer.card_number)[0] == self.customer.card_pin:
                print('\nYou have successfully logged in!\n')
                self.show_account_menu()
            else:
                print('\nWrong card number or PIN!\n')
                self.show_start_menu()
        except KeyError:
            print('\nWrong card number or PIN!\n')

    def show_account_menu(self):
        print(self.login_menu)
        account_option = int(input())
        if account_option == 1:
            print(f'\nBalance: {self.db.db_get_card_balance(self.customer.card_number)[0]}\n')
            self.show_account_menu()
        elif account_option == 2:
            income = int(input('Enter income:\n').strip())
            self.db.db_add_income_to_balance(self.customer.card_number, income)
            print('\nIncome was added!\n')
            self.show_account_menu()
        elif account_option == 3:
            self.transfer_amount()
        elif account_option == 4:
            self.db.db_remove_account(self.customer.card_number)
            print('\nThe account has been closed!\n')
            self.show_start_menu()
        elif account_option == 5:
            print('\nYou have successfully logged out!\n')
            self.show_start_menu()
        elif account_option == 0:
            self.db.cur.close()
            self.db.db_conn.close()
            print('\nBye!')
        else:
            print('\nPlease, choose one of the existing Login options\n')
            self.show_account_menu()

    def transfer_amount(self):
        transfer_card = input('Transfer\nEnter card number:\n').strip()
        if self.customer.card_number == transfer_card:
            print("\nYou can't transfer money to the same account!\n")
            self.show_account_menu()
        elif transfer_card[-1] != str(self.return_checksum(transfer_card[:-1])):
            print('\nProbably you made a mistake in the card number. Please try again!\n')
            self.show_account_menu()
        elif self.db.db_get_card_balance(transfer_card) is None:
            print('\nSuch a card does not exist.\n')
            self.show_account_menu()
        else:
            transfer_amount = int(input('Enter how much money you want to transfer:\n').strip())
            if transfer_amount > self.db.db_get_card_balance(self.customer.card_number)[0]:
                print('Not enough money!\n')
                self.show_account_menu()
            else:
                # TODO: make transactional on a DB level (ex. open transaction, commit)
                self.db.db_add_income_to_balance(self.customer.card_number, -transfer_amount)
                self.db.db_add_income_to_balance(transfer_card, transfer_amount)
                print('Success!\n')
                self.show_account_menu()

if __name__ == '__main__':
    BankingConsoleInterface()
exit()


from torch import nn
import torch

class Encoder(nn.Module):
    def __init__(self, num_channel=3, num_feature=64, latent_dim=100, data_parallel=True):
        super(Encoder, self).__init__()
        features = nn.Sequential(
            # input is (num_channel) x 64 x 64
            nn.Conv2d(num_channel, num_feature, 4, 2, 1, bias=False),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. (num_feature) x 32 x 32
            nn.Conv2d(num_feature, num_feature * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(num_feature * 2),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. (num_feature*2) x 16 x 16
            nn.Conv2d(num_feature * 2, num_feature * 4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(num_feature * 4),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. (num_feature*4) x 8 x 8
            nn.Conv2d(num_feature * 4, num_feature * 8, 4, 2, 1, bias=False),
            nn.BatchNorm2d(num_feature * 8),
            nn.LeakyReLU(0.2, inplace=True),
        )
        z_mean_map = nn.Sequential(
            # state size. (num_feature*8) x 4 x 4
            nn.Conv2d(num_feature * 8, latent_dim, 4, 1, 0, bias=True),
        )
        z_log_sigma_map = nn.Sequential(
            # state size. (num_feature*8) x 4 x 4
            nn.Conv2d(num_feature * 8, latent_dim, 4, 1, 0, bias=True),
        )
        if data_parallel:
            self.features = nn.DataParallel(features)
            self.z_mean_map = nn.DataParallel(z_mean_map)
            self.z_log_sigma_map = nn.DataParallel(z_log_sigma_map)
        else:
            self.features = features
            self.z_mean_map = z_mean_map
            self.z_log_sigma_map = z_log_sigma_map
        for name, param in self.named_parameters():
            if 'conv' in name and 'weight' in name:
                nn.init.xavier_normal_(param.data)
            elif 'norm' in name and 'weight' in name:
                param.data.fill_(1)
            elif 'norm' in name and 'bias' in name:
                param.data.fill_(0)

    def forward(self, x):
        x = self.features(x)
        mu = self.z_mean_map(x)
        log_sigma = self.z_mean_map(x)
        sigma = torch.exp(log_sigma)
        std_z = torch.randn(mu.size())
        if mu.is_cuda:
            std_z = std_z.cuda()
        z_sample = mu + std_z * sigma
        return mu, log_sigma, sigma, z_sample


import cv2
import numpy as np
import math
import time

from statistics import stdev

# Constant
XCAM_WIDTH = 32
XCAM_HEIGHT = 32
VIDEO_WIDTH = XCAM_WIDTH * 6      # Defined from firmware
VIDEO_HEIGHT = XCAM_HEIGHT * 6

# Video device has to be in global scope
np.set_printoptions(threshold=np.nan)
np.set_printoptions(precision=1, suppress=True)
cap = cv2.VideoCapture(0)
cap.set(3,XCAM_WIDTH)                     # CV_CAP_PROP_FRAME_WIDTH
cap.set(4,XCAM_HEIGHT)                    # CV_CAP_PROP_FRAME_HEIGHT

def createColorTable():
  colorPalette0 =  np.array([[176,0,240],
                          [142,0,240],
                          [108,0,240],
                          [65,0,240],
                          [0,0,235],
                          [0,0,218],
                          [0,0,201],
                          [0,0,184],
                          [0,0,163],
                          [0,19,133],
                          [0,48,110],
                          [0,74,104],
                          [0,100,110],
                          [0,97,119],
                          [0,104,151],
                          [0,119,160],
                          [0,136,160],
                          [0,153,168],
                          [0,170,170],
                          [0,189,189],
                          [0,206,206],
                          [0,219,219],
                          [0,228,228],
                          [0,236,236],
                          [0,240,225],
                          [0,235,204],
                          [0,232,155],
                          [0,225,117],
                          [0,217,119],
                          [0,200,119],
                          [0,184,110],
                          [0,174,80],
                          [0,157,80],
                          [0,140,80],
                          [0,133,72],
                          [0,140,34],
                          [25,142,0],
                          [55,160,0],
                          [65,177,0],
                          [82,194,0],
                          [104,206,0],
                          [131,214,0],
                          [157,223,0],
                          [189,231,0],
                          [231,232,0],
                          [224,223,0],
                          [224,206,0],
                          [224,180,0],
                          [224,153,0],
                          [224,128,0],
                          [224,102,0],
                          [224,76,0],
                          [224,51,0],
                          [219,17,0],
                          [206,0,0],
                          [183,0,0],
                          [157,0,0],
                          [131,0,0],
                          [104,0,0],
                          [80,0,0],
                          [80,0,0]], np.int32)
  colorTable = np.zeros([1200,3], dtype=np.int32)

  # BGR2RGB
  colorPalette0[:,[0,2]] = colorPalette0[:,[2,0]]
  for i in range(len(colorPalette0) - 1):  # 60
    for j in range(20):
       colorTable[i*20 + j] = colorPalette0[i] + (colorPalette0[i+1]-colorPalette0[i])*j/20

  return colorTable

def find_nearest(array, value):
    idx = []
    array = np.asarray(array)

    for i in range(len(array)):
      idx.append(np.abs(math.sqrt((array[i][0] - value[0])**2 + (array[i][1] - value[1])**2 + (array[i][2] - value[2])**2)))#.argmin()
    idx_numpy = np.array(idx)
    targetIdx = idx_numpy.argmin()
    return targetIdx, array[targetIdx]

def getTrimmedFrame(original_frame, src_frame, width, height):
    for i in range(width):
      for j in range(height):
        index, value = find_nearest(color_table,original_frame[3+6*i][3+6*j])
        src_frame[i][j] = (index - 600)/10

########################## Routines ##########################
# 0 <= sd_threshould <= 1
def dead_pixel_test(sd_threshould):
  std_tempArray = [[[0] * XCAM_WIDTH for i in range(XCAM_HEIGHT)] for frame in range(2)]
  print("Dead Pixel Testing")
  print("Please cover the camera with constant room temperature object within 3 seconds")
  for count in range(2):
      # Take 2 frame
      _, frame = cap.read()
      title = str("frame" + str(count))
      cv2.imshow(title,frame)
      getTrimmedFrame(frame,std_tempArray[count],XCAM_WIDTH,XCAM_HEIGHT)

      if(count == 0):
        print("Now fully cover the camera with human hand within 3 seconds")
        time.sleep(3)
        print("Second capturing")
      else:
        print("Done")

  arr = np.asarray(std_tempArray)
  std_arr = np.std(arr, axis=0)
  index = np.where(std_arr < sd_threshould)
  #print(std_arr[[std < 0.5 for std in std_arr]])
  for k in range(len(index[0])):
    print("[" + str(index[1][k]) + "," + str(index[0][k]) + "]")

  cv2.waitKey(1)

def rgb2tmp(x,y):
    while(1):

        # Take each frame
        check, frame = cap.read()
        if not check:
          print("Open XCAM failure...")
          print("Check cap = cv2.VideoCapture(0) pointing to XCAM device")
          break
        index, value = find_nearest(color_table,frame[3+6*x][3+6*y])
        value_str = str(np.array2string(value, precision=1, separator=','))
        print("index = " + str(index) + ":" + value_str+ ", " + str((index - 600)/10))

        cv2.imshow('frame',frame)

        k = cv2.waitKey(5) & 0xFF
        if k == 27:
            break
################################################################################################################
# This is the testing application of using Meridian Innovation Limited 32x32 XCAM.
#
# Settings
# - XCAM_single (YUYV output thermal image)
# - Non-adaptive color mapping mode
# - *Using defalut colorPalette0
# - SetTempDisplay(0)
#
# Functions
# 1) Dead Pixel Testing
# 2) rgb2tmp Example
# 3) YUYV2tmp Example
#
# createColorTable() : create the color table following the same algorithm on MCU firmware, it is palette dependent*
# find_nearest(array, value): find the nearest point that matching to the target RGB value, since the cap.read()
#                             convert the YUYV stream to BGR internally, the convertion makes precision issue,
#                             which is why we cannot directly mapping by comparing R,G,B value only.
#                             Also openCV does not support getting YUYV raw streaming instead of BGR.
# "frame" is the raw data captured by cap.read() which is in BGR color space in size of 192x192, 6 times enlarged.
# You can get original 32x32 pixel value by trimming the array.
################################################################################################################
while 1:
  print("-------------------------MI XCAM test-------------------------")
  color_table = np.asarray(createColorTable())
  print("1) Dead Pixel Testing")
  print("2) rgb2tmp Example")
  print("3) YUYV2tmp Example")
  print("q) Quit")
  choice = input("Input: ")
  cv2.destroyAllWindows()
  if(choice == "1"):
      dead_pixel_test(0.05)
  elif(choice == "2"):
      print("Demo will also convert target pixel from rgb to temperature value")
      print("Input the target coordination in the format of x,y where 0<= x,y < 32")
      x,y = input("Coordinate = ").split(",")
      print("Press Esc to quit")
      time.sleep(3)
      rgb2tmp(int(x),int(y))
  elif(choice == "3"):
      print("Not implemented yet")
  elif(choice == "q"):
      break
  else:
      print("Wrong input!")

cv2.destroyAllWindows()
cap.release()


import numpy as np
from sympy import Matrix
import random
from modules.alphabet import getAlphabet

def getModularMatrix(matrix):

    '''
    ------------
    DESCRIPCIÓN:
    Función que se encarga de encontrar la matriz modular inversa.

    :param matrix:  (numpy matrix)
        Representa la llave que se utiliza para el cifrado. Debe ser
        una matriz cuadrada cuyo determinante sea distinto de 0 ya que debe
        ser posible invertirla.

    :return:        (numpy matrix)
        La función da como salida una matriz que representa la matriz modular
        inversa.
    '''

    ALPHABET = getAlphabet()
    inverse_matrix = Matrix(matrix)
    # matriz modular inversa
    inverse_matrix = inverse_matrix.inv_mod(len(ALPHABET))
    inverse_matrix = np.array(inverse_matrix)

    # cambio de tipo de datos.
    new_matrix = []
    for row in inverse_matrix:
        for i in row:
            new_matrix.append(int(i))

    new_matrix = np.array(new_matrix).reshape(np.shape(matrix)[0],np.shape(matrix)[1])

    return (new_matrix)

def getRandomKey(mod):
    '''
    ------------
    DESCRIPCIÓN:
    Función que de generar una key valida para hacer el cifrado.

    :param mod:  (int)
        Como es necesario que la matriz a generar tenga una inversa modular
        es necesario saber por que modulo se debe realizar.

    :return:        (numpy matrix)
        La función da como salida una matriz que representa la llave (key).
    '''
    sizekey = [2,3,4,5,6]

    size = sizekey[random.randint(0, len(sizekey)-1)]

    det = 0
    key = []
    while det == 0:
        key = []
        for _ in range(size*size):
            key.append(random.randint(0,29))
        key = np.array(key)

        key = np.reshape(key,(size,size))

        try:
            inverse_matrix = Matrix(key)
            inverse_matrix = inverse_matrix.inv_mod(mod)
            det = 1
        except:
            det = 0

    return(key)


#!/usr/bin/env python2
'''Containers/HBox 0
'''

import pygtk
pygtk.require('2.0')
import gtk
import os

IMAGEDIR = os.path.join(os.path.dirname(__file__), 'images')
ICON_IMAGE = os.path.join(IMAGEDIR, 'gtk-logo.svg')
text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et" \
       " dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum." \
       " Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
text2 = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et" \
       " dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum." \
       " Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."

class HBox0Demo(gtk.Window):
    def __init__(self, parent=None):
        gtk.Window.__init__(self)
        try:
            self.set_screen(parent.get_screen())
        except AttributeError:
            self.connect('destroy', lambda *w: gtk.main_quit())

        self.set_title(self.__class__.__name__)
        self.set_default_size(400, 200)
        self.set_icon_from_file(ICON_IMAGE)
        self.set_geometry_hints(min_width=100, min_height=100)

        textview = gtk.TextView()
        textbuffer = textview.get_buffer()
        textbuffer.set_text(text)
        textview.set_wrap_mode(gtk.WRAP_WORD)

        sw1 = gtk.ScrolledWindow()
        sw1.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw1.add(textview)

        textview2 = gtk.TextView()
        textbuffer2 = textview2.get_buffer()
        textbuffer2.set_text(text2)
        textview2.set_wrap_mode(gtk.WRAP_WORD)

        sw2 = gtk.ScrolledWindow()
        sw2.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw2.add(textview2)
        hbox = gtk.HBox()
        self.add(hbox)
        hbox.pack_start(sw1, True, True)
        hbox.pack_start(sw2, True, True)
        self.show_all()

if __name__ == '__main__':
    HBox0Demo()
    gtk.main()


import copy
from qtpy.QtCore import Qt, Signal
from qtpy.QtWidgets import QTreeWidget, QTreeWidgetItem

from ezcad.config.base import _
from ezcad.widgets.ezdialog import EasyDialog
from ezcad.widgets.projects.config import EXTMODULES_DEFAULTS_DICT
from ezcad.utils.logger import logger

class SelectModules(EasyDialog):
    NAME = _("Select modules")
    sigExtModules = Signal(dict)

    def __init__(self, parent=None, test=False):
        EasyDialog.__init__(self, parent)
        self.setup_page()
        if test:
            self.add_items()
            self.treeWidget.expandAll()

    def setup_page(self):
        self.treeWidget = QTreeWidget(self)
        self.treeWidget.setHeaderHidden(True)
        self.treeWidget.itemChanged.connect (self.check_changed)
        self.layout.addWidget(self.treeWidget)

        action = self.create_action()
        self.layout.addWidget(action)

    def check_changed(self, item, column):
        key = item.text(column)
        subitemName = item.text(column)
        try:
            itemName = item.parent().text(0)
            key = itemName + '/' + subitemName
            if item.checkState(column) == Qt.Checked:
                self.extmodules[key] = True
            elif item.checkState(column) == Qt.Unchecked:
                self.extmodules[key] = False
            else:
                pass
        except AttributeError:
            pass

    def add_items(self, defaults=None):
        """
        -i- defaults : dict, current selection of modules
        """
        if defaults is None:
            self.extmodules = copy.deepcopy(EXTMODULES_DEFAULTS_DICT)
        else:
            self.extmodules = defaults
        itemNameOld = None
        for option in sorted(self.extmodules.keys()):
            itemName, subitemName = option.split('/')
            checkState = self.extmodules[option]
            if itemName != itemNameOld:
                item = QTreeWidgetItem(self.treeWidget)
                item.setText(0, _(itemName))
                item.setFlags(item.flags() | Qt.ItemIsTristate |
                      Qt.ItemIsUserCheckable)
                itemNameOld = itemName
            subitem = QTreeWidgetItem(item)
            subitem.setText(0, subitemName)
            subitem.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            if checkState == 'True':
                subitem.setCheckState(0, Qt.Checked)
            else:
                subitem.setCheckState(0, Qt.Unchecked)

    def apply(self):
        logger.info("External modules: {}".format(str(self.extmodules)))
        self.sigExtModules.emit(self.extmodules)

def main():
    from qtpy.QtWidgets import QApplication
    app = QApplication([])
    test = SelectModules(test=True)
    test.show()
    app.exec_()

if __name__ == '__main__':
    main()


import sys
import requests
import json

from django.core.mail import EmailMultiAlternatives
from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import render_to_string
from django.conf import settings

def send_mail(subject, email_template_name,
              context, to_email, html_email_template_name=None, request=None, from_email=None):
    """
    Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
    """

    print(f'''
    subject: {subject}
    html email template name: {html_email_template_name}
    context: {context}
    to email: {to_email}
    request: {request}
    from email: {from_email}
    ''')
    ctx_dict = {}
    if request is not None:
        ctx_dict = RequestContext(request, ctx_dict)
    # update ctx_dict after RequestContext is created
    # because template context processors
    # can overwrite some of the values like user
    # if django.contrib.auth.context_processors.auth is used
    if context:
        ctx_dict.update(context)

    # Email subject *must not* contain newlines
    from_email = from_email or getattr(settings, 'DEFAULT_FROM_EMAIL')
    if email_template_name:
        message_txt = render_to_string(email_template_name,
                                       ctx_dict)

        email_message = EmailMultiAlternatives(subject, message_txt,
                                               from_email, to_email)
    else:
        try:
            message_html = render_to_string(
                html_email_template_name, ctx_dict)
            email_message = EmailMultiAlternatives(subject, message_html,
                                                   from_email, to_email)
            email_message.content_subtype = 'html'
        except TemplateDoesNotExist:
            pass

    try:
        email_message.send()
    except Exception as e:
        if settings.DEBUG:
            print(f'ERROR: email not sent (utils/utils.py). Reason: {e}')
            print(sys.exc_info())

def check_captcha(request):
    client_key = request.POST['g-recaptcha-response']
    secret_key = settings.RECAPTCHA_PRIVATE_KEY

    captcha_data = {
        'secret':secret_key,
        'response':client_key
    }

    r = requests.post('https://www.google.com/recaptcha/api/siteverify',data=captcha_data)
    response = json.loads(r.text)
    verify = response['success']
    return verify


""" WORKER MODULE

    - This module contains our inbuilt Workers and the base Worker.

    All Workers inherit the Worker base class.

    Users wanting to create their own custom Worker, should inherit from Worker.

    For detailed information on Workers, please see our Readme on our Github.
    https://github.com/RTMAAI/CO600-Musical-Analysis
"""
import threading
import os
import logging
from rtmaii.workqueue import WorkQueue
from scipy.signal import resample
from rtmaii.analysis import frequency, pitch, key, spectral, bpm
from pydispatch import dispatcher
from numpy import reshape, array
from tensorflow.contrib import predictor

LOGGER = logging.getLogger()
class Worker(threading.Thread):
    """ Base worker class, responsible for initializing shared attributes.

        Attributes:
            - queue: queue of data to be processed by a worker.
            - channel_id: id of channel being analysed.

        Args:
            - queue_length: length of queue structure. [Default = 1]
                Workers are greedy and will only consider the latest item.
    """
    def __init__(self, config: dict = None, channel_id: int = None, queue_length: int = 1):
        threading.Thread.__init__(self, args=(), kwargs=None)
        self.queue = WorkQueue(queue_length)
        self.config = config
        self.channel_id = channel_id
        self.setDaemon(True)
        self.reset_attributes()
        self.start()

    def run(self):
        raise NotImplementedError("Run should be implemented")

    def reset_attributes(self):
        """ Inherited method, used for resetting any attributes on configuration changes. """
        pass

class GenrePredictorWorker(Worker):
    """ Worker responsible for analysing Spectrogram intensities for a genre.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - exporter: Exports spectrograms to an external file for use future training set
            - predict_fn: Loads the 'predict' function of trained tensorflow model
            - genredict: The dictionary from converting the number labels of predicted genre
    """
    def __init__(self, exporter: object, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])
        self.exporter = exporter

        self.predict_fn = predictor.from_saved_model(os.path.join(os.path.dirname(__file__), 'model'))
        self.accuracyChecker = []
        self.genredict = {}
        self.genredict[0] = 'Rock'
        self.genredict[1] = 'Folk'
        self.genredict[2] = 'Hip-Hop'
        self.genredict[3] = 'Electric'
        self.prediction = 'N/A'

    def run(self):

        while True:
            spectrogram = self.queue.get()
            spectrodata = spectrogram[2]
            testphoto = array(spectrodata)
            testphoto = testphoto.astype('float32')

            try:
                testphoto = reshape(testphoto, (1,128,128,1))
                predictions = self.predict_fn({'x': testphoto})
                predictionclass = predictions['classes'][0]
                self.prediction = self.genredict[predictionclass]
                self.accuracyChecker.append(self.prediction)

                if(len(self.accuracyChecker) > 3):
                    self.accuracyChecker.pop(0)
                    print(self.accuracyChecker)
                    self.prediction = max(set(self.accuracyChecker), key=self.accuracyChecker.count)

                export_data = [spectrodata,self.prediction]
                self.exporter.queue.put(export_data)
            except:
                pass

            spectrogram = []

            dispatcher.send(signal='genre', sender=self.channel_id, data=self.prediction)

class BandsWorker(Worker):
    """ Worker responsible for analysing interesting frequency bands.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - bands_of_interest: dictionary of frequency bands to analyse.
            - sampling_rate: sampling_rate of source being analysed.
    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def reset_attributes(self):
        self.bands_of_interest = self.config.get_config('bands')
        self.sampling_rate = self.config.get_config('sampling_rate')

    def run(self):
        while True:
            spectrum = self.queue.get()
            frequency_bands = frequency.frequency_bands(spectrum,
                                                        self.bands_of_interest,
                                                        self.sampling_rate)
            dispatcher.send(signal='bands', sender=self.channel_id, data=frequency_bands)

class Key(object):
    """ Abstract class that has methods to analyse the key/note given a pitch. """
    @staticmethod
    def analyse_note(freq: float, channel_id: int):
        """ Extract the note of a given frequency..

            Args
                - freq: estimated frequency to analyse.
                - channel_id: channel the frequency was analysed from.
        """
        estimated_note = key.note_from_pitch(freq)
        dispatcher.send(signal='note', sender=channel_id, data=estimated_note)

    @staticmethod
    def analyse_key(freq: float, channel_id: int):
        """ Extract the key of a given frequency.

            Args
                - freq: estimated frequency to analyse.
                - channel_id: channel the frequency was analysed from.
        """
        pass

class ZeroCrossingWorker(Worker, Key):
    """ Worker responsible for analysing the fundamental pitch using the zero-crossings method.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - sampling_rate: sampling_rate of source being analysed.
    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def reset_attributes(self):
        self.sampling_rate = self.config.get_config('sampling_rate')

    def run(self):
        while True:
            signal = self.queue.get()
            estimated_pitch = pitch.pitch_from_zero_crossings(signal, self.sampling_rate)
            dispatcher.send(signal='pitch', sender=self.channel_id, data=estimated_pitch)
            self.analyse_note(estimated_pitch, self.channel_id)

class AutoCorrelationWorker(Worker, Key):
    """ Worker responsible for analysing the fundamental pitch using the auto-corellation method.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - sampling_rate: sampling_rate of source being analysed.
    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def reset_attributes(self):
        self.sampling_rate = self.config.get_config('sampling_rate')

    def run(self):
        while True:
            signal = self.queue.get()
            convolved_signal = spectral.convolve_signal(signal)
            estimated_pitch = pitch.pitch_from_auto_correlation(convolved_signal,
                                                                self.sampling_rate)
            dispatcher.send(signal='pitch', sender=self.channel_id, data=estimated_pitch)
            self.analyse_note(estimated_pitch, self.channel_id)

class HPSWorker(Worker, Key):
    """ Worker responsible for analysing pitch using the harmonic-product-spectrum method.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - sampling_rate: sampling_rate of source being analysed.
    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def reset_attributes(self):
        self.sampling_rate = self.config.get_config('sampling_rate')

    def run(self):
        while True:
            spectrum = self.queue.get()
            estimated_pitch = pitch.pitch_from_hps(spectrum, self.sampling_rate, 7)
            dispatcher.send(signal='pitch', sender=self.channel_id, data=estimated_pitch)
            self.analyse_note(estimated_pitch, self.channel_id)

class FFTWorker(Worker, Key):
    """ Worker responsible for analysing the fundamental pitch using the FFT method.

        Kwargs:
            - config (Config): Configuration options to use.
            - channel_id: id of channel being analysed.

        Attributes:
            - sampling_rate: sampling_rate of source being analysed.
    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def reset_attributes(self):
        self.sampling_rate = self.config.get_config('sampling_rate')

    def run(self):
        while True:
            spectrum = self.queue.get()
            estimated_pitch = pitch.pitch_from_fft(spectrum, self.sampling_rate)
            dispatcher.send(signal='pitch', sender=self.channel_id, data=estimated_pitch)
            self.analyse_note(estimated_pitch, self.channel_id)

#class BeatsWorker(Worker):
#    """ Worker responsible for determining beats happening.

#    """
#    def __init__(self, channel_id: int):
#        Worker.__init__(self, channel_id)
#
#    def run(self):
#        while True:
#            data = self.queue.get()
#            beat = bpm.beatdetection(data)
#            timedif = bpm.gettimedif()
#            dispatcher.send(signal='beat', sender=self.channel_id, data=beat)
#            self.analyse_bpm(timedif, self.channel_id)

class BPMWorker(Worker):
    """ Worker responsible for determining beats happening.

    """
    def __init__(self, **kwargs: dict):
        Worker.__init__(self, kwargs['config'], kwargs['channel_id'])

    def run(self):
        while True:
            data = self.queue.get()
            beats = data[0]
            if(len(data)>1):
                hbeats = data[1]
            beats = bpm.cleanbeatarray(beats)
            bpmestimate = bpm.bpmsimple(beats)

            dispatcher.send(signal='bpm', sender=self.channel_id, data=bpmestimate)
            #self.analyse_bpm(timedif, self.channel_id)

#class BPMWorker(Worker):
    #""" Analyse bpm based on beat times """
    #def __init__(self, channel_id: int):
    #    Worker.__init__(self, args=(), kwargs=None)

    #def analyse_bpm(self, timedif):
    #    estimated_bpm = bpm.bpmsimple()
        #dispatcher.send(signal='key', sender=self.channel_id, data=estimated_key)


# REになる...なぜ
import sys
read = sys.stdin.readline
from functools import reduce

class SqrtDecomposedList:
    def __init__(self, ls, segfunc, identity_element):
        from math import sqrt, ceil
        from copy import copy
        self.f = segfunc  # queryのfunction
        self.ide = identity_element
        self.n = len(ls)
        self.ls = copy(ls)
        self.b = ceil(sqrt(self.n))
        self.bucket = [self.ide] * (self.b + 1)
        self._build()

    def _build(self):
        for d in range(self.b):
            self.bucket[d] = reduce(
                self.f, self.ls[(d * self.b):((d + 1) * self.b)], self.ide)
        # for i, v in enumerate(self.ls):
        #     self.bucket[i // self.b] = \
        #         self.f(v, self.bucket[i // self.b])

    def __getitem__(self, idx):
        return self.ls[idx]

    def update(self, i, x):
        '''i番目の要素をxに更新する O(√n)'''
        self.ls[i] = x
        s = i // self.b * self.b
        t = s + self.b
        # print(i, self.b, i // self.b, s, t)
        self.bucket[i // self.b] = reduce(self.f,
                                          self.ls[s:t], self.ide)

    def query(self, l, r):
        '''半開区間[l,r)で指定すること O(√n)'''
        if r - l < 2 * self.b:
            return reduce(self.f, self.ls[l:r])
        l_bucket = (l - 1) // self.b + 1
        r_bucket = r // self.b  # 半開区間なのでこれでいい
        ret = reduce(self.f, self.bucket[l_bucket:r_bucket], self.ide)
        ret = self.f(
            reduce(self.f, self.ls[l:(l_bucket * self.b)], self.ide),
            ret)
        ret = self.f(
            reduce(self.f, self.ls[(r_bucket * self.b):r], self.ide),
            ret)
        return ret

Q = int(input())
sqls = SqrtDecomposedList([0] * 200001, segfunc=lambda x,
                          y: x + y, identity_element=0)

def is_ok(idx, segtree, x):
    # 条件を満たすかどうか？問題ごとに定義
    return segtree.query(0, idx + 1) >= x

def meguru_bisect(ng, ok, segtree, x):
    '''
    define is_okと
    初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す
    ng ok は  とり得る最小の値-1 とり得る最大の値+1
    最大最小が逆の場合はよしなにひっくり返す
    '''
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(mid, segtree, x):
            ok = mid
        else:
            ng = mid
    return ok

for _ in range(Q):
    t, x = map(int, read().split())
    if t == 1:
        sqls.update(x, 1)
    else:
        # 二分探索で初めてX以上になるidxを探す
        # →和がX以上になる(ok)状態の最小値
        idx = meguru_bisect(0, 200002, sqls, x)
        print(idx)
        # print(segtree[idx:idx + 5])
        # print(len(segtree[:]))
        sqls.update(idx, 0)


import torch
import torch.nn as nn
from torch.distributions.categorical import Categorical
import numpy as np

class GFN(nn.Module):
    def __init__(self, m, learn_Z=False, architecture=None, h=None):
        """
        :param architecture: nn.Module with input layer of size m and output layer of size m+1
        :param m: input size
        :param learn_Z: if True, then an extra parameter needs to be learned logZ
        :param h: if architecture is not specified then it's the number of hidden units for each of the 2 hidden layers
        """
        super().__init__()
        self.m = m
        if architecture is None:
            assert h is not None
            architecture = nn.Sequential(nn.Linear(m, h), nn.ReLU(), nn.Linear(h, h), nn.ReLU(), nn.Linear(h, m + 1))
        self.logit_maker = architecture
        if learn_Z:
            self.logZ = nn.Parameter(torch.tensor(0.))

    def forward(self, s):
        """
        :param s: (batched) states of the GFN. tensor of size k x m
        :return: P_F(. | s) represented as a tensor of size k x m+1.
        """
        assert s.ndim == 2 and s.shape[1] == self.m
        logits = self.logit_maker(s)
        return logits

class BinaryMaskGFN(GFN):
    """
    The states of the GFN are binary vectors of size m. An action amounts to replacing a zero with a one
    """

    def forward(self, theta):
        """
        :param theta: (batched) states of the GFN, binary tensor of size k x m
        :return: masked out logits: -infinity to invalid actions (those that try to replace a 1 with a 1)
        """
        logits = super().forward(theta)
        logits[torch.cat((theta, torch.zeros(theta.shape[0], 1)), 1) == 1.] = - float("inf")
        return logits

    def on_policy_trajectory_sample(self, temperature=1.):
        """
        :param temperature: softmax temperature
        :return: a complete GFN trajectory (i.e. ending in a terminating state) as a T x m tensor
        The function assumes the source state of the GFN is [0, 0, ..., 0]
        """
        theta = torch.zeros(1, self.m)
        trajectory = [theta.clone().detach()]
        while True:
            logits = self(theta)
            probs = torch.softmax(logits / temperature, 1)
            idx = Categorical(probs).sample()[0]
            if idx == self.m:  # terminating state
                break
            theta[0, idx] = 1.
            trajectory.append(theta.clone().detach())
        return torch.cat(trajectory, 0)

    def uniform_trajectory_sample(self, terminate_prob=0.1):
        """
        :param terminate_prob: probability of ending the trajectory at each step of the trajectory
        :return: a complete GFN trajectory (i.e. ending in a terminating state) as a T x m tensor
        """
        m = self.m
        theta = torch.zeros(1, m)
        trajectory = [theta.clone().detach()]
        while True:
            possible_indices = [i for i, j in enumerate(theta[0].detach().numpy()) if j == 0]
            if len(possible_indices) == 0:
                break
            probs = ((1 - terminate_prob) / len(possible_indices)) * np.ones(len(possible_indices))
            idx = np.random.choice(possible_indices + [m], p=list(probs) + [terminate_prob])
            if idx == m:
                break
            theta[0, idx] = 1.
            trajectory.append(theta.clone().detach())
        return torch.cat(trajectory, 0)

def modified_trajectory_balance_loss(pf, traj, MIN_REW, pb_fn, reward_fn):
    """
    :param pf: nn.Module representing P_F (can be an instantiation of BinaryMaskGFN e.g.)
    :param traj: sampled trajectory
    :param MIN_REW: minimum reward value to replace lower rewards (including -infinity) with
    :param pb_fn: function taking a trajectory (T x m tensor) as input and outputting the backward probs as a (T-1) tensor
    :param reward_fn: function mapping a trajectory to a reward (list of same length)
    :return: loss(traj)
    Works only if all states are connected to the sink state, those that aren't are given an imaginary reward of MIN_REW
    """
    trajectory_logits = pf(traj)
    final_forward_logprob_differences = trajectory_logits[:-1, -1] - trajectory_logits[1:, -1]
    denominators = torch.logsumexp(trajectory_logits, 1)
    final_forward_logprob_differences = final_forward_logprob_differences - (denominators[:-1] - denominators[1:])
    forward_logprobs = trajectory_logits[:-1, :-1][
        torch.arange(traj.shape[0] - 1), (traj[1:, :] - traj[:-1, :]).argmax(1)]  # 1-dim tensor of size T-1
    forward_logprobs = forward_logprobs - denominators[:-1]

    pb = pb_fn(traj)
    log_pb = torch.log(pb)
    pred = final_forward_logprob_differences + log_pb - forward_logprobs

    rewards = reward_fn(traj)
    trajectory_rewards = torch.tensor(rewards).clamp_min(MIN_REW).to(pred.dtype)

    targets = trajectory_rewards[:-1] - trajectory_rewards[1:]
    loss = nn.MSELoss(reduction='sum')(pred, targets)

    return loss, rewards, forward_logprobs.sum()

def trajectory_balance_loss(pf, traj, MIN_REW, pb_fn, reward_fn):
    """
    :param pf: nn.Module representing P_F (can be an instantiation of BinaryMaskGFN e.g.)
    :param traj: sampled trajectory
    :param MIN_REW: minimum reward value to replace lower rewards (including -infinity) with
    :param pb_fn: function taking a trajectory (T x m tensor) as input and outputting the backward probs as a (T-1) tensor
    :param reward_fn: function mapping a trajectory to a reward (list of same length)
    :return: loss(traj)
    needs the GFN to be paramertrized with logZ
    """
    trajectory_logits = pf(traj)
    denominators = torch.logsumexp(trajectory_logits, 1)
    forward_logprobs = trajectory_logits[:-1, :-1][
        torch.arange(traj.shape[0] - 1), (traj[1:, :] - traj[:-1, :]).argmax(1)]  # 1-dim tensor of size length-1
    forward_logprobs = forward_logprobs - denominators[:-1]
    sink_logprob = trajectory_logits[-1, -1] - denominators[-1]
    pb = pb_fn(traj)
    log_pb = torch.log(pb)

    pred = pf.logZ + forward_logprobs.sum() + sink_logprob - log_pb.sum()
    trajectory_rewards = reward_fn(traj[[-1]])  # log-likelihood (maybe + log-prior)
    targets = torch.tensor(trajectory_rewards).clamp_min(MIN_REW).to(pred.dtype)[0]
    loss = nn.MSELoss()(pred, targets)

    trajectory_logprob = forward_logprobs.sum() + sink_logprob

    return loss, trajectory_rewards, trajectory_logprob


# Enter your code here. Read input from STDIN. Print output to STDOUT
hashset = set(map(int, input().split()))

t = int(input())
bools = []

for _ in range(t):
    childset = set(map(int, input().split()))

    if hashset.intersection(childset) == childset:
        bools.append(True)
    else:
        bools.append(False)

if sum(bools) == len(bools):
    print(True)
else:
    print(False)


import re

email_list = "all_emails_dirty.tsv"

def xml_scrape(line):
    scraped = re.sub(r"<.*>", "", line)
    return scraped

def dash_scrape(line):
    scraped = re.sub(r"----.*", "", line)
    return scraped

def from_scrape(line):
    scraped = re.sub(r"From:.*", "", line)
    return scraped

def spaces_scrape(line):
    scraped = re.sub(r" {5}.*", "", line)
    return scraped

def outlook_scrape(line):
    scraped = re.sub(r"Outlook Migration Team@ENRON.*", "", line)
    return scraped

def enron_sign_scrape(line):
    scraped = re.sub(r" {4}Enron North America Corp.*", "", line)
    return scraped

def to_scrape(line):
    scraped = re.sub(r"To:.*", "", line)
    return scraped

def scrape(line):
    round1 = xml_scrape(line)
    round2 = dash_scrape(round1)
    round3 = from_scrape(round2)
    round4 = outlook_scrape(round3)
    round5 = enron_sign_scrape(round4)
    round6 = to_scrape(round5)
    scraped = spaces_scrape(round6)
    return scraped

def field_split(line):
    fields = line.split("\t")
    return fields

def delete_empty_lines(lines):
    no_empties = [line for line in lines if field_split(line)[2] != ""]
    return no_empties

print("Scraping extraneous text from emails...\n")
with open(email_list, "r", encoding='utf-8') as f:
    emails = f.readlines()
    s_emails = [email.strip() for email in emails]

    scraped_emails = [scrape(email) for email in s_emails]
    empties_deleted = delete_empty_lines(scraped_emails)
print("Done!\n\nWriting clean emails to new doc...")
with open("all_emails_dbl_clean.tsv", "w", encoding='utf-8') as out:
    for i in range(len(empties_deleted)):
        out.write(empties_deleted[i]+"\n")
        if i % 1000 == 0:
            print(f"{str(i)} emails written")


import numpy as np

# Initialization | Run Before Everything
print("Processing Dictionaries...")
words = []

content = open(r"FreqDict.txt").read()
words.extend(content.split("\n"))

nw = []
for wd in words:
    nw.append(wd.upper().split(" "))

freq, wds = np.array(nw).T[:2]
freq = np.int32(freq)
idx = np.where(np.char.isalpha(wds))
fin_freq, fin_wds = freq[idx], wds[idx]

freqdict = {}
for i in range(len(fin_wds)):
    if fin_wds[i] in freqdict:
        freqdict[fin_wds[i]] += fin_freq[i]
    else:
        freqdict[fin_wds[i]] = fin_freq[i]

fin_wds = list(freqdict.keys())

# Necessary Functions

def letterguess(word_len, startlist, roundno, usedletters, verbose):
    revised_words = [wd for wd in fin_wds if len(wd) == word_len]

    def check_word(word):
        for idx in range(len(word)):
            if word[idx] in usedletters: # if letter is in used letters, then could be bad word, or already found good word
                if word[idx] != startlist[idx]:
                    return False
            if startlist[idx] == "*":
                continue
            elif startlist[idx] != word[idx]:
                return False
        return True

    revised_words2 = [i for i in revised_words if check_word(i)]
    if verbose:
        print("Some Possible Words:")
        print(np.random.choice(revised_words2, size = 10))
    alpha = np.array(list("abcdefghijklmnopqrstuvwxyz".upper()))

    freq = {}
    for wd in revised_words2:
        for i in wd:
            if i in freq:
                freq[i] += (1 * freqdict[wd])
            else:
                freq[i] = (1 * freqdict[wd])

    for let in usedletters:
        freq[let] = 0

    probs = []
    for i in alpha:
        try:
            probs.append(freq[i])
        except KeyError:
            probs.append(0)
    probs = np.array(probs)
    probs = probs / np.sum(probs)
    let = np.random.choice(alpha, p = probs)

    return let

def guess(word, totattempts = 10, verbose = True):
    if verbose:
        print("Word to Guess:", word)
        print("Let the Game Begin!")
        print()
    startlist = ["*" for i in range(len(word))]
    wordlist = list(word.upper())
    attempts = totattempts
    usedletters = set()
    roundno = 1
    while attempts > 0:
        if verbose:
            print("Guess #" + str(roundno), "| Attempts:", attempts)
        letter = letterguess(len(word), startlist, roundno, usedletters, verbose).upper()
        if verbose:
            print("Guess is:", letter)

        if letter in usedletters:
            raise Exception("Letter Already Used!")

        usedletters.add(letter)

        if letter in wordlist:
            for idx in range(len(wordlist)):
                if wordlist[idx] == letter:
                    startlist[idx] = letter
            if verbose:
                print("Correct Guess!")
        else:
            if verbose:
                print("Incorrect Guess!")
            attempts -= 1

        if verbose:
            print()
            print("Word:", "".join(startlist))
        roundno += 1
        if startlist == wordlist:
            if verbose:
                print("Guesser Won! It took", totattempts - attempts, "attempts.")
                print()
            return 1
    if verbose:
        print("Guesser Lost! It ran out of attempts.")
        print()
    return 0

# Final Game
print("Done.")

word = str(input("Enter your word: "))
guess(word)

# Calculating Final Winrate for Word
print("Calculating Overall Winrate...")
winrate = 0
for i in range(100):
    winrate += guess(word, verbose = False)
print("Final Winrate for", word.upper() + ":", str(winrate) + "%")


with open("Day 3/input.txt", "r") as f:
    lines = f.readlines()
    moves_wire_1 = lines[0].split(",")
    moves_wire_2 = lines[1].split(",")

def get_points(moveset: list):
    current_x = 0
    current_y = 0

    points = set()

    for move in moveset:
        direction = move[:1]
        steps = int(move[1:])

        if direction == "R":
            line_points = [(current_x + i, current_y) for i in range(1, steps+1)]
            points.update(line_points)
            current_x += steps

        elif direction == "L":
            line_points = [(current_x - i, current_y) for i in range(1, steps+1)]
            points.update(line_points)
            current_x -= steps

        elif direction == "D":
            line_points = [(current_x, current_y - i) for i in range(1, steps+1)]
            points.update(line_points)
            current_y -= steps

        elif direction == "U":
            line_points = [(current_x, current_y + i) for i in range(1, steps+1)]
            points.update(line_points)
            current_y += steps

    return points

# Get all points where the wire goes
points_wire_1 = get_points(moves_wire_1)
points_wire_2 = get_points(moves_wire_2)

# Find the points that are the same in both list
in_both = [p for p in points_wire_2 if p in points_wire_1]

# Find the closest one from the start
distances = [abs(x)+abs(y) for x, y in in_both]
print(min(distances))


import argparse
import os
import sys
from importlib import metadata
from typing import Callable, Optional

from jmeslog import core, model
from jmeslog.constants import DEFAULT_RENDER_TEMPLATE
from jmeslog.errors import NoChangesFoundError, ValidationError

SUB_CMD_FUNC = Callable[[argparse.Namespace], int]

def cmd_new_release(args: argparse.Namespace) -> int:
    # Parse the upcoming changes and determine the type of version
    # bump.
    # Apply the version bump to the last known release and figure out
    # the new version.
    # Create a new version file from the existing changes.
    # Delete the next changes folder.
    changes = core.load_next_changes(args.change_dir)
    if args.release_version is not None:
        next_version = args.release_version
    else:
        last_released_version = core.find_last_released_version(
            args.change_dir
        )
        next_version = core.determine_next_version(
            last_released_version, changes.version_bump_type
        )
    release_file = core.consolidate_next_release(
        next_version, args.change_dir, changes
    )
    print(f"New release file written: {release_file}")
    return 0

def cmd_new_change(args: argparse.Namespace) -> int:
    entry = model.JMESLogEntry(
        type=args.type, category=args.category, description=args.description
    )
    recorder = core.create_entry_recorder(entry, args.change_dir)
    try:
        change_file = recorder.write_change_file_entry()
    except ValidationError as e:
        sys.stderr.write(str(e))
        sys.stderr.write("\n")
        return 1
    except Exception:
        sys.stderr.write("Unexpected error raised:\n\n")
        raise
    print(
        f"The change has been written to: {change_file}\n"
        f"You add this to your commit by running:\n\n"
        f"git add {change_file}\n"
    )
    return 0

def cmd_render(args: argparse.Namespace) -> int:
    changes = core.load_all_changes(args.change_dir)
    template_file = None
    if args.template:
        template_file = os.path.join(
            args.change_dir, 'templates', args.template
        )
        with open(template_file) as f:
            template_contents = f.read()
    else:
        template_contents = DEFAULT_RENDER_TEMPLATE
    core.render_changes(changes, sys.stdout, template_contents)
    return 0

def cmd_init(args: argparse.Namespace) -> int:
    if not os.path.isdir(args.change_dir):
        os.mkdir(args.change_dir)
    return 0

def cmd_query(args: argparse.Namespace) -> int:
    runner = core.ChangeQuery(args.change_dir)
    try:
        result = runner.run_query(args.query_for)
    except NoChangesFoundError as e:
        sys.stdout.write(str(e))
        sys.stdout.write("\n")
        return 1
    print(result)
    return 0

def cmd_pending(args: argparse.Namespace) -> int:
    pending_changes = core.load_next_changes(args.change_dir)
    sys.stdout.write('\n')
    core.render_single_release_changes(pending_changes, sys.stdout)
    return 0

def create_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--version', action='version', version=metadata.version(__package__)
    )
    parser.add_argument(
        '--change-dir',
        default='.changes',
        help='The location of the .changes directory.',
    )
    subparser = parser.add_subparsers()

    init = subparser.add_parser('init')
    init.set_defaults(func=cmd_init)

    new_change = subparser.add_parser('new-change')
    new_change.set_defaults(func=cmd_new_change)
    new_change.add_argument(
        '-t',
        '--type',
        default='',
        choices=('bugfix', 'feature', 'enhancement'),
    )
    new_change.add_argument('-c', '--category', dest='category', default='')
    new_change.add_argument(
        '-d', '--description', dest='description', default=''
    )

    new_release = subparser.add_parser('new-release')
    new_release.set_defaults(func=cmd_new_release)
    new_release.add_argument(
        '-r', '--release-type', default='', choices=('patch', 'minor', 'major')
    )
    new_release.add_argument(
        '--release-version',
        help=(
            'Specify release version.  If not specified '
            'this value will be determined automatically.'
        ),
    )
    new_release.add_argument(
        '-d',
        '--description',
        dest='description',
        help=("Provide additional release notes for this " "release."),
    )

    render = subparser.add_parser('render')
    render.add_argument(
        '-t',
        '--template',
        help=(
            'The name of the template to use from the '
            '.changes/templates/ directory.'
        ),
    )
    render.set_defaults(func=cmd_render)

    query = subparser.add_parser('query')
    query.add_argument(
        'query_for',
        choices=('next-release-type', 'next-version', 'last-release-version'),
    )
    query.set_defaults(func=cmd_query)

    pending = subparser.add_parser('pending')
    pending.set_defaults(func=cmd_pending)

    return parser

def main(argv: Optional[list[str]] = None) -> int:
    parser = create_parser()
    if argv is None:
        argv = sys.argv[1:]
    args = parser.parse_args(argv)
    if not hasattr(args, 'func'):
        parser.print_help()
        return 0
    else:
        handler: SUB_CMD_FUNC = args.func
        return handler(args)

if __name__ == '__main__':
    sys.exit(main())


import re
import gast

from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import origin_info
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import transformer
from tensorflow.python.platform import test

class TransformerTest(test.TestCase):

  def _simple_context(self):
    entity_info = transformer.EntityInfo(
        name='Test_fn',
        source_code=None,
        source_file=None,
        future_features=(),
        namespace=None)
    return transformer.Context(entity_info, None, None)

  def assertSameAnno(self, first, second, key):
    self.assertIs(anno.getanno(first, key), anno.getanno(second, key))

  def assertDifferentAnno(self, first, second, key):
    self.assertIsNot(anno.getanno(first, key), anno.getanno(second, key))

  def test_state_tracking(self):

    class LoopState(object):
      pass

    class CondState(object):
      pass

    class TestTransformer(transformer.Base):

      def visit(self, node):
        anno.setanno(node, 'loop_state', self.state[LoopState].value)
        anno.setanno(node, 'cond_state', self.state[CondState].value)
        return super(TestTransformer, self).visit(node)

      def visit_While(self, node):
        self.state[LoopState].enter()
        node = self.generic_visit(node)
        self.state[LoopState].exit()
        return node

      def visit_If(self, node):
        self.state[CondState].enter()
        node = self.generic_visit(node)
        self.state[CondState].exit()
        return node

    tr = TestTransformer(self._simple_context())

    def test_function(a):
      a = 1
      while a:
        _ = 'a'
        if a > 2:
          _ = 'b'
          while True:
            raise '1'
        if a > 3:
          _ = 'c'
          while True:
            raise '1'

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    fn_body = node.body
    outer_while_body = fn_body[1].body
    self.assertSameAnno(fn_body[0], outer_while_body[0], 'cond_state')
    self.assertDifferentAnno(fn_body[0], outer_while_body[0], 'loop_state')

    first_if_body = outer_while_body[1].body
    self.assertDifferentAnno(outer_while_body[0], first_if_body[0],
                             'cond_state')
    self.assertSameAnno(outer_while_body[0], first_if_body[0], 'loop_state')

    first_inner_while_body = first_if_body[1].body
    self.assertSameAnno(first_if_body[0], first_inner_while_body[0],
                        'cond_state')
    self.assertDifferentAnno(first_if_body[0], first_inner_while_body[0],
                             'loop_state')

    second_if_body = outer_while_body[2].body
    self.assertDifferentAnno(first_if_body[0], second_if_body[0], 'cond_state')
    self.assertSameAnno(first_if_body[0], second_if_body[0], 'loop_state')

    second_inner_while_body = second_if_body[1].body
    self.assertDifferentAnno(first_inner_while_body[0],
                             second_inner_while_body[0], 'cond_state')
    self.assertDifferentAnno(first_inner_while_body[0],
                             second_inner_while_body[0], 'loop_state')

  def test_state_tracking_context_manager(self):

    class CondState(object):
      pass

    class TestTransformer(transformer.Base):

      def visit(self, node):
        anno.setanno(node, 'cond_state', self.state[CondState].value)
        return super(TestTransformer, self).visit(node)

      def visit_If(self, node):
        with self.state[CondState]:
          return self.generic_visit(node)

    tr = TestTransformer(self._simple_context())

    def test_function(a):
      a = 1
      if a > 2:
        _ = 'b'
        if a < 5:
          _ = 'c'
        _ = 'd'

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    fn_body = node.body
    outer_if_body = fn_body[1].body
    self.assertDifferentAnno(fn_body[0], outer_if_body[0], 'cond_state')
    self.assertSameAnno(outer_if_body[0], outer_if_body[2], 'cond_state')

    inner_if_body = outer_if_body[1].body
    self.assertDifferentAnno(inner_if_body[0], outer_if_body[0], 'cond_state')

  def test_visit_block_postprocessing(self):

    class TestTransformer(transformer.Base):

      def _process_body_item(self, node):
        if isinstance(node, gast.Assign) and (node.value.id == 'y'):
          if_node = gast.If(
              gast.Name(
                  'x', ctx=gast.Load(), annotation=None, type_comment=None),
              [node], [])
          return if_node, if_node.body
        return node, None

      def visit_FunctionDef(self, node):
        node.body = self.visit_block(
            node.body, after_visit=self._process_body_item)
        return node

    def test_function(x, y):
      z = x
      z = y
      return z

    tr = TestTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    node = tr.visit(node)

    self.assertEqual(len(node.body), 2)
    self.assertIsInstance(node.body[0], gast.Assign)
    self.assertIsInstance(node.body[1], gast.If)
    self.assertIsInstance(node.body[1].body[0], gast.Assign)
    self.assertIsInstance(node.body[1].body[1], gast.Return)

  def test_robust_error_on_list_visit(self):

    class BrokenTransformer(transformer.Base):

      def visit_If(self, node):
        # This is broken because visit expects a single node, not a list, and
        # the body of an if is a list.
        # Importantly, the default error handling in visit also expects a single
        # node.  Therefore, mistakes like this need to trigger a type error
        # before the visit called here installs its error handler.
        # That type error can then be caught by the enclosing call to visit,
        # and correctly blame the If node.
        self.visit(node.body)
        return node

    def test_function(x):
      if x > 0:
        return x

    tr = BrokenTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    with self.assertRaises(ValueError) as cm:
      node = tr.visit(node)
    obtained_message = str(cm.exception)
    expected_message = r'expected "ast.AST", got "\<(type|class) \'list\'\>"'
    self.assertRegex(obtained_message, expected_message)

  def test_robust_error_on_ast_corruption(self):
    # A child class should not be able to be so broken that it causes the error
    # handling in `transformer.Base` to raise an exception.  Why not?  Because
    # then the original error location is dropped, and an error handler higher
    # up in the call stack gives misleading information.

    # Here we test that the error handling in `visit` completes, and blames the
    # correct original exception, even if the AST gets corrupted.

    class NotANode(object):
      pass

    class BrokenTransformer(transformer.Base):

      def visit_If(self, node):
        node.body = NotANode()
        raise ValueError('I blew up')

    def test_function(x):
      if x > 0:
        return x

    tr = BrokenTransformer(self._simple_context())

    node, _ = parser.parse_entity(test_function, future_features=())
    with self.assertRaises(ValueError) as cm:
      node = tr.visit(node)
    obtained_message = str(cm.exception)
    # The message should reference the exception actually raised, not anything
    # from the exception handler.
    expected_substring = 'I blew up'
    self.assertIn(expected_substring, obtained_message)

  def test_origin_info_propagated_to_new_nodes(self):

    class TestTransformer(transformer.Base):

      def visit_If(self, node):
        return gast.Pass()

    tr = TestTransformer(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 1
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    node = tr.visit(node)

    created_pass_node = node.body[1]
    # Takes the line number of the if statement.
    self.assertEqual(
        anno.getanno(created_pass_node, anno.Basic.ORIGIN).loc.lineno, 102)

  def test_origin_info_preserved_in_moved_nodes(self):

    class TestTransformer(transformer.Base):

      def visit_If(self, node):
        return node.body

    tr = TestTransformer(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 1
        x += 3
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    node = tr.visit(node)

    assign_node = node.body[1]
    aug_assign_node = node.body[2]
    # Keep their original line numbers.
    self.assertEqual(
        anno.getanno(assign_node, anno.Basic.ORIGIN).loc.lineno, 103)
    self.assertEqual(
        anno.getanno(aug_assign_node, anno.Basic.ORIGIN).loc.lineno, 104)

class CodeGeneratorTest(test.TestCase):

  def _simple_context(self):
    entity_info = transformer.EntityInfo(
        name='test_fn',
        source_code=None,
        source_file=None,
        future_features=(),
        namespace=None)
    return transformer.Context(entity_info, None, None)

  def test_basic_codegen(self):

    class TestCodegen(transformer.CodeGenerator):

      def visit_Assign(self, node):
        self.emit(parser.unparse(node, include_encoding_marker=False))
        self.emit('\n')

      def visit_Return(self, node):
        self.emit(parser.unparse(node, include_encoding_marker=False))
        self.emit('\n')

      def visit_If(self, node):
        self.emit('if ')
        # This is just for simplifity. A real generator will walk the tree and
        # emit proper code.
        self.emit(parser.unparse(node.test, include_encoding_marker=False))
        self.emit(' {\n')
        self.visit_block(node.body)
        self.emit('} else {\n')
        self.visit_block(node.orelse)
        self.emit('}\n')

    tg = TestCodegen(self._simple_context())

    def test_fn():
      x = 1
      if x > 0:
        x = 2
        if x > 1:
          x = 3
      return x

    node, source = parser.parse_entity(test_fn, future_features=())
    origin_info.resolve(node, source, 'test_file', 100, 0)
    tg.visit(node)

    r = re.compile('.*'.join([
        r'x = 1',
        r'if \(?x > 0\)? {',
        r'x = 2',
        r'if \(?x > 1\)? {',
        r'x = 3',
        r'} else {',
        r'}',
        r'} else {',
        r'}',
        r'return x']), re.DOTALL)

    self.assertRegex(tg.code_buffer, r)
    # TODO(mdan): Test the source map.

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


from enum import Enum
from collections import namedtuple
import re

class Transação(object):
	"""docstring for Transação"""
	# Estados possíveis em que uma transação pode estar
	(INICIADA, LENDO, COMMITED) = (1, 2, 3)

	def __init__(self, identificador, operações):
		super(Transação, self).__init__()
		self.identificador = identificador
		self.operações = operações
		self.estado = self.INICIADA
		self.conjunto_leitura = set()
		self.conjunto_escrita = set()

		self.timestamp_commit = None
		self.timestamp_leitura = None

		for op in operações:
			if   op.op == "w":
				self.conjunto_escrita.add(op.objeto)
			elif op.op == "r":
				self.conjunto_leitura.add(op.objeto)

	def __repr__(self):
		out = "Transação("+repr(self.identificador)+",[\""
		for op in self.operações:
			out+=op.op+"("+op.objeto+")"
		out += "\"])"
		return out

	def __str__(self):
		out = "T"+str(self.identificador)+":"
		for op in self.operações:
			out+=op.op+"("+op.objeto+")"
		return out

	def nome(self):
		return "T"+str(self.identificador)

	def primeiro_teste(Ti,Tj):
		"""Transação Tj completa sua fase de escrita antes que Ti começou sua
		fase de leitura """
		#print ("Primeiro Teste")
		#print (Tj.nome()+".timestamp_commit < "+Ti.nome()+".timestamp_leitura")
		#print (str(Tj.timestamp_commit)+"<"+str(Ti.timestamp_leitura))
		#print ((Tj.timestamp_commit)<(Ti.timestamp_leitura))
		return Tj.timestamp_commit < Ti.timestamp_leitura

	def segundo_teste(Ti, Tj):
		"""Ti começa a sua fase de escrita depois que Tj completa sua fase de
		escrita e o conjunto de leitura de Ti não tem intersecção com o
		conjunto de escrita de Tj"""
		#print ("\nSegundo Teste")
		#print (Ti.nome()+".conjunto_leitura.isdisjoint("+Tj.nome()+".conjunto_escrita)")
		#print (str(Ti.conjunto_leitura)+".isdisjoint("+str(Tj.conjunto_escrita)+")")
		#print (Ti.conjunto_leitura.isdisjoint(Tj.conjunto_escrita))
		return Ti.conjunto_leitura.isdisjoint(Tj.conjunto_escrita)

	def terceiro_teste(Ti, Tj):
		"""A união do conjunto de leitura e escrita de Ti não tem intersecção
		com o conjunto de escrita de Tj e Tj completa sua fase de leitura antes
		de Ti."""
		x = Ti.conjunto_leitura.isdisjoint(Tj.conjunto_escrita) and \
		    Ti.conjunto_escrita.isdisjoint(Tj.conjunto_escrita)
		#print("\nTerceiro Teste")
		#print(Ti.nome()+".conjunto_leitura.isdisjoint("+Tj.nome()+".conjunto_escrita) and \n"+
		#      Ti.nome()+".conjunto_escrita.isdisjoint("+Tj.nome()+".conjunto_escrita)")
		#print(str(Ti.conjunto_leitura)+".isdisjoint("+str(Tj.conjunto_escrita)+") and \n"+
		#      str(Ti.conjunto_escrita)+".isdisjoint("+str(Tj.conjunto_escrita)+")")
		#print(x)
		return x

	def validar(Ti,timestamp,comitadas):
		teste = lambda Tj: Ti.primeiro_teste(Tj) or \
		                   Ti.segundo_teste(Tj)  or \
		                   Ti.terceiro_teste(Tj)

		validada = all(map(teste,comitadas))
		if (validada):
			Ti.timestamp_commit = timestamp
			Ti.estado = Ti.COMMITED
		return validada

	def ler_do_arquivo(caminho):
		arquivo = open(caminho,"r");
		retorno = []
		for line in arquivo:
			identificador = int(line.split(":")[0][1:])
			operações = re.findall("(\S+?)\((\S+?)\)",line.split(":")[1])
			operações = list(map(Operação._make,operações))
			retorno.append(Transação(identificador,operações))
		return retorno

	def iniciar_leitura(self,timestamp):
		self.estado = self.LENDO
		self.timestamp_leitura = timestamp
		self.numero_operações = 0

	def próxima_operação(self):
		"""Leva a transação par a próxima operação.
		Retorna True se todas as operações daquela transação forem realizadas,
		assinalando a hora de dar commit"""

		self.numero_operações = self.numero_operações + 1
		return self.numero_operações == len(self.operações)

	def reiniciar_transação(self):
		"""Reincia a transação"""
		self.estado = self.INICIADA

Operação = namedtuple("Operação",['op','objeto'])


from pages import covid, weather, economy
import csv

file_path = "data/data.csv"
columns = ["Area", "Active cases", "Total vaccines", "Temperature", "Humidity", "Air Quality", "Unemployed"]

def create_new_file(file):
    with open(file, 'w') as f:
        f.write("")

def write_to_file(data):
    with open(file_path, 'w', newline='') as f:
        writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)

        writer.writerow([column for column in columns])

        for j in range(len(data[0])):
            current = [data[i][j] for i in range(len(columns))]
            writer.writerow(current)

def main():
    create_new_file(file_path)

    data = [covid.areas]
    data.append(covid.get_new_cases())
    data.append(covid.get_vaccines())
    data.append(weather.get_temperatures())
    data.append(weather.get_humidities())
    data.append(weather.get_aq())
    data.append(economy.get_areas_unemployement())

    write_to_file(data)

if __name__ == "__main__":
    main()


## imaging_360.py
# This example demonstrates how to read all 4 csi cameras and display in a single openCV window. If you encounter any errors,
# use the hardware_test_csi_camera_single.py script to find out which camera is giving you trouble.

from pal.utilities.vision import Camera2D
import time
import struct
import numpy as np
import cv2

# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
## Timing Parameters and methods
startTime = time.time()
def elapsed_time():
    return time.time() - startTime

sampleRate     = 30.0
sampleTime     = 1/sampleRate
simulationTime = 60.0
print('Sample Time: ', sampleTime)

# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
# Additional parameters
counter = 0
imageWidth = 640
imageHeight = 480
imageBuffer360 = np.zeros((imageHeight + 40, 4*imageWidth + 120, 3), dtype=np.uint8) # 20 px padding between pieces

# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
## Initialize the CSI cameras
# myCam1 = Camera2D(cameraId="0", frameWidth=imageWidth, frameHeight=imageHeight, frameRate=sampleRate)
# myCam2 = Camera2D(cameraId="1", frameWidth=imageWidth, frameHeight=imageHeight, frameRate=sampleRate)
# myCam3 = Camera2D(cameraId="2", frameWidth=imageWidth, frameHeight=imageHeight, frameRate=sampleRate)
myCam4 = Camera2D(cameraId="3", frameWidth=imageWidth, frameHeight=imageHeight, frameRate=sampleRate)

# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
## Main Loop
try:
    # while elapsed_time() < simulationTime:
    while True:

        # Start timing this iteration
        start = time.time()

        # Capture RGB Image from CSI
        # myCam1.read()
        # myCam2.read()
        # myCam3.read()
        myCam4.read()

        counter += 1

        # End timing this iteration
        end = time.time()

        # Calculate the computation time, and the time that the thread should pause/sleep for
        computationTime = end - start
        sleepTime = sampleTime - ( computationTime % sampleTime )

        # Stitch images together with black padding
        horizontalBlank     = np.zeros((20, 4*imageWidth+120, 3), dtype=np.uint8)
        verticalBlank       = np.zeros((imageHeight, 20, 3), dtype=np.uint8)

        # imageBuffer360 = np.concatenate(
        #                                    (horizontalBlank,
        #                                     np.concatenate((    verticalBlank,
        #                                                         # myCam2.imageData[:,320:640],
        #                                                         # verticalBlank,
        #                                                         # myCam3.imageData,
        #                                                         # verticalBlank,
        #                                                         myCam4.imageData,
        #                                                         # verticalBlank,
        #                                                         # myCam1.imageData,
        #                                                         # verticalBlank,
        #                                                         # # myCam2.imageData[:,0:320],
        #                                                         # verticalBlank
        #                                                         ),
        #                                                         axis = 1),
        #                                     horizontalBlank
        #                                     ),
        #                                     axis=0
        #                                 )

        # Display the stitched image at half the resolution
        # cv2.imshow('Combined View', cv2.resize(imageBuffer360, (int(2*imageWidth), int(imageHeight/2))))
        # cv2.imshow('Combined View', myCam4.imageData)
        img = cv2.imread('LAneTest.png')
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        # Apply edge detection method on the image
        edges = cv2.Canny(gray, 200, 250, apertureSize=3)

        # This returns an array of r and theta values
        lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

        cv2.imshow('Combined Viewedge', edges)

        # The below for loop runs till r and theta values
        # are in the range of the 2d array
        if (lines is not None) :
            for r_theta in lines:
                arr = np.array(r_theta[0], dtype=np.float64)
                r, theta = arr
                # Stores the value of cos(theta) in a
                a = np.cos(theta)

                # Stores the value of sin(theta) in b
                b = np.sin(theta)

                # x0 stores the value rcos(theta)
                x0 = a*r

                # y0 stores the value rsin(theta)
                y0 = b*r

                # x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
                x1 = int(x0 + 1500*(-b))

                # y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
                y1 = int(y0 + 1500*(a))

                # x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
                x2 = int(x0 - 1500*(-b))

                # y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
                y2 = int(y0 - 1500*(a))

                # cv2.line draws a line in img from the point(x1,y1) to (x2,y2).
                # (0,0,255) denotes the colour of the line to be
                # drawn. In this case, it is red.
                cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 255), 1)
        cv2.imshow('Combined View', gray)

        # Pause/sleep for sleepTime in milliseconds
        msSleepTime = int(1000*sleepTime)
        if msSleepTime <= 0:
            msSleepTime = 1 # this check prevents an indefinite sleep as cv2.waitKey waits indefinitely if input is 0
        cv2.waitKey(msSleepTime)

except KeyboardInterrupt:
    print("User interrupted!")

finally:
    # Terminate all webcam objects
    # myCam1.terminate()
    # myCam2.terminate()
    # myCam3.terminate()
    myCam4.terminate()
# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --


import XSSSD
import asyncio
import tkinter as tk
from tkinter import *
import sys

#sys.setrecursionlimit(10000)

class App:
    async def exec(self):
        self.window = Window(asyncio.get_event_loop())
        await self.window.show()

class Window(Tk):
    def __init__(self, loop):

        self.loop = loop
        self.root = Tk()
        self.root.configure(bg=self.Colors.black)
        self.SetUrlEntryText = tk.StringVar()
        self.SetInputEntryText = tk.StringVar()

        self.IntroUrlLabel = tk.Label(text="Introduce URL: ",bg=self.Colors.blue, fg=self.Colors.green,width=30).grid(column=0,row=0)
        self.IntroInputLabel = tk.Label(text="Introduce Input: ",bg=self.Colors.blue, fg=self.Colors.green,width=30).grid(column=0,row=1)
        self.SetUrlEntry = tk.Entry(width=50, textvariable=self.SetUrlEntryText,bg=self.Colors.blue, fg=self.Colors.green).grid(column=1,row=0)
        self.SetInputEntry = tk.Entry(width=50, textvariable=self.SetInputEntryText,bg=self.Colors.blue, fg=self.Colors.green).grid(column=1,row=1)
        self.SearchButton = tk.Button(text="Exploit",width=10,height=5,command=self.exploit,bg=self.Colors.blue, fg=self.Colors.green).grid(column=2,row=0,columnspan=2,rowspan=2, pady=10)
        self.SearchButton = tk.Button(text="Save",width=10,height=5,command=self.saveInDisc,bg=self.Colors.blue, fg=self.Colors.green).grid(column=2,row=2,padx=10)
        self.VulenrableUrlListbox = tk.Listbox(width=40, bg=self.Colors.blue, fg=self.Colors.green)
        self.VulenrableUrlListbox.grid(column=0,row=2,padx=10)
        self.VulenrabilitiesPerUrl = tk.Text(bg=self.Colors.blue, fg=self.Colors.green,state="disabled")
        self.VulenrabilitiesPerUrl.grid(column=1,row=2, pady=10)
        self.VulenrableUrlListbox.bind("<<ListboxSelect>>", self.pepe)

        self.arrayOfVulnerabilities = {}
        self.saves=0

    async def show(self):
        while True:
            try:
                self.root.state()
                self.root.update()
                await asyncio.sleep(.1)
            except:
                break

    class Colors():
        black = "#000033"
        blue = "#3137fd"
        green="#66ff33"

    #payloadsValidos = XSSSD.payloadsValidos

    def pepe(self,event):
       asyncio.gather(self.vulnerabilitiesText(event))

    async def vulnerabilitiesText(self,event):
        try:
            ListaVulnSinCorchetes = self.arrayOfVulnerabilities[self.VulenrableUrlListbox.get(self.VulenrableUrlListbox.curselection()[0])]
            self.VulenrabilitiesPerUrl.config(state="normal")
            self.VulenrabilitiesPerUrl.delete('1.0', END)
            self.VulenrabilitiesPerUrl.insert(INSERT, "\n ------------------------------Estos payloads servirían---------------------- \n")
            #ListaVulnSinCorchetes = arrayOfVulnerabilities[event.widget.get(event.widget.curselection())]
            self.VulenrabilitiesPerUrl.insert(INSERT,"\n")
            for payloads in ListaVulnSinCorchetes:
                self.VulenrabilitiesPerUrl.insert(INSERT,payloads)
                self.VulenrabilitiesPerUrl.insert(INSERT,"\n")
                self.VulenrabilitiesPerUrl.insert(INSERT,"\n")
            self.VulenrabilitiesPerUrl.config(state="disabled")
        except:
            print

    async def ponerNombre(self):
        await asyncio.sleep(1)
        self.VulenrableUrlListbox.insert(tk.END,XSSSD.urlLink)
        await asyncio.sleep(1)
        self.arrayOfVulnerabilities[XSSSD.urlLink] = XSSSD.payloadsValidos

    async def executeOrder66(self):
        XSSSD.urlLink = self.SetUrlEntryText.get()
        XSSSD.inputLink = self.SetInputEntryText.get()
        XSSSD.payloadsValidos=[]
        XSSSD.posicionRespuesta=0
        XSSSD.respuesta=""
        asyncio.gather(XSSSD.main())
        asyncio.gather(self.ponerNombre())

    def exploit(self):
        asyncio.gather(self.executeOrder66())

    def saveInDisc(self):
        self.saves+=1
        with open('SavedOutputs/output'+str(self.saves)+'.txt', 'w') as f:
            for key in self.arrayOfVulnerabilities:
                f.write(str(key) + ': ' + str(self.arrayOfVulnerabilities[key]) + '\n\n')

asyncio.run(App().exec())


# coding: utf-8
import re

from batch.crawler import Crawler

def main():
  headers = {'Accept-Language': 'ja'}
  with Crawler() as crawler:
    html = crawler.get_html('https://beta.atcoder.jp/contests/archive', headers)
    page_count = len(html.cssselect('ul.pagination li'))
    print(page_count)

    for i in range(page_count):
      html = crawler.get_html(f'https://beta.atcoder.jp/contests/archive?page={i+1}', headers)
      table = html.cssselect('div.table-responsive table')[0]
      contests = table.cssselect('tr td:nth-child(2) a')
      for contest in contests:
        link = contest.get('href')
        match = re.fullmatch('^/contests/(.+)$', link)
        if match:
          print(match[1])

if __name__ == '__main__':
  main()


#!/usr/bin/env python3

def count_trees(*slopes):
    with open("day-3-map.txt") as f:
        map = f.read().splitlines()
    total = 1
    for slope in slopes:
        count = 0
        xcord, ycord = 0, 0
        while ycord < (len(map) - 1):
            xcord += slope[0]
            ycord += slope[1]
            if xcord > (len(map[ycord])-1):
                xcord -= len(map[ycord])
            if map[ycord][xcord] == "#":
                count +=1
        total *= count
    print (total)

if __name__ == "__main__":
    count_trees((3,1))
    count_trees((1,1), (3,1), (5,1), (7,1),(1,2))


class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:

        # pos = [-1, -1]
        #
        # if len(nums) > 0 and target in nums:
        #     for i in range(len(nums)):
        #         if nums[i] == target:
        #             if pos[0] == -1:
        #                 pos = [i, i]
        #             else:
        #                 pos[1] = i

        # return pos

        # if target not in nums:
        #     return [-1, -1]
        #
        # start = bisect_left(nums, target)
        # end = bisect_right(nums, target) - 1
        #
        # return [start, end]

        left, right = 0, len(nums) - 1

        while left <= right:
            if nums[left] == target and nums[right] == target:
                return [left, right]
            if nums[left] < target:
                left += 1
            if nums[right] > target:
                right -= 1

        return [-1, -1]


from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse

# Create your models here.
#Quiz Model
class Quiz(models.Model):
    title = models.CharField(max_length=100, verbose_name="Quiz Title")
    slug = models.SlugField(max_length=200, unique=True, null=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    date = models.DateTimeField(null=True, blank=True)
    duration = models.PositiveIntegerField(verbose_name="Quiz Duration (mins)", null=True, blank=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

    def get_group_detail(self):
        return reverse('quiz_detail', args=[self.slug])

#Question Model
class Question(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions", verbose_name="Quiz", null=True)
    order = models.PositiveIntegerField(verbose_name="Question Order", default=1)
    question = models.TextField(null=True, blank=True, verbose_name="Question")
    image = models.ImageField(upload_to='questions/image/', blank=True, null=True, verbose_name='Question image')
    optionA = models.CharField(max_length=200, null=True, blank=True, verbose_name="Option A")
    optionB = models.CharField(max_length=200, null=True, blank=True, verbose_name="Option B")
    optionC = models.CharField(max_length=200, null=True, blank=True, verbose_name="Option C")
    optionD = models.CharField(max_length=200, null=True, blank=True, verbose_name="Option D")
    cat = (('optionA', 'optionA'), ('optionB', 'optionB'), ('optionC', 'optionC'), ('optionD', 'optionD'))
    answer = models.CharField(max_length=200, choices=cat)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f'Question {self.order}'

# Groups Model
GROUP_CHOICES = (
    ('Public', 'Public'),
    ('Private', 'Private')
)
class Group(models.Model):
    title = models.CharField(max_length=100, verbose_name="Group Title", null=True)
    description = models.TextField(verbose_name="Group Description", null=True, blank=True)
    type = models.CharField(max_length=100, choices=GROUP_CHOICES, verbose_name="Group Type", default='Public')
    slug = models.SlugField(max_length=200, unique=True, null=True)
    image = models.ImageField(upload_to='groups/image/', blank=True, null=True, verbose_name='Group image')
    admins = models.ManyToManyField(User, related_name="group_admin", blank=True)
    members = models.ManyToManyField(User, related_name="group_member",blank=True)
    quizzes = models.ManyToManyField(Quiz, related_name="group", blank=True)

    def get_group_detail(self):
        return reverse('group_detail', args=[self.slug])

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

#Profile Model
class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile")
    f_name = models.CharField(max_length=100, verbose_name="First Name", null=True)
    l_name = models.CharField(max_length=100, verbose_name="Last Name", null=True)
    photo = models.ImageField(upload_to='users/photo/', blank=True, null=True, verbose_name='Profile Pic')
    about = models.TextField(verbose_name="About", null=True, blank=True)
    school = models.CharField(max_length=200, verbose_name="Institution", null=True, blank=True)
    course = models.CharField(max_length=200, verbose_name="Course Studying", null=True, blank=True)
    quiz = models.ManyToManyField(Quiz, related_name="creator", blank=True)

    def get_user_profile(self):
        return reverse('user_profile', args=[self.user.username])

    def __str__(self):
        return f'{self.f_name} {self.l_name}'

    class Meta:
        ordering = ['l_name']

# Score Model
REMARK_CHOICES = (
    ('Gold', 'Gold'),
    ('Silver', 'Silver'),
    ('Bronze', 'Bronze'),
    ('Copper', 'Copper'),
)
class Score(models.Model):
    student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="scores")
    name = models.CharField(max_length=100, null=True, blank=True, verbose_name="name")
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="score")
    score = models.FloatField(verbose_name="Total Score")
    remark = models.CharField(max_length=100, choices=REMARK_CHOICES, null=True, blank=True, verbose_name="Remark")
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.student}'

    class Meta:
        ordering = ['-score']

class Chat(models.Model):
    sender = models.CharField(max_length=100, null=True, verbose_name="sender")
    receiver = models.CharField(max_length=100, null=True, verbose_name="receiver")
    message = models.TextField(verbose_name="message")
    date = models.DateTimeField(auto_now_add=True, null=True)
    seen = models.BooleanField(default=False, null=True)

    def __str__(self):
        return f'{self.sender}'

    class Meta:
        ordering = ['date']

class Developer(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="developer", null=True)
    nickname = models.CharField(max_length=100, verbose_name="Nickname", null=True)
    f_name = models.CharField(max_length=100, verbose_name="First Name", null=True)
    l_name = models.CharField(max_length=100, verbose_name="Last Name", null=True)
    photo = models.ImageField(upload_to='devs/photo/', blank=True, null=True, verbose_name='Profile Pic')
    about = models.TextField(verbose_name="About", null=True, blank=True)
    organization = models.CharField(max_length=200, verbose_name="Organization", null=True, blank=True)
    location = models.CharField(max_length=200, verbose_name="Location", null=True, blank=True)
    skill = models.CharField(max_length=200, verbose_name="Skills", null=True, blank=True)
    email = models.EmailField(max_length=200, verbose_name="Email", null=True, blank=True)
    phone_no = models.CharField(max_length=200, verbose_name="Phone Number", null=True, blank=True)
    website = models.URLField(max_length=200, verbose_name="website", null=True, blank=True)
    facebook = models.URLField(max_length=200, verbose_name="facebook", null=True, blank=True)
    twitter = models.URLField(max_length=200, verbose_name="twitter", null=True, blank=True)
    github = models.URLField(max_length=200, verbose_name="github", null=True, blank=True)
    whatsapp = models.URLField(max_length=200, verbose_name="whatsapp", null=True, blank=True)

    def __str__(self):
        return f'{self.nickname}'


from aiogram import Bot,Dispatcher,executor,types
from config import API_TOKEN
import logging
from buttons  import natija,natijaa

logging.basicConfig(level=logging.INFO)

bot=Bot(token=API_TOKEN)
dp=Dispatcher(bot)

@dp.message_handler(commands=['start'])
async def start(message: types.Message):
    ism = message.from_user.first_name
    await message.answer(f"Assalomu aleykum {ism}. Botimizga xush kelibsiz.",reply_markup=natija)

@dp.message_handler(text=["Ma'lumot"])
async def start(message: types.Message):
    await message.answer_photo("https://t.me/alisher_sadullaev/3419",
    caption="Ko'proq Ma'lumot:'https://ezguamal.org/taskin'")

@dp.message_handler(text="Xodimlar haqida ma'lumot")
async def start(message: types.Message):
    await message.answer("🤵🏼 Mamayusupov Ilxom Ravshanovich: Vrach reanimatolog, Bo'lim mudiri",reply_markup=natija)
    await message.answer("🧑 Ochilova Zilola Absalom qizi: Psixolog",reply_markup=natija)

if __name__=='__main__':
    executor.start_polling(dp, skip_updates=True)


from tensorflow.python.ops import string_ops
from tensorflow.python.platform import test

class StringStripOpTest(test.TestCase):
  """ Test cases for tf.strings.strip."""

  def test_string_strip(self):
    strings = ["pigs on the wing", "animals"]

    with self.cached_session() as sess:
      output = string_ops.string_strip(strings)
      output = self.evaluate(output)
      self.assertAllEqual(output, [b"pigs on the wing", b"animals"])

  def test_string_strip_2d(self):
    strings = [["pigs on the wing", "animals"],
               [" hello ", "\n\tworld \r \n"]]

    with self.cached_session() as sess:
      output = string_ops.string_strip(strings)
      output = self.evaluate(output)
      self.assertAllEqual(output, [[b"pigs on the wing", b"animals"],
                                   [b"hello", b"world"]])

  def test_string_strip_with_empty_strings(self):
    strings = [" hello ", "", "world ", " \t \r \n "]

    with self.cached_session() as sess:
      output = string_ops.string_strip(strings)
      output = self.evaluate(output)
      self.assertAllEqual(output, [b"hello", b"", b"world", b""])

if __name__ == "__main__":
  test.main()


from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http.request import Request
from test_scrapy.items import TestScrapyItem

class WoblogSpider(BaseSpider):
    name = "woblog"
    allowed_domains = ["tetsuwo.tumblr.com"]
    start_urls = ["http://tetsuwo.tumblr.com"]

    def parse(self, response):
        hxs = HtmlXPathSelector(request)

        next_page = hxs.select("//div[@class='pagination']/a[@class='next_page']/@href").extract()
        if not not next_page:
            yield Request(next_page[0], self.parse)

        posts = hxs.select("//div[@class='post']")
        items = []
        for post in posts:
            item = TestScrapyItem()
            item["title"] = post.select("//div[@class='bodytext']/h2/a/text()").extract()
            item["link"] = post.select("//div[@class='bodytext']/h2/a/@href").extract()
            item["content"] = post.select("//div[@class='bodytext']/p/text()").extract()
            items.append(item)
        for item in items:
            yield item