from django.urls import path
from app_feria.views import *
from django.contrib.auth.views import LogoutView
from app_feria import views
"""

urlpatterns = [
    path('', inicio, name="Inicio"),
    path('vuelo/', vuelo),
    path('personal/', personal),
    path('pasajero/', pasajero),
    path('sobrenostros', sobrenosotros, name="Sobrenosotros"),

#URL DE CREACION
    path('formulario1/', formulariovuelo, name="Crear Vuelos"),
    path('formulario2/', formulariopersonal, name="Crear Personal"),
    path('formulario3/', formulariopasajero, name="Crear Pasajeros"),

#URL DE LEER
    path('leerVuelos/',leerVuelos, name="Leer Vuelos"),
    path('leerPersonal/',leerPersonal, name="Leer Personal"),
    path('leerPasajeros/',leerPasajero, name="Leer Pasajeros"),

#URL DE EDICION
    path('editaVuelo/<numVuelo>/', editaVuelo, name = "EditaVuelo"),
    path('editarPersonal/<profesionPersonal>/', editarPersonal, name = "EditarPersonal"),
    path('editarPasajero/<idvueloPasajero>/', editarPasajero, name = "EditarPasajero"),

#URL DE ELIMINACION
    path('eliminaVuelo/<numVuelo>/', eliminaVuelo, name = "EliminaVuelo"),
    path('eliminaPersonal/<profesionPersonal>/', eliminaPersonal, name = "EliminaPersonal"),
    path('eliminaPasajero/<idvueloPasajero>/', eliminaPasajero, name = "EliminaPasajero"),

#URL DE BUSQUEDAS
    path('bus/', bus, name="Buscar"),
    path('buscarVuelos/', busquedaVuelos, name="Buscar Vuelos"),
    path('buscarPersonal/', busquedaPersonal, name="Buscar Personal"),
    path('buscarPasajero/', busquedaPasajero, name="Buscar Pasajeros"),
##
    path('buscar_pasa/',buscar_pasa),
    path('buscar_per/',buscar_per),
    path('buscar/',buscar),

#URL DE LOGIN Y LOGOUT
    path('login/',InicioSesion, name="Login"),
    path('registro/',registro, name="Registrarse"),
    path('logout/', LogoutView.as_view(template_name="app_feria/logout.html"), name="Logout"),

#URL DE EDICIONUSUARIO
    path('editUser/',editarUsuario, name="Editar Usuario"),
    path('avatar/', agregarAvatar, name="Avatar"),

    ]

"""

urlpatterns = [
    path('', inicio, name="Inicio"),
    path('editar_registro/', editar_registro, name="Editarosalir"),
    path('registro_inicio/', registro_inicio, name="Iniciar_o_registrar"),
    path('sobrenostros/', sobrenosotros, name="Sobrenosotros"),

    path('jean_detail/<int:codigo>/', views.jean_detail, name="Detalle"),
    path('remera_detail/<int:codigo>/', views.remera_detail, name="Detalle_remera"),
    path('camisa_detail/<int:codigo>/', views.camisa_detail, name="Detalle_camisa"),
    path('calzado_detail/<int:codigo>/', views.calzado_detail, name="Detalle_calzado"),
    path('todo100_detail/<int:codigo>/', views.todo100_detail, name="Detalle_todo100"),
    path('invernal_detail/<int:codigo>/', views.invernal_detail, name="Detalle_invernal"),
    path('pantalon_detail/<int:codigo>/', views.pantalon_detail, name="Detalle_pantalon"),
    path('campera_detail/<int:codigo>/', views.campera_detail, name="Detalle_campera"),

#URL DE CREACION
    path('formulario1/', formulariojean, name="Crear Jeans"),
    path('formulario2/', formularioremera, name="Crear Remera"),
    path('formulario3/', formulariocamisa, name="Crear Camisa"),
    path('formulario4/', formulariotodo, name="Crear todo por 100"),
    path('formulario5/', formulariocalzado, name="Crear Calzado"),
    path('formulario6/', formularioinvernal, name="Crear Invernal"),
    path('formulario7/', formulariopantalon, name="Crear Pantalon"),
    path('formulario8/', formulariocampera, name="Crear Campera"),

#URL DE LEER
    path('leerJeans',leerJeans, name="Leer Jeans"),
    path('leerRemera/',leerRemera, name="Leer Remera"),
    path('leerCamisas/',leerCamisa, name="Leer Camisas"),
    path('leerTodo100/',leerTodo, name="Leer todo por 100"),
    path('leerCalzado/',leerCalzado, name="Leer Calzado"),
    path('leerInvernal/',leerInvernal, name="Leer Invernal"),
    path('leerPantalon/',leerPantalon, name="Leer Pantalon"),
    path('leerCampera',leerCampera, name="Leer Campera"),

#URL DE EDICION
    path('editaJean/<numJean>/', editaJean, name = "EditaJean"),
    path('editarRemera/<generoRemera>/', editarRemera, name = "EditarRemera"),
    path('editarCamisa/<generoCamisa>/', editarCamisa, name = "EditarCamisa"),
    path('editarTodo/<generoTodo>/', editarTodo, name = "Editar todo por 100"),
    path('editarCalzado/<generoCalzado>/', editarCalzado, name = "EditarCalzado"),
    path('editarInvernal/<generoInvernal>/', editarInvernal, name = "EditarInvernal"),
    path('editarPantalon/<generoPantalon>/', editarPantalon, name = "EditarPantalon"),
    path('editarCampera/<generoCampera>/', editarCampera, name = "EditarCampera"),

#URL DE ELIMINACION
    path('eliminaJean/<numJean>/', eliminaJean, name = "EliminaJean"),
    path('eliminaRemera/<generoRemera>/', eliminaRemera, name = "EliminaRemera"),
    path('eliminaCamisa/<generoCamisa>/', eliminaCamisa, name = "EliminaCamisa"),
    path('eliminaTodo/<generoTodo>/', eliminaTodo, name = "Elimina todo por 100"),
    path('eliminaCalzado/<generoCalzado>/', eliminaCalzado, name = "EliminaCalzado"),
    path('eliminaInvernal/<generoInvernal>/', eliminaInvernal, name = "EliminaInvernal"),
    path('eliminaPantalon/<generoPantalon>/', eliminaPantalon, name = "EliminaPantalon"),
    path('eliminaCampera/<generoCampera>/', eliminaCampera, name = "EliminaCampera"),

#URL DE BUSQUEDAS
    path('bus/', bus, name="Buscar"),
    path('buscarJeans/', busquedaJeans, name="Buscar Jeans"),
    path('buscarRemera/', busquedaRemera, name="Buscar Remera"),
    path('buscarCamisa/', busquedaCamisa, name="Buscar Camisa"),
    path('buscarCalzado/', busquedaCalzado, name="Buscar Calzado"),
    path('buscarInvernal/', busquedaInvernal, name="Buscar Invernal"),
    path('buscarPantalon/', busquedaPantalon, name="Buscar Pantalon"),
    path('buscarCampera/', busquedaCampera, name="Buscar Campera"),

##
    path('buscar_campe/',buscar_campe),
    path('buscar_panta/',buscar_panta),
    path('buscar_inve/',buscar_inve),
    path('buscar_calza/',buscar_calza),
    path('buscar_cami/',buscar_cami),
    path('buscar_rem/',buscar_rem),
    path('buscar/',buscar),

#URL DE LOGIN Y LOGOUT
    path('login/',InicioSesion, name="Login"),
    path('registro/',registro, name="Registrarse"),
    path('logout/', LogoutView.as_view(template_name="app_feria/logout.html"), name="Logout"),

#URL DE EDICIONUSUARIO
    path('editUser/',editarUsuario, name="Editar Usuario"),

    ]

"""

About

"""


def isqrt(a):
    x = a
    while True:
        x1 = (x * x + a) // (2 * x)
        if x1 >= x: return x
        x = x1

print(isqrt(16))  # есть целочисленный корень
print(isqrt(17))  # нет целочисленного корня

print(isqrt(16.))  # есть целочисленный корень - вернется  число типа float
print(isqrt(17.))  # нет целочисленного корня - вернется  число типа float


'''
Created on 17/feb/2014
@author: Fabio
'''
class bicicletta:
    ruote = 2

    def __init__(self,colore,taglia,paccoPignoni,moltipliche):
        self.colore=colore
        self.taglia=taglia
        self.paccoPignoni=paccoPignoni
        self.moltipliche=moltipliche


import csv
import datetime

FILE_NAME_READ = "Before Eod.csv"
FILE_NAME_WRITE = "After Eod.csv"
FIELDS_NAME = [
    "id",
    "Nama",
    "Age",
    "Balanced",
    "No 2b Thread-No",
    "No 3 Thread-No",
    "Previous Balanced",
    "Average Balanced",
    "No 1 Thread-No",
    "Free Transfer",
    "No 2a Thread-No",
]

# This will handle question no 1.
def rataanBalance(currentBalance, previousBalance):
    return (currentBalance + previousBalance) / 2

# This will handle question no 3.
def additionalBalanceToTop100(users):
    for user in users[:100]:
        currentBalance = user[FIELDS_NAME[3]]
        user[FIELDS_NAME[3]] = currentBalance + 10

def getDataFromCSV(filename):
    print(f"Start Read Data From {FILE_NAME_READ} at {datetime.datetime.now()}")
    users = []
    with open(filename, 'r') as csv_file:
        dataFromCSV = csv.DictReader(csv_file, delimiter=';')
        for row in dataFromCSV:
            balance = int(row['Balanced'])
            prevBalance = int(row['Previous Balanced'])
            freeTransfer = int(row['Free Transfer'])
            users.append(
                {
                    FIELDS_NAME[0]: row[FIELDS_NAME[0]],
                    FIELDS_NAME[1]: row[FIELDS_NAME[1]],
                    FIELDS_NAME[2]: row[FIELDS_NAME[2]],
                    FIELDS_NAME[3]: 25 + balance if balance > 150 else balance,
                    FIELDS_NAME[4]: '',
                    FIELDS_NAME[5]: '',
                    FIELDS_NAME[6]: prevBalance,
                    FIELDS_NAME[7]: rataanBalance(balance, prevBalance),
                    FIELDS_NAME[8]: '',
                    FIELDS_NAME[9]: 5 + freeTransfer if 100 <= balance <= 150 else freeTransfer,
                    FIELDS_NAME[10]: '',
                }
            )
        additionalBalanceToTop100(users)
    print(f"Finish Read Data from {FILE_NAME_READ} at {datetime.datetime.now()}")
    return users

def writeDataToCSV(filename, users):
    print(f"Start Write Data to {FILE_NAME_WRITE} at {datetime.datetime.now()}")
    with open(filename, 'w') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=FIELDS_NAME)
        writer.writeheader()
        writer.writerows(users)
    print(f"Finish Write Data to {FILE_NAME_WRITE} at {datetime.datetime.now()}")

if __name__ == '__main__':
    users = getDataFromCSV(FILE_NAME_READ)
    writeDataToCSV(FILE_NAME_WRITE, users)


import dice

from timmy.command_processors.base_command import BaseCommand
from timmy.data.command_data import CommandData

class DiceCommand(BaseCommand):
    user_commands = ['roll']
    interaction_checks = False

    help_topics = [('user', 'amusement commands', '!roll <dice string>', 'Generates a random number, as if rolling '
                                                                         'the specified dice. Example: !roll 2d6')]

    def process(self, command_data: CommandData) -> None:
        if self._execution_checks(command_data):
            if command_data.arg_count > 0:
                dice_string: str = command_data.arg_string

                try:
                    dice_result = dice.roll(dice_string)

                    try:
                        dice_total = sum(dice_result)

                        if len(dice_result) <= 20:
                            detailed_dice = dice.utilities.verbose_print(dice_result)
                        else:
                            detailed_dice = "[ too many dice ]"
                    except TypeError:
                        dice_total = dice_result
                        detailed_dice = "[ no detailed dice ]"

                    self.respond_to_user(command_data, f"Your result was {dice_total}. {detailed_dice}")
                except dice.DiceBaseException as e:
                    self.respond_to_user(command_data, e.pretty_print())
            else:
                self.respond_to_user(command_data, "Usage: !roll <dice string>")
                self.respond_to_user(command_data, "Example: !roll 2d6")


# 틀린 테스트케이스를 찾아라.(Find wrong testcase)
# 코드업에서 자신이 만든 문제를 풀던 광곽이는 자신이 만들었던 문제의 테스트케이스
# 가 틀렸음을 알아냈다! 광곽이는 어쩔줄 몰라서 admin에게 사과를 하고, 다시 코드업
# 문제 만들기에 도입했다. 하지만, 광곽이는 이번에도 admin에게 틀린 테스트케이스를
# 주고 말았고, admin은 광곽이에게 문제를 만드는 권한을 없애버렸다. 그에 광곽이는
# 다시는 그러지 않겠다고 다짐하고 테스트케이스에 오류가 있는지 확인하는 프로그램을
# 만들기로 했다. 광곽이가 만든 프로그램은 세 정수를 입력하면 세 정수 중에 가장
# 작은 값을 출력하는 프로그램이다.
# 첫 번째 줄에 테스트케이스의 갯수 n이 입력된다.
# 그 다음 1 .. n줄까지 input 데이터 3개, 테스트 케이스의 output이 공백으로
# 분리되어 입력된다.
# 테스트케이스가 틀렸으면, 테스트케이스의 번호와 정답을 출력한다.
# 틀린 테스트케이스가 없으면 -1을 출력한다.
# 틀린 테스트케이스가 2개 이상이면, 가장 먼저 나온 틀린 테스트케이스의 경우로
# 출력한다.
# method 1
n = int(input())
d = []
cnt = 0
idx = []
ans = []
for i in range(n):
    d.append(list(map(int, input().split())))
    min = d[i][0]
    for j in range(1, len(d[i])-1):
        if min > d[i][j]:
            min = d[i][j]
    if min != d[i][len(d[i])-1]:
        idx.append(i+1)
        ans.append(min)
        cnt += 1
if cnt == 0:
    print(-1)
elif cnt >= 1:
    print(idx[0], ans[0])

CodeUp/I_O statements and operators/1720.py


from selenium import webdriver
from selenium.webdriver.common.by import By
from web_test_base import WebTestBase
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

class TestOrder(WebTestBase):

    def test_valid_zipcode_works(self):
        driver = self.driver
        driver.get(self.WEBSITE_URL)

        zipcode_field = driver.find_element(By.CLASS_NAME, "zipcode-field")

        input_element = zipcode_field.find_element(By.ID, "order-form")
        confirm_button = driver.find_element(By.CLASS_NAME, "order-confirm-button")

        input_element.send_keys("98139")
        confirm_button.click()

        self.assertIn("Vi levererar till dig", driver.page_source)

    def test_invalid_zipcode_works(self):
        driver = self.driver
        driver.get(self.WEBSITE_URL)

        zipcode_field = driver.find_element(By.CLASS_NAME, "zipcode-field")

        input_element = zipcode_field.find_element(By.ID, "order-form")
        confirm_button = driver.find_element(By.CLASS_NAME, "order-confirm-button")

        input_element.send_keys("123456")
        confirm_button.click()

        self.assertIn("Tyvärr kör vi inte ut inom detta område", driver.page_source)

    def test_keyshortcuts_works(self):
        driver = self.driver
        driver.get(self.WEBSITE_URL)

        zipcode_field = driver.find_element(By.CLASS_NAME, "zipcode-field")

        input_element = zipcode_field.find_element(By.ID, "order-form")
        input_element.send_keys("98139")
        input_element.send_keys(Keys.RETURN)

        self.assertIn("Vi levererar till dig", driver.page_source)


import socket
from socket import setdefaulttimeout
import ipaddress
import itertools
import json
from multiprocessing.pool import ThreadPool
import subprocess
import argparse
import base64
import os

class IPScan():
    def __init__(self):
        setdefaulttimeout(0.10)
        self.open_ports = []
        self.ports = list(range(0,1000))

    def scan_ips(self, start_ip, end_ip):
        start_ip = ipaddress.IPv4Address(start_ip)
        end_ip = ipaddress.IPv4Address(end_ip)
        results = []
        for ip in range(int(start_ip), int(end_ip)):
            results.append(self.host(ipaddress.IPv4Address(ip)))
        return results
    def network_scan(self, network_expression):
        results = []
        for ip in ipaddress.IPv4Network(network_expression):
            ip = str(ip)
            results.append(self.host(ip))
        return results

    def port_check(self, ip, port):
        try:
            sock = socket.socket()
            sock.settimeout(0.10)
            result = sock.connect_ex((ip, port))
            try:
                if result == 0:
                    self.open_ports.append("port {0}: open".format(str(port)))
                else:
                    self.open_ports.append("port {0}: closed".format(str(port)))
            except Exception as e:
                self.open_ports.append("port {0} conn fail: {1}".format(str(port), e))
            finally:
                sock.close()
        except:
            self.open_ports.append("networking failed for port {0} : {1}".format(str(port), e))

    def scan_host(self, ip):
        _host_temp = str(ip)
        returns = {}
        returns['_hostname'] = socket.getfqdn(_host_temp)
        returns['ipAddress'] = _host_temp
        self.threads = []
        pool = ThreadPool(10)
        results = pool.starmap(self.port_check, zip(itertools.repeat(_host_temp), self.ports))
        pool.close()
        pool.join()
        self.open_ports.sort()
        returns['openPorts'] = self.open_ports
        return returns

    def set_ports(self, ports):
        self.ports = ports
        return None


import spacy
import json
nlp = spacy.load('en')
json_data = open('Book_Data_Set.json',encoding="utf8")
data = json.load(json_data)
title = ""
for i in range (0, 10):
	doc = nlp(data[i]['description'])
	for np in doc:
		if np.pos_ == "NOUN" or np.pos_ == "PROPN":
			print (np.text,end='****')
	print()


def safe_pawns(pawns: set) -> int:
    chpawns = set()
    chpawns1 = set()
    chpawns2 = set()
    for i in pawns:
        x = ord(i[0])
        y = ord(i[1])
        chpawns.add(str(x)+str(y))
        chpawns1.add(str(x-1)+str(y+1))
        chpawns2.add(str(x+1) + str(y+1))
    return len(chpawns & chpawns1 | chpawns & chpawns2)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
    assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")


from django.conf.urls import url

from .views import (
    get_articles_list,
    home,
    search_articles,
)

urlpatterns = [
    # url(r'^create$', collection_create, name="create"),
    # url(r'^(?P<slug>[\w-]+)/add$', link_add, name='add'),
    # url(r'^(?P<slug>[\w-]+)(?:/(?P<tag>[\w-]+))?/$', collection_detail, name='detail'),
    # url(r'^(?P<slug>[\w-]+)/search$', search_link, name="search_link"),
    # url(r'^(?P<slug>[\w-]+)/edit$', collection_update, name='update'),
    # url(r'^(?P<slug>[\w-]+)/delete$', collection_delete, name='delete'),
    url(r'^$', home, name='home'),
    url(r'^api/v1/get-articles-list$', get_articles_list, name='get_articles_list'),
    url(r'^api/v1/search-articles$', search_articles, name='search_articles'),
    # url(r'^about$', about, name='about'),
    # url(r'^link/(?P<id>\d+)/delete$', link_delete, name='link_delete' ),
    # url(r'^(?P<slug>[\w-]+)/delete$', collection_delete, name='collection_delete'),
    # url(r'^link/(?P<id>\d+)/edit$', link_edit, name='link_edit' ),
]


from datetime import timedelta
from random import randint, choices

import faker_commerce
from django.core.management.base import BaseCommand
from django_seed import Seed
from faker import Faker

from catalog.models import Category, Discount, Producer, Promocode, Product

class Command(BaseCommand):
    help = "Filling database"
    __DEFAULT_COUNT_PRODUCERS = 200
    __DEFAULT_COUNT_CATEGORIES = 75
    __DEFAULT_COUNT_PRODUCTS = 2000
    __DEFAULT_COUNT_PROMOCODES = 250
    __DEFAULT_COUNT_DISCOUNTS = 20

    def __init__(self, *args, **kwargs):
        self.seeder = Seed.seeder()
        self.fake = Faker()
        self.fake.add_provider(faker_commerce.Provider)
        super().__init__(*args, **kwargs)

    def handle(self, *args, **options):
        self.__create_producers()
        self.__create_categories()
        self.__create_discounts()
        self.__create_promocodes()
        self.__create_products()
        return "Fake data is created"

    def __create_producers(self):
        self.seeder.add_entity(
            model=Producer,
            number=self.__DEFAULT_COUNT_PRODUCERS,
            customFieldFormatters={
                "name": lambda x: self.fake.company(),
                "description": lambda x: self.fake.paragraph(nb_sentences=3),
                "country": lambda x: self.fake.country(),
            },
        )
        self.seeder.execute()

    def __create_categories(self):
        self.seeder.add_entity(
            model=Category,
            number=self.__DEFAULT_COUNT_CATEGORIES,
            customFieldFormatters={
                "name": lambda x: self.fake.ecommerce_category(),
                "description": lambda x: self.fake.paragraph(nb_sentences=2),
            },
        )
        self.seeder.execute()

    def __create_discounts(self):
        self.seeder.add_entity(
            model=Discount,
            number=self.__DEFAULT_COUNT_DISCOUNTS,
            customFieldFormatters={
                "percent": lambda x: randint(1, 50),
                "name": lambda x: self.fake.sentence(nb_words=1)[:-1],
                "date_start": lambda x: self.fake.date_this_month(),
                "date_end": lambda x: self.fake.date_this_month()
                + timedelta(days=randint(5, 100)),
            },
        )
        self.seeder.execute()

    def __create_promocodes(self):
        self.seeder.add_entity(
            model=Promocode,
            number=self.__DEFAULT_COUNT_PROMOCODES,
            customFieldFormatters={
                "name": lambda x: self.fake.swift(length=8),
                "percent": lambda x: randint(1, 50),
                "date_start": lambda x: self.fake.date_this_month(),
                "date_end": lambda x: self.fake.date_this_month()
                + timedelta(days=randint(20, 200)),
                "is_cumulative": lambda x: self.fake.pybool(),
            },
        )
        self.seeder.execute()

    def __create_products(self):
        discounts = Discount.objects.all()
        categories = Category.objects.all()
        producers = Producer.objects.all()
        self.seeder.add_entity(
            model=Product,
            number=self.__DEFAULT_COUNT_PRODUCTS,
            customFieldFormatters={
                "name": lambda x: self.fake.ecommerce_name(),
                "price": lambda x: self.fake.ecommerce_price(),
                "count_on_stock": lambda x: randint(100, 10000),
                "articul": lambda x: self.fake.isbn10(),
                "description": lambda x: self.fake.paragraph(nb_sentences=2),
                "discount": lambda x: choices(discounts)[0],
                "category": lambda x: choices(categories)[0],
                "producer": lambda x: choices(producers)[0],
            },
        )
        self.seeder.execute()


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

'''
本文档用于对下载回来的图片文件夹内其中文件进行整理
作者：吴厚波
创建时间：2018-5-19
更新时间：2018-5-21 15:34:35
'''

import shutil, os
import re

base_path = 'H:\开车\Cosplay&写真\少女映画\\'
re_video = re.compile(r'mp4|mkv|avi|rmvb|MTS|flv')
re_nochange_name = re.compile(r'IMG|DSC')
dirs = []
for name in os.listdir(base_path):
    if os.path.isdir(base_path + name):
        dirs.append(name)

for x in dirs:
    new_name = re.sub(r'[[(（【](.+?)[])）】]', '', x).strip()
    old_dir = base_path + x
    old_names = [y for y in os.listdir(old_dir)]
    num = len(old_names)
    video_num = 0
    is_has_video = False
    for y in old_names:
        if re_video.search(y):
            video_num += 1
    if video_num > 0:
        if video_num<num:
            new_name = new_name + ' ({}P+{}V)'.format(num - video_num, video_num)
        else:
            new_name = new_name + ' ({}V)'.format(video_num)
    else:
        new_name = new_name + ' ({}P)'.format(num)
    print('原文件夹名：{}\t新文件夹名：{}'.format(x, new_name))
    new_dir = base_path + new_name
    if not os.path.exists(new_dir):
        os.mkdir(new_dir)
    old_dir += '\\'
    new_dir += '\\'
    zero_add = 10
    if num >= 100:
        zero_add = 100
    i = 1
    for y in os.listdir(old_dir):
        (shot_name, extension) = os.path.splitext(y)
        if re_video.search(extension):
            shutil.move(old_dir + y, new_dir + y)
            continue
        new_filename = ''
        if re_nochange_name.search(shot_name):
            if i < zero_add:
                if zero_add == 10:
                    new_filename = '0{}{}'.format(i, extension)
                else:
                    new_filename = '00{}{}'.format(i, extension)
            else:
                new_filename = '{}{}'.format(i, extension)
        else:
            new_filename = y
        print('原文件名：{}\\{}\t新文件名：{}\\{}'.format(x, y, new_name, new_filename))
        shutil.move(old_dir + y, new_dir + new_filename)
        i += 1
    try:
        os.rmdir(old_dir)
    except Exception as ex:
        print("文件夹名不变")  # 提示：错误信息，目录不是空的
print('整理完毕！')


# version code 761
# Please fill out this stencil and submit using the provided submission script.

from vec import Vec
from GF2 import one

## Problem 1
def vec_select(veclist, k):
    '''
    >>> D = {'a','b','c'}
    >>> v1 = Vec(D, {'a': 1})
    >>> v2 = Vec(D, {'a': 0, 'b': 1})
    >>> v3 = Vec(D, {        'b': 2})
    >>> v4 = Vec(D, {'a': 10, 'b': 10})
    >>> vec_select([v1, v2, v3, v4], 'a') == [Vec(D,{'b': 1}), Vec(D,{'b': 2})]
    True
    '''
    return [v for v in veclist if k not in v.f or v.f[k] is 0]

def vec_sum(veclist, D):
    '''
    >>> D = {'a','b','c'}
    >>> v1 = Vec(D, {'a': 1})
    >>> v2 = Vec(D, {'a': 0, 'b': 1})
    >>> v3 = Vec(D, {        'b': 2})
    >>> v4 = Vec(D, {'a': 10, 'b': 10})
    >>> vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 11})
    True
    '''
    dic = dict()
    for k in D:
        key_sum = sum([v.f[k] if k in v.f else 0 for v in veclist])
        if key_sum is not 0:
            dic[k] = key_sum
    return Vec(D, dic)

def vec_select_sum(veclist, k, D):
    '''
    >>> D = {'a','b','c'}
    >>> v1 = Vec(D, {'a': 1})
    >>> v2 = Vec(D, {'a': 0, 'b': 1})
    >>> v3 = Vec(D, {        'b': 2})
    >>> v4 = Vec(D, {'a': 10, 'b': 10})
    >>> vec_select_sum([v1, v2, v3, v4], 'a', D) == Vec(D, {'b': 3})
    True
    '''
    return vec_sum(vec_select(veclist, k), D)

## Problem 2
def scale_vecs(vecdict):
    '''
    >>> v1 = Vec({1,2,3}, {2: 9})
    >>> v2 = Vec({1,2,4}, {1: 1, 2: 2, 4: 8})
    >>> scale_vecs({3: v1, 5: v2}) == [Vec({1,2,3},{2: 3.0}), Vec({1,2,4},{1: 0.2, 2: 0.4, 4: 1.6})]
    True
    '''
    return [Vec(vecdict[m].D, {k:vecdict[m].f[k]/m for k in vecdict[m].f.keys()}) for m in vecdict.keys()]

def scale_up_vecs(vecdict):
    '''
    >>> v1 = Vec({1,2,3}, {2: 9})
    >>> v2 = Vec({1,2,4}, {1: 1, 2: 2, 4: 8})
    >>> scale_vecs({3: v1, 5: v2}) == [Vec({1,2,3},{2: 27}), Vec({1,2,4},{1: 5, 2: 10, 4: 40})]
    True
    '''
    return [Vec(vecdict[m].D, {k:vecdict[m].f[k]*m for k in vecdict[m].f.keys()}) for m in vecdict.keys()]

## Problem 3
def GF2_span(D, L):
    '''
    >>> from GF2 import one
    >>> D = {'a', 'b', 'c'}
    >>> L = [Vec(D, {'a': one, 'c': one}), Vec(D, {'b': one})]
    >>> len(GF2_span(D, L))
    4
    >>> Vec(D, {}) in GF2_span(D, L)
    True
    >>> Vec(D, {'b': one}) in GF2_span(D, L)
    True
    >>> Vec(D, {'a':one, 'c':one}) in GF2_span(D, L)
    True
    >>> Vec(D, {x:one for x in D}) in GF2_span(D, L)
    True
    '''
    gf2_opt = gen_GF2(len(L))
    arr = list()
    for x in gf2_opt:
        sub_arr = list()
        for y in range(len(x)):
            sub_arr.append(scale_up_vecs({ x[y]:L[y] })[0])
        arr.append(vec_sum(sub_arr, D))
    return arr

def gen_GF2(length, lists=[]):
    if len(lists) is 0:
        lists = [[]]

    for i in range(len(lists)):
        l = lists[i][:]
        lists[i].append(0)
        l.append(one)
        lists.append(l)

    if len(lists[0]) is length:
        return lists
    else:
        return gen_GF2(length, lists)

## Problem 4
# Answer with a boolean, please.

is_it_a_vector_space_1 = True
is_it_a_vector_space_2 = False

## Problem 5
is_it_a_vector_space_3 = True
is_it_a_vector_space_4 = False

## Problem 6

is_it_a_vector_space_5 = True
is_it_a_vector_space_6 = False


class PlayFairCipher:
    def __init__(self, key):
        self.key = key
        self.letter2index = self.get_letter_2_index_map()

    def get_letter_2_index_map(self):
        index_map = {}
        for row in range(len(self.key)):
            for column in range(len(self.key[row])):
                letter = self.key[row][column].lower()
                if letter == 'i':
                    index_map['j'] = (row, column)
                index_map[letter] = (row, column)
        return index_map

    def encrypt(self, plaintext):
        plaintext = self.pad_extra(self.remove_consecutive_same_chars(plaintext.lower()))
        # print('plaintext:', plaintext)
        ciphertext = ''
        for index in range(0, len(plaintext), 2):
            pair = plaintext[index: index + 2]
            ciphertext += self.encipher(pair)
        return ciphertext.upper()

    def decrypt(self, ciphertext):
        plaintext = ''
        for index in range(0, len(ciphertext), 2):
            pair = ciphertext[index: index + 2].lower()
            plaintext += self.decipher(pair)
        return plaintext

    def decipher(self, pair):
        row1, column1 = self.letter2index[pair[0]]
        row2, column2 = self.letter2index[pair[1]]
        if row1 == row2:
            return self.key[row1][(column1 - 1) % 5] + self.key[row1][(column2 - 1) % 5]
        elif column1 == column2:
            return self.key[(row1 - 1) % 5][column1] + self.key[(row2 - 1) % 5][column2]
        return self.key[row1][column2] + self.key[row2][column1]

    def encipher(self, pair):
        row1, column1 = self.letter2index[pair[0]]
        row2, column2 = self.letter2index[pair[1]]
        if row1 == row2:
            return self.key[row1][(column1 + 1) % 5] + self.key[row1][(column2 + 1) % 5]
        elif column1 == column2:
            return self.key[(row1 + 1) % 5][column1] + self.key[(row2 + 1) % 5][column2]
        return self.key[row1][column2] + self.key[row2][column1]

    @staticmethod
    def pad_extra(plaintext):
        return plaintext + PlayFairCipher.middle_character(plaintext[len(plaintext) - 1]) \
            if len(plaintext) % 2 == 1 else plaintext

    @staticmethod
    def remove_consecutive_same_chars(plaintext):
        for index in range(len(plaintext) - 1):
            if plaintext[index] == plaintext[index + 1]:
                plaintext = plaintext[: index + 1] + PlayFairCipher.middle_character(plaintext[index]) + plaintext[index + 1:]
        return plaintext

    @staticmethod
    def middle_character(letter):
        # return chr((ord(letter) - ord('a') + 1) % 26 + ord('a'))
        return 'x'


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

from odoo import models, fields, api

class Parnter(models.Model):
    _inherit = 'res.partner'

    #odoo通过child_ids，来为当前联系人关联子联系人，地址等。
    #odoo中，多个联系人和多个联系地址都是通过child_ids来实现的。修改为：多对多的联系人，用独立的many_child_ids来实现。原来的child_ids用来保存多个地址（界面中屏蔽添加联系人）
    many_child_ids = fields.Many2many('res.partner', 'res_partner_many_child_ids_rel', 'partner_id', 'many_partner_id', string="联系人", help="通用的对多对关系,用来实现联系人的子联系人,客户下的联系人.")

    support_many_child_ids = fields.Boolean('是否支持多对多联系人', compute='_compute_support_many_child_ids')

    contact_relation_contact_ids = fields.One2many('anodoo.contact.relation.contact', 'contact_id', string='相关联系人')

    #个人客户或个人联系人的信息扩展
    birth_date = fields.Date(string="出生日期")
    gender_type = fields.Selection(
        [('man', '男'),
         ('woman', '女'),
         ('unknown', '未知'),
        ], string='性别', default='unknown')

    #重写父类，名称还是使用本身的名称
    def _get_name(self):
        return self.name

    def _compute_support_many_child_ids(self):
        ConfigParameter = self.env['ir.config_parameter'].sudo()
        support = ConfigParameter.get_param('anodoo_contacts.support_many_child_ids', False)

        for contact in self:
            contact.support_many_child_ids = support


import colors as c
from utils import ask

intro = c.orange + '''
Welcome to the orange quiz game!!!!!!
'''  + c.reset

def q1():
    color = ask(c.yellow + 'What is the color of an orange?' + c.reset)
    if color == 'orange':
        return True
    print(c.red + 'You have failed' + c.reset)
    return False

def q2():
    peel = ask(c.green + 'What is the correct way to eat an orange?' + c.reset)
    if peel.startswith("peel"):
        return True
    print(c.red + "You have failed" + c.reset)
    return False

def q3():
    type = ask(c.blue + 'Am I refferring to the fruit or color?' + c.reset)
    if type == ("fruit"):
        return True
    print (c.red + 'You have failed' + c.reset)
    return False
questions = [q1,q2,q3]


# https://www.acmicpc.net/problem/1157
import sys

def get_maximum_freq_alphabet(w):
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    dic = {a: 0 for a in alpha}

    for c in w.upper():
        dic[c] += 1

    maxs = []
    max_num = -1

    for c in dic:
        if dic[c] > max_num:
            max_num = dic[c]
            maxs = [c]
        elif dic[c] == max_num:
            maxs.append(c)

    if len(maxs) == 1:
        return maxs[0]
    return "?"

if __name__ == "__main__":
    print(get_maximum_freq_alphabet(sys.stdin.readline().strip()))


class Solution(object):
    def scheduleCourse(self, courses):
        """
        :type courses: List[List[int]]
        :rtype: int
        """
        courses.sort(key = lambda x : x[1])
        hq = []
        day = 0
        res = 0
        for dur, ddl in courses:
            heapq.heappush(hq, -dur)
            day += dur
            res += 1
            if day > ddl:
                day += heapq.heappop(hq)
                res -= 1
        return res


# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_submodules

hiddenimports = ['scipy.spatial.transform._rotation_groups', 'sqlalchemy.sql.default_comparator', 'sklearn.metrics._pairwise_distances_reduction._datasets_pair', 'sklearn.neighbors._partition_nodes', 'sklearn.metrics._pairwise_distances_reduction._datasets_pair', 'cmath']
hiddenimports += collect_submodules('sklearn.utils')

block_cipher = None

a = Analysis(
    ['run.py'],
    pathex=['/opt/homebrew/Caskroom/miniforge/base/envs/scope2screen2'],
    binaries=[],
    datas=[('minerva_analysis/client', 'minerva_analysis/client'), ('minerva_analysis/__init__.py', 'minerva_analysis/'), ('minerva_analysis/server', 'minerva_analysis/server'), ('/opt/homebrew/Caskroom/miniforge/base/envs/scope2screen2/lib/python3.8/site-packages/xmlschema/schemas', 'xmlschema/schemas')],
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='scope2screen_mac',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)


#defino librerias
import csv
import datetime as ti
#constantes y variables
opciones="""
Bienvenido
__________________________
seleccione una opcion
1.Ingresar datos

2.salir

"""

runTime=True
datetime = ti.date.today()
#funciones
"""Recive el nombre del archivo atraves de un input de usuario y si el archivo existe convierte los datos a valores dentro
de un diccionario donde definimos las claves.
"""
def readFile(urlfile):
    cheques=[]
    file=open(urlfile+".csv","r")
    csvfile=csv.reader(file)
    for row in csvfile:
        if row != []:
            data = {"Nrocheque":row[0],"codigoBanco":row[1],
            "codigoSucursal":row[2],"ctaOrigen":row[3],"ctaDestino":row[4],
            "valor":row[5],"fechaOrigen":row[6],"fechaPago":row[7],"DNI":row[8],"tipo":row[9],"estado":row[10],}
            cheques.append(data)
    file.close
    return cheques

"""Funcion hecha para devolver los datos requeridos por el usuario, que son filtrados por el dni y el tipo de cheque
solicitado a traves de un input que son verificados en torno a las claves y valores del diccionario realizado en la funcion anterior"""
def buscarDni(dni, tipo):
    busqueda=[]
    cantidad = 0
    cheques = readFile(urlfile)
    for cheque in cheques:
        if cheque["DNI"]==dni and cheque["tipo"]==tipo:
            cantidad += 1
            print("cheque encontrado\n")
            busqueda.append(cheque)
    repetidos = []
    for i in busqueda:

        repetidos = map(lambda x:x["Nrocheque"], busqueda)
        if i["Nrocheque"] in busqueda:
            repetidos.append(i["Nrocheque"])
    if repetidos !=[]:
        print("Error cheques duplicados")
    else:
        print(f"se encontraron {cantidad} cheques")
        print(busqueda)

def CSVDES(dni, busqueda):
    file = open(dni+"__"+datetime+"csv","w")
    csvfile=csv.writer(file)
    for row in busqueda:
        csvfile.writerow([row["Nrocheque"],row["codigoBanco"],row[
            "codigoSucursal"],row["ctaOrigen"],row["ctaDestino"],row[
            "valor"],row["fechaOrigen"],row["fechaPago"],row["DNI"],row["tipo"],row["estado"]])
    file.close
    print("csv grabado")

#metodo principal

if __name__=="__main__":
    while runTime:
        print(opciones)
        op = input()
        if op == "1":
            urlfile = input("ingrese el nombre del archivo: \n")
            dni = input("ingrese el DNI del usuario a consultar: \n")
            tipo = input("tipo de cheque a buscar EMITIDO o DEPOSITADO: \n")
            salida = input("desea la salida por pantalla o csv: \n")
            print(urlfile,dni,tipo,salida)
            try:
                resultado = buscarDni(dni, tipo)
                if salida =="PANTALLA":
                    print(resultado)
                elif salida == "CSV":
                    CSVDES(resultado)
                else:
                    print("invalido")
            except:
                print("invalido")

        elif op =="2":
            runTime = False
        else:
            runTime = False


'''
Given an integer x, return true if x is a
palindrome, and false otherwise.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
'''
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """

        x = [x for x in str(x)]

        b = [x[i] for i in range(len(x)-1, -1, -1)]

        if x == b:
            return True
        else:
            return False


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

import requests
from bs4 import BeautifulSoup as bs

def get_historical_data(name, number_of_days):
    data = []
    url = "https://finance.yahoo.com/quote/" + name + "/history/"
    content = requests.get(url).content
    rows = bs(content, 'html.parser').findAll('table')[0].tbody.findAll('tr')

    for each_row in rows:
        divs = each_row.findAll('td')
        if divs[1].span.text != 'Dividend':
            data.append({'Date': divs[0].span.text, 'Open': float(divs[1].span.text.replace(',', ''))})

    return data[:number_of_days]

if __name__ == '__main__':
    get_historical_data('AAPL', 10)


from functools import cmp_to_key

class Solution:
    def reconstructQueue(self, people: list) -> list:
        people = sorted(people, key=cmp_to_key(self.cmp))
        ans = []

        for p in people:
            ans.insert(p[1], p)

        return ans

    def cmp(self, a: list, b: list):
        if a[0] > b[0]:
            return -1
        elif a[0] < b[0]:
            return 1
        else:
            if a[1] < b[1]:
                return -1
            else:
                return 1

Medium/406. Queue Reconstruction by Height(sort&greedy).py


"""Handles different kind of browser streams."""

import copy
import logging
from typing import Dict

import cv2
import imutils
import tornado.ioloop
import tornado.web
from tornado.queues import Queue

from viseron.config.config_camera import MJPEG_STREAM_SCHEMA
from viseron.const import TOPIC_FRAME_PROCESSED, TOPIC_STATIC_MJPEG_STREAMS
from viseron.data_stream import DataStream
from viseron.helpers import draw_contours, draw_mask, draw_objects, draw_zones
from viseron.nvr import FFMPEGNVR

LOGGER = logging.getLogger(__name__)

class StreamHandler(tornado.web.RequestHandler):
    """Represents a stream."""

    async def process_frame(self, nvr: FFMPEGNVR, frame, mjpeg_stream_config):
        """Return JPG with drawn objects, zones etc."""
        if mjpeg_stream_config["width"] and mjpeg_stream_config["height"]:
            resolution = mjpeg_stream_config["width"], mjpeg_stream_config["height"]
            frame.resize(
                "tornado", mjpeg_stream_config["width"], mjpeg_stream_config["height"]
            )
            # TODO move this to a preprocess
            processed_frame = frame.get_preprocessed_frame(
                "tornado"
            ).get()  # Convert to Mat
        else:
            resolution = nvr.camera.resolution
            processed_frame = frame.decoded_frame_mat_rgb

        if mjpeg_stream_config["draw_motion_mask"] and nvr.config.motion_detection.mask:
            draw_mask(
                processed_frame,
                nvr.config.motion_detection.mask,
            )

        if mjpeg_stream_config["draw_motion"] and frame.motion_contours:
            draw_contours(
                processed_frame,
                frame.motion_contours,
                resolution,
                nvr.config.motion_detection.area,
            )

        if mjpeg_stream_config["draw_zones"]:
            draw_zones(processed_frame, nvr.zones)

        if mjpeg_stream_config["draw_objects"]:
            draw_objects(
                processed_frame,
                frame.objects,
                resolution,
            )

        if mjpeg_stream_config["rotate"]:
            processed_frame = imutils.rotate_bound(
                processed_frame, mjpeg_stream_config["rotate"]
            )

        if mjpeg_stream_config["mirror"]:
            processed_frame = cv2.flip(processed_frame, 1)

        # Write a low quality image to save bandwidth
        ret, jpg = cv2.imencode(
            ".jpg", processed_frame, [int(cv2.IMWRITE_JPEG_QUALITY), 100]
        )

        return ret, jpg

class DynamicStreamHandler(StreamHandler):
    """Represents a dynamic stream using query parameters."""

    async def get(self, camera):
        """Handle a GET request."""
        request_arguments = {k: self.get_argument(k) for k in self.request.arguments}
        LOGGER.debug(request_arguments)
        mjpeg_stream_config = MJPEG_STREAM_SCHEMA(request_arguments)
        LOGGER.debug(mjpeg_stream_config)
        nvr = FFMPEGNVR.nvr_list.get(camera, None)

        if not nvr:
            self.set_status(404)
            self.write(f"Camera {camera} not found.")
            self.finish()
            return

        self.set_header(
            "Content-Type", "multipart/x-mixed-replace;boundary=--jpgboundary"
        )
        self.set_header("Connection", "close")

        frame_queue = Queue(maxsize=10)
        frame_topic = f"{nvr.config.camera.name_slug}/{TOPIC_FRAME_PROCESSED}/*"
        unique_id = DataStream.subscribe_data(frame_topic, frame_queue)
        while True:
            try:
                item = await frame_queue.get()
                frame = copy.copy(item.frame)
                ret, jpg = await self.process_frame(nvr, frame, mjpeg_stream_config)

                if ret:
                    self.write("--jpgboundary")
                    self.write("Content-type: image/jpeg\r\n")
                    self.write("Content-length: %s\r\n\r\n" % len(jpg))
                    self.write(jpg.tobytes())
                    await self.flush()
            except tornado.iostream.StreamClosedError:
                DataStream.unsubscribe_data(frame_topic, unique_id)
                LOGGER.debug(f"Stream closed for camera {nvr.config.camera.name_slug}")
                break

class StaticStreamHandler(StreamHandler):
    """Represents a static stream defined in config.yaml."""

    active_streams: Dict[str, object] = {}

    @tornado.gen.coroutine
    def stream(self, nvr, mjpeg_stream, mjpeg_stream_config, publish_frame_topic):
        """Subscribe to frames, draw on them, then publish processed frame."""
        frame_queue = Queue(maxsize=10)
        subscribe_frame_topic = (
            f"{nvr.config.camera.name_slug}/{TOPIC_FRAME_PROCESSED}/*"
        )
        unique_id = DataStream.subscribe_data(subscribe_frame_topic, frame_queue)

        while self.active_streams[mjpeg_stream]:
            item = yield frame_queue.get()
            frame = copy.copy(item.frame)
            ret, jpg = yield self.process_frame(nvr, frame, mjpeg_stream_config)

            if ret:
                DataStream.publish_data(publish_frame_topic, jpg)

        DataStream.unsubscribe_data(subscribe_frame_topic, unique_id)
        LOGGER.debug(f"Closing stream {mjpeg_stream}")

    async def get(self, camera, mjpeg_stream):
        """Handle GET request."""
        nvr = FFMPEGNVR.nvr_list.get(camera, None)
        if not nvr:
            self.set_status(404)
            self.write(f"Camera {camera} not found.")
            self.finish()
            return

        mjpeg_stream_config = nvr.config.camera.static_mjpeg_streams.get(
            mjpeg_stream, None
        )
        if not mjpeg_stream_config:
            self.set_status(404)
            self.write(f"Stream {mjpeg_stream} not defined.")
            self.finish()
            return

        frame_queue = Queue(maxsize=10)
        frame_topic = (
            f"{TOPIC_STATIC_MJPEG_STREAMS}/{nvr.config.camera.name_slug}/{mjpeg_stream}"
        )
        unique_id = DataStream.subscribe_data(frame_topic, frame_queue)

        if self.active_streams.get(mjpeg_stream, False):
            self.active_streams[mjpeg_stream] += 1
            LOGGER.debug(
                "Stream {mjpeg_stream} already active, number of streams: "
                f"{self.active_streams[mjpeg_stream]}"
            )
        else:
            LOGGER.debug(f"Stream {mjpeg_stream} is not active, starting")
            self.active_streams[mjpeg_stream] = 1
            tornado.ioloop.IOLoop.current().spawn_callback(
                lambda: self.stream(
                    nvr, mjpeg_stream, mjpeg_stream_config, frame_topic
                ),
            )

        self.set_header(
            "Content-Type", "multipart/x-mixed-replace;boundary=--jpgboundary"
        )
        self.set_header("Connection", "close")
        while True:
            try:
                jpg = await frame_queue.get()
                self.write("--jpgboundary")
                self.write("Content-type: image/jpeg\r\n")
                self.write("Content-length: %s\r\n\r\n" % len(jpg))
                self.write(jpg.tobytes())
                await self.flush()
            except tornado.iostream.StreamClosedError:
                DataStream.unsubscribe_data(frame_topic, unique_id)
                LOGGER.debug(
                    f"Stream {mjpeg_stream} closed for camera "
                    f"{nvr.config.camera.name_slug}"
                )
                break
        self.active_streams[mjpeg_stream] -= 1


import torch
from torch.nn import functional as F

def compute_mvg(d_latents, latent_name, mean_v, inv_cov_v):
    if latent_name == "W":
        _w = d_latents["W"]
        _v = F.leaky_relu(_w, negative_slope=5.0)
        dv = (_v - mean_v)
        loss = (dv.matmul(inv_cov_v).matmul(dv.T))
        return loss
    elif latent_name == "W+":
        _wp = d_latents["W+"].double()
        _vp = F.leaky_relu(_wp, negative_slope=5.0)
        loss = 0.0
        for idx in range(_vp.shape[1]):
            _v = _vp[:, idx, :]
            dv = (_v - mean_v)
            loss += (dv@inv_cov_v@dv.T)
        return loss.squeeze(0).squeeze(0)

def b_compute_mvg(d_latents, latent_name, mean_v, inv_cov_v):
    if latent_name == "W+":
        _wp = d_latents["W+"].double()
        _vp = F.leaky_relu(_wp, negative_slope=5.0)
        bs = _wp.shape[0]
        inv_cov_v = inv_cov_v.reshape(1, 512, 512).repeat(bs, 1, 1)
        loss = 0.0
        for idx in range(_vp.shape[1]):
            _v = _vp[:, idx, :]
            dv = (_v - mean_v).reshape(-1, 1, 512)
            loss += torch.bmm(torch.bmm(dv, inv_cov_v), torch.transpose(dv, 1, 2)).mean()
        return loss

def delta_loss(latent):
    loss = 0.0
    first_w = latent[:, 0, :]
    for i in range(1, latent.shape[1]):
        delta = latent[:, i, :] - first_w
        delta_loss = torch.norm(delta, 2, dim=1).mean()
        loss += delta_loss
    return loss


import torch
import pytorch_ssim

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

nc = 3
imsize = 256

def ssim(img, ref,weight_ssim):
    img = img.reshape(1, nc, imsize, imsize)

    img.requires_grad_()

    ssim_value = pytorch_ssim.ssim(ref, img)
    ssim_loss = pytorch_ssim.SSIM()
    ssim_out = -weight_ssim * ssim_loss(ref, img)
    ssim_out.backward()

    #    del ref
    #    torch.cuda.empty_cache()
    return ssim_value, img.grad.flatten()

def ssim_opt(m0, temp, ref,weight_ssim):
    temp = temp.reshape(1, nc, imsize, imsize)

    # _, nc, imsize, imsize = temp.shape
    temp.requires_grad_()

    ssim_value = pytorch_ssim.ssim(ref, temp)
    ssim_loss = pytorch_ssim.SSIM()
    ssim_out = -weight_ssim * ssim_loss(ref, temp)
    comp = ((-weight_ssim * m0) - ssim_out) ** 2
    comp.backward()

    return comp, temp.grad


import stanza
import json,re
# # stanza.download('en')       # This downloads the English models for the neural pipeline
nlp = stanza.Pipeline('en') # This sets up a default neural pipeline in English
field = "yugioh"

f = open(field+"_entitys.json")
field_entitys = json.load(f)
f.close()

max_num = 5000

def exist(text,entitys):
    flag = False
    label_title = None
    match_type = None
    if text in entitys:#exact match
        flag = True
        label_title = text
        match_type = "exact match"
        return flag,label_title,match_type
    return flag,label_title,match_type

src = open("./data/zeshel/documents/"+field+".json")
out_f = open("exact_"+field+"_tmp.jsonl",'w')
cnt = 0
succ_cnt = 0
line = src.readline()
finish_flag = False
while line:
    if finish_flag:
        break
    cnt += 1
    if cnt%100==0:
        print(cnt)
    text = json.loads(line)["text"]
    from_doc = json.loads(line)["title"]
    try:
        doc = nlp(text)
    except:
        line = src.readline()
        continue
    mention_list = []
    entity_list = []
    doc_flag = False
    for sentence in doc.sentences:
        if doc_flag:
            break
        for ent in sentence.ents:
            if doc_flag:
                break
            if ent.text in mention_list:
                continue
            if ent.type == "DATE" or ent.type == "CARDINAL" or ent.type == "ORDINAL":#不要日期
                continue
            flag, label_title,match_type = exist(ent.text.lower(),field_entitys)
            if flag:
                if from_doc.lower() == label_title:
                    continue
                start,end = ent.start_char,ent.end_char
                sample = {}
                sample["context_left"] = text[:start]
                if len(sample["context_left"].split())<64:
                    continue
                sample["context_left"] = " ".join(sample["context_left"].split()[-128:])
                sample["mention"] = ent.text
                sample["context_right"] = text[end:]
                sample["context_right"] = " ".join(sample["context_right"].split()[:128])
                sample["label_title"] = label_title
                sample["world"] = field
                sample["from_doc"] = from_doc
                sample["match_type"] = match_type
                out_f.write(json.dumps(sample)+"\n")
                succ_cnt += 1
                if succ_cnt>=max_num:
                    finish_flag = True
                entity_list.append(label_title)
                mention_list.append(ent.text)
                doc_flag = True
    line = src.readline()
src.close()
out_f.close()

f = open(field+"_entity_index_by_title")
entity_index_by_title = json.load(f)
f.close()

out_f = open("exact_"+field+".jsonl",'w')
f = open("exact_"+field+"_tmp.jsonl")
line = f.readline()
while line:
    line = json.loads(line)
    new_line = {}
    new_line["context_left"] = line["context_left"]
    new_line["context_right"] = line["context_right"]
    label_title = line["label_title"]
    new_line["label"] = entity_index_by_title[label_title][0]
    new_line["label_title"] = label_title
    new_line["label_id"] = entity_index_by_title[label_title][1]
    new_line["mention"] = line["mention"]
    new_line["from_doc"] = line["from_doc"]
    new_line["world"] = line["world"]
    new_line["match_type"] = line["match_type"]
    out_f.write(json.dumps(new_line)+"\n")
    line = f.readline()
f.close()
out_f.close()


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

# In[ ]:

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

# In[ ]:

# In[ ]:

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

# In[ ]:

"""
Created on Fri Oct 13 20:37:30 2023

@author: saimo
"""
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import altair as alt
from PIL import Image
from sklearn.feature_selection import SelectKBest, chi2
import plotly.express as px
import hiplot as hip
from sklearn.metrics import roc_curve
from sklearn.metrics import accuracy_score, roc_curve, auc
from sklearn.impute import SimpleImputer
#import pandas as pd
from sklearn.utils import resample
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, roc_curve, auc, f1_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier, ExtraTreesClassifier, BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
from xgboost import XGBClassifier, XGBRFClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
import matplotlib.pyplot as plt
import numpy as np

st.set_option('deprecation.showPyplotGlobalUse', False)
st.set_page_config(layout="wide")

# Load the Framingham dataset
@st.cache_data
def load_data():
    data = pd.read_csv('Framingham_app/framingham.csv')  # Replace with the actual path to your dataset
    return data

data = load_data()

tab1, tab2, tab3,tab4,tab5,tab6,tab7 = st.tabs(["About Data", "Basic information Plots", "UniVariant Analysis Plots","MultiVariant Analysis Plots","Machine Learning Models","Inference on Inputs","Bio"])

with tab1:
   st.title("Framingham Heart Study Data")
   image = Image.open('Framingham_app/Heart_img.png')
   img = image.resize((image.height, 300))

   st.image(img, caption='Image')

   st.title("About the DATA")
   st.write("The Framingham Heart Study is a long-term, ongoing cardiovascular cohort study that began in 1948 in Framingham, Massachusetts, USA. It's one of the most well-known and influential epidemiological studies of heart disease. The study has provided valuable insights into the risk factors associated with cardiovascular disease and has helped shape our understanding of heart disease and its prevention. The Framingham dataset is a collection of data generated through this study, and it's widely used in epidemiological and public health research.")
   st.write("The dataset contains detailed information about a variety of cardiovascular risk factors and other health-related variables for thousands of individuals. Here's an overview of the key aspects of the Framingham dataset: 1. **Study Participants**: The dataset includes information about thousands of participants from the Framingham area. It has both original and offspring cohorts, meaning it has data from different generations.2. **Data Categories**: The Framingham dataset includes information on a wide range of variables, including:- Demographic information (age, gender, etc.).- Medical history (e.g., diabetes, hypertension).")

   st.title("About this WebAPP")

   st.write("The web app is designed to provide an interactive and visually engaging platform for exploring and visualizing data from the Framingham Heart Study dataset. Users can interact with the app to:")

   st.write("1. Visualize data relationships: Explore relationships between various attributes and Ten-Year Coronary Heart Disease (CHD) status through interactive scatter plots.")

   st.write("2. Understand CHD distribution: View the proportion of CHD cases versus no CHD cases using an interactive pie chart.")

   st.write("3. Interactive 3D visualization: Discover how age, cigarettes per day, and systolic blood pressure relate to Ten-Year CHD using an interactive 3D scatter plot.")

   st.write("4. Missing data analysis: Visualize missing data patterns using heatmaps and bar plots for a comprehensive data overview.")

   st.write("5. Customizable exploration: Users can customize their exploration by selecting attributes and visualizations through drop-down menus and select boxes.")

   st.write("This web app empowers users to gain insights and understand the Framingham dataset visually, enhancing the process of data exploration and analysis.")

   col1,col2 = st.columns(2)
   with col1:
    on = st.toggle('feature list of the dataset')
    if on:
        #st.write('Feature activated!')
        k = list(data.columns)
        st.write(k)
        st.write('Basic Framingham Dataset Information:')
        st.write(f'Total Number of Samples: {data.shape[0]}')
        st.write(f'Number of Features: {data.shape[1]}')
    with col2:
        on1 = st.toggle('summary statistics of the dataset')

        if on1:
            st.write("### Summary Statistics")
            st.write(data.describe())

with tab2:

    chd_counts = data['TenYearCHD'].value_counts()
    chd_proportion = chd_counts / chd_counts.sum()

    st.title("Pie Chart: Proportion of CHD vs. No CHD")

    fig = px.pie(chd_proportion, values=chd_proportion, names=chd_proportion.index,
                 labels={'index': 'CHD Status'}, title="Proportion of CHD vs. No CHD")

    st.plotly_chart(fig)

    st.header('Data Filters')
    age_filter = st.slider('Filter by Age', min_value=int(data['age'].min()), max_value=int(data['age'].max()))
    filtered_data = data[data['age'] <= age_filter]
    # st.write("### Filtered Data")
    # st.write(filtered_data)
    # Show an Altair plot of age distribution
    st.write("### Age Distribution")
    age_chart = alt.Chart(filtered_data).mark_bar().encode(
        x=alt.X('age:Q', bin=True),
        y='count()',
        tooltip=['age:Q', 'count()']
    ).interactive()
    st.altair_chart(age_chart)
    st.write("### Filtered Data")
    st.write(filtered_data)

    # Interactive scatter plot use it in the 3rd tab.
    # st.write("### Interactive Scatter Plot")
    # x_column = st.selectbox("X-axis", filtered_data.columns)
    # y_column = st.selectbox("Y-axis", filtered_data.columns)
    # scatter_chart = alt.Chart(filtered_data).mark_circle().encode(
    #     x=x_column,
    #     y=y_column,
    #     tooltip=[x_column, y_column]
    # ).interactive()
    # st.altair_chart(scatter_chart)

#     missing_data = data.isnull()

# # Use Seaborn to create a heatmap
#     fig = plt.figure(figsize=(10, 6))
#     sns.heatmap(missing_data, cbar=False, cmap='viridis')
#     plt.title('Missing Data in Framingham Dataset')
#     st.pyplot(fig)

    missing_values_count = data.isnull().sum()
    plt.figure(figsize=(10, 6))
    missing_values_count.plot(kind='bar', color='skyblue')
    plt.title("Missing Values by Attribute")
    plt.xlabel("Attributes")
    plt.ylabel("Count of Missing Values")
    plt.xticks(rotation=45)
    st.pyplot()

    numeric_columns = data.select_dtypes(include=['number']).columns
    categorical_columns = data.select_dtypes(exclude=['number']).columns

# Impute missing values based on data type

    st.title ("Data Before Handling Missing Values")
    imputed_data = data.copy()

    col1,col2 = st.columns(2)

    with col1:
     on = st.toggle('feature list of the dataset',['features'])
     if on:
         st.write("Original Data:")
         st.write(data)
     else:
         col1.empty()
        #st.write('Feature activated!')
        # k = list(data.columns)
        # st.write(k)
        # st.write('Basic Framingham Dataset Information:')
        # st.write(f'Total Number of Samples: {data.shape[0]}')
        # st.write(f'Number of Features: {data.shape[1]}')

    with col2:
        on1 = st.toggle('summary statistics of the dataset',['summary'])

        if on1:
            st.write("### Summary Statistics")
            st.write(data.describe())

    for col in numeric_columns:
        imputed_data[col].fillna(imputed_data[col].mean(), inplace=True)

    for col in categorical_columns:
        imputed_data[col].fillna(imputed_data[col].mode().iloc[0], inplace=True)

    st.title("Imputed Data (Mean for Numeric, Mode for Categorical):")
    st.write(imputed_data.describe())
#framingham.csv" with the actual path to your Framingham dataset. This code handles missing values according to the data type of the attribute and provides an imputed dataset for further analysis or visualization.

    # chd_counts = data['TenYearCHD'].value_counts()
    # chd_proportion = chd_counts / chd_counts.sum()

    # st.title("Interactive Pie Chart: Proportion of CHD vs. No CHD")

    # fig = px.pie(chd_proportion, values=chd_proportion, names=chd_proportion.index,
    #              labels={'index': 'CHD Status'}, title="Proportion of CHD vs. No CHD")

    # st.plotly_chart(fig)

    # # Example: Plot a histogram of Age
    # st.subheader("Age Distribution")
    # plt.figure(figsize=(8, 6))
    # sns.histplot(data['age'], bins=20, kde=True)
    # st.pyplot()
    # st.header("A dog")
    # st.image("https://static.streamlit.io/examples/dog.jpg", width=200)
    #st.subheader("Conclusion")
    #st.write(" From the above analysis we can clearly see how the data is distributed and how the missing values look after imputation.")

with tab3:
    data = load_data()

# Basic EDA plots for categorical variables using interactive violin plots
    st.title("Violin Plots for Categorical Variables in Framingham Dataset")

    st.write("Univariate analysis : Here we focus on examining individual variables one at a time. In the context of the Framingham Heart Study dataset, univariate analysis involves studying the relationship between each individual feature (independent variable) and the target variable 'TenYearCHD' (Coronary Heart Disease) to understand how each feature influences the presence of CHD. Univariate analysis helps identify which features have a significant impact on CHD.")

# Define the categorical variables to be visualized
    categorical_columns = ["currentSmoker", "BPMeds", "prevalentStroke", "prevalentHyp","male"]
    selected_variable = st.selectbox("Select a Categorical Variable", categorical_columns)

    fig = px.violin(data, x=selected_variable, y="age", box=True, points="all", title=f"Interactive Violin Plot for {selected_variable} vs Age")
    st.plotly_chart(fig)

    selected_variable = st.radio("Select a Categorical Variable", categorical_columns)

# Create box plots for the selected variable with respect to CHD

    fig = px.box(data, x=selected_variable, y="age", color="TenYearCHD",
              labels={"age": "Age", selected_variable: selected_variable, "TenYearCHD": "CHD"})

    fig.update_layout(
    title=f"Interactive Box Plot for {selected_variable} with Respect to CHD",
    xaxis_title='',
    yaxis_title='Age',
    showlegend=True,
)
    st.plotly_chart(fig)

# Create interactive violin plots for categorical variables
   # Create interactive violin plot for the selected variable

    # for col in categorical_columns:
    #     fig = px.violin(data, x=col, y="age", box=True, points="all", title=f"Interactive Violin Plot for {col} vs Age")
    #     st.plotly_chart(fig)

    st.title("KDE Plots for the Attributes with Respect to CHD")

    # Define the numerical variables to be visualized
    numerical_columns = ["age", "cigsPerDay", "totChol", "sysBP", "diaBP", "BMI", "heartRate", "glucose"]

    # Select box to choose a numerical variable
    # selected_variable = st.selectbox("Select a Numerical Variable", numerical_columns)

# Create KDE plots for the selected numerical variable with respect to CHD

# Filter the data into two subsets based on TenYearCHD
    chd_positive = data[data['TenYearCHD'] == 1]
    chd_negative = data[data['TenYearCHD'] == 0]

    # List of columns to plot
    columns_to_plot = data.columns.drop('TenYearCHD')

    # Plot categorical features (bar plots)
    for column in columns_to_plot:
        if data[column].dtype == 'object':
            plt.figure(figsize=(8, 4))
            sns.countplot(x=column, data=data, hue='TenYearCHD')
            plt.title(f'{column} vs. Ten-Year CHD')
            plt.xticks(rotation=45)
            # plt.show()
            st.pyplot()

    # Plot continuous features (histograms)
    for column in columns_to_plot:
        if data[column].dtype != 'object':
            plt.figure(figsize=(8, 4))
            sns.histplot(chd_negative[column], kde=True, label='No CHD', color='blue', alpha=0.6)
            sns.histplot(chd_positive[column], kde=True, label='CHD', color='red', alpha=0.6)
            plt.title(f'{column} vs. Ten-Year CHD')
            plt.xlabel(column)
            plt.legend()
            # plt.show(
            st.pyplot()
    st.subheader('Conclusion')
    st.write('From the above plots we can see the relation that how each feature is being associate with the output and we also get know about the distribution of the data according to the target class')

with tab4:

    st.title("Multivariant Analyis")

    st.write("Here we examing the relationships between multiple variables simultaneously. In the context of the Framingham Heart Study dataset, you can perform multivariate analysis to understand how combinations of features (independent variables) collectively influence the presence of Ten-Year Coronary Heart Disease (CHD) represented by the 'TenYearCHD' target variable. ")

    selected_variable = st.selectbox("Select a Numerical Variable", data.select_dtypes(include=['number']).columns)

    #st.write("suggested attributes for the scatter plot are")

    non_categorical_columns = data.select_dtypes(exclude=['object']).columns

    # Print the column names that do not have categorical values
    numerical_columns = ["cigsPerDay", "totChol", "sysBP", "diaBP", "BMI", "heartRate", "glucose"]

    st.write ("Suggested Attributes")
    st.write(numerical_columns)

    # Create an interactive scatter plot showing age vs. the selected numerical variable with color-coded CHD
    st.title(f"Interactive Scatter Plot: Age vs. {selected_variable} vs. Ten-Year CHD")

    fig = px.scatter(data, x="age", y=selected_variable, color="TenYearCHD",
                     color_continuous_scale=["blue", "red"],
                     labels={"age": "Age", selected_variable: selected_variable, "TenYearCHD": "CHD"})

    fig.update_layout(
        title=f"Age vs. {selected_variable} vs. Ten-Year CHD",
        xaxis_title="Age",
        yaxis_title=selected_variable
    )

    st.plotly_chart(fig)

    st.title("Interactive 3D Scatter Plot: Age, Cigarettes Per Day, Systolic BP vs. Ten-Year CHD")

    fig = px.scatter_3d(data, x="age", y="cigsPerDay", z="sysBP", color="TenYearCHD",
                        color_continuous_scale=["blue", "red"],
                        labels={"age": "Age", "cigsPerDay": "Cigarettes Per Day", "sysBP": "Systolic BP", "TenYearCHD": "CHD"})

    fig.update_layout(
        scene=dict(xaxis_title="Age", yaxis_title="Cigarettes Per Day", zaxis_title="Systolic BP"),
        title="Age, Cigarettes Per Day, Systolic BP vs. Ten-Year CHD"
    )

    st.plotly_chart(fig)

#visualization with HiPlot
    def save_hiplot_to_html(exp):
        output_file = "hiplot_plot_1.html"
        exp.to_html(output_file)
        return output_file

    st.header("Visualization with HiPlot")
    selected_columns = st.multiselect("Select columns to visualize", imputed_data.columns,default = ['age', 'cigsPerDay', 'totChol', 'sysBP','heartRate','TenYearCHD'])
                                      #color='TenYearCHD', title='Interactive Parallel Coordinates Plot')
    selected_data = imputed_data[selected_columns]
    if not selected_data.empty:
        experiment = hip.Experiment.from_dataframe(selected_data)
        hiplot_html_file = save_hiplot_to_html(experiment)
        st.components.v1.html(open(hiplot_html_file, 'r').read(), height=1500, scrolling=True)
    else:
        st.write("No data selected. Please choose at least one column to visualize.")
    st.subheader('Conclusion')
    st.write('This tab was mainly used to understand how two features of the data played a role in understanding the target disease. From the Hi-plot we can interactively and select the features and data accordingly to see what effect the features have on Heart Disease.')

with tab5:
    st.title("Machine Learning Classifier Performance")
    #data, selected_columns = oad_data()
    st.write('The Predictive Analysis feature within the application utilizes sophisticated machine learning models such as Logistic Regression and Random Forest to unravel the features of the subjects. With a diverse array of models, users can gain varied analytical perspectives on Framingham Data.')
    st.write('This tab serves as a conduit for translating complex data into accessible and interactive insights, enabling users, from decision-makers to the general public, to experiment with data and witness immediate results. This approach not only facilitates the prediction and comprehension of this complex data but also empowers users to engage with and respond to these critical issues proactively. The customization feature allows users to tailor the analysis with respect to the selected feautures and also use top 10 features to dervide insights.')
    st.write('The inclusion of a range of models is pivotal, as it enables users to apply diverse analytical perspectives to the same dataset. This diversity is critical because different models can spotlight distinct facets of the data.')
    st.markdown("""<hr style="height:3px;border:none;color:#333;background-color:#333;" /> """, unsafe_allow_html=True)
    def oad_data():
        data = pd.read_csv('Framingham_app/framingham.csv')

        data = data.sample(frac=0.6, random_state=42)  # Use a fixed random state for reproducibility

        # Preprocessing steps (handle missing values, etc.)
        missing_values_before = data.isnull().sum()
        #st.write("Missing values before imputation:", missing_values_before)

        # Impute missing values for numerical columns
        num_cols = data.select_dtypes(include=['int64', 'float64']).columns
        imputer = SimpleImputer(strategy='median')
        data[num_cols] = imputer.fit_transform(data[num_cols])

        # Check for missing values after imputation
        missing_values_after = data.isnull().sum()

        #st.write("Missing values after imputation:", missing_values_after)

        # Check for and replace infinite values
        data.replace([np.inf, -np.inf], np.nan, inplace=True)

        # Check for missing values after replacing infinite values
        missing_infinite = data.isnull().sum()
        #st.write("Missing/infinite values after replacement:", missing_infinite)

        # Drop any rows that still have NaNs (should be very few if any)
        data.dropna(inplace=True)

        # Preprocessing steps (handle missing values, etc.)
        # ...

        # Splitting the dataset based on class
        target1 = data[data['TenYearCHD'] == 1]
        target0 = data[data['TenYearCHD'] == 0]

        # Resampling to balance the dataset
        target1_resampled = resample(target1, replace=True, n_samples=len(target0), random_state=40)
        data_balanced = pd.concat([target0, target1_resampled])

        # Feature Selection
        X = data_balanced.iloc[:, 0:15]
        y = data_balanced.iloc[:, -1]

        best = SelectKBest(score_func=chi2, k=10)
        best.fit(X, y)

        # Select the top 10 features
        top_features = [X.columns[i] for i in best.get_support(indices=True)]
        data_selected = data_balanced[top_features + ['TenYearCHD']]

        return data_selected

    data = oad_data()

    def train_evaluate_model_cv(model, X, y, cv_folds):
        scores = cross_val_score(model, X, y, cv=cv_folds, scoring='f1')
        mean_score = np.mean(scores)
        accuracy_scores = cross_val_score(model, X, y, cv=cv_folds, scoring='accuracy')
        mean_accuracy_score = np.mean(accuracy_scores)
        st.write(f"Mean Accuracy Score (Cross-Validation): {mean_accuracy_score:.4f}")
        st.write(f"Mean F1 Score (Cross-Validation): {mean_score:.4f}")
        return mean_score, mean_accuracy_score
        #st.write(f"Mean F1 Score (Cross-Validation): {mean_score:.4f}")

        #return mean_score
    # Function to plot top 10 important features
    def plot_top_features(X, y):
        selector = SelectKBest(f_classif, k=10)
        X_new = selector.fit_transform(X, y)
        feature_scores = pd.DataFrame({'Feature': X.columns, 'Score': selector.scores_})
        top_features = feature_scores.nlargest(10, 'Score')

        fig, ax = plt.subplots()
        top_features.plot(x='Feature', y='Score', kind='barh', ax=ax, color='skyblue')
        ax.set_title('Top 10 Important Features')
        st.pyplot(fig)

    # Main app
    #st.title("Machine Learning Classifier Performance")

    #st.title("Machine Learning Classifier Performance")

# Load data
    data = oad_data()

    # Sidebar for feature selection
    all_features = data.drop('TenYearCHD', axis=1).columns.tolist()
    selected_features = st.multiselect("Select Features for Training", all_features, default=all_features[:10])

    # Option to use top 10 features from SelectKBest
    use_top_features = st.checkbox("Use Top 10 Features from SelectKBest", value=True)

    st.markdown("""<hr style="height:3px;border:none;color:#333;background-color:#333;" /> """, unsafe_allow_html=True)

    # Prepare data based on feature selection
    if use_top_features:
        X = data[selected_features]
    else:
        X = data[all_features]
    y = data['TenYearCHD']

    # Load data
    data = oad_data()

    # Sidebar for CV folds and feature selection
    cv_folds = st.slider("Select Number of Cross-Validation Folds", min_value=2, max_value=10, value=5)
    #selected_features = st.sidebar.multiselect("Select Features for Training",
                                           #options=data.columns.drop('TenYearCHD').tolist(),
                                           #default=data.columns.drop('TenYearCHD').tolist()[:10])

    #selected_features = st.sidebar.multiselect("Select Features for Training", data.columns.drop('TenYearCHD'), default=data.columns.drop('TenYearCHD'))
    st.markdown("""<hr style="height:3px;border:none;color:#333;background-color:#333;" /> """, unsafe_allow_html=True)

    # Prepare data
    #X = data[selected_features]
    #y = data['TenYearCHD']

    # Create tabs for each model
    tab_lr, tab_rf, tab_nb, tab_gb = st.tabs(["Logistic Regression", "Random Forest", "Naive Bayes", "Gradient Boosting"])

    with tab_lr:
        C_lr = st.number_input("C (Regularization parameter)", min_value=0.01, max_value=10.0, step=0.01, value=1.0)
        model_lr = LogisticRegression(C=C_lr, max_iter=1000)
        if st.button('Run Logistic Regression'):
            train_evaluate_model_cv(model_lr, X, y, cv_folds)

    with tab_rf:
        n_estimators_rf = st.slider("Number of trees in the forest", min_value=10, max_value=200, value=100)
        model_rf = RandomForestClassifier(n_estimators=n_estimators_rf)
        if st.button('Run Random Forest'):
            train_evaluate_model_cv(model_rf, X, y, cv_folds)

   # with tab_svm:
   #     C_svm = st.number_input("SVM - C (Regularization parameter)", 0.01, 10.0, step=0.01, value=1.0)
   #     kernel_svm = st.selectbox("SVM - Kernel", ("linear", "rbf", "poly"))
   #     model_svm = SVC(C=C_svm, kernel=kernel_svm, probability=True)
   #     if st.button('Run SVM'):
   #         train_evaluate_model_cv(model_svm, X, y, cv_folds)

    with tab_gb:
        n_estimators_gb = st.slider("Number of boosting stages", min_value=10, max_value=200, value=100)
        learning_rate_gb = st.number_input("Gradient Boosting - Learning Rate", 0.01, 1.0, step=0.01, value=0.1)
        model_gb = GradientBoostingClassifier(n_estimators=n_estimators_gb, learning_rate=learning_rate_gb)
        if st.button('Run Gradient Boosting'):
            train_evaluate_model_cv(model_gb, X, y, cv_folds)

    with tab_nb:
    #st.subheader("Naive Bayes Classifier")

    	model_nb = GaussianNB()

    	if st.button('Run Naive Bayes'):
        	train_evaluate_model_cv(model_nb, X, y, cv_folds)

    st.subheader("How each model understands data ?")
    st.write('Logistic Regression: Overview: Logistic Regression is a statistical method used for binary classification problems. It predicts the probability of an instance belonging to a particular class. Application: In the context of Framingham data, Logistic Regression can be used to predict the likelihood of a participant developing a cardiovascular condition based on various input features such as age, cholesterol levels, blood pressure, etc. However becaue of the complex features presnt in the dataset. This models fails to provide accurate predictions')
    st.write('Random Forest: Random Forest is an ensemble learning method that builds multiple decision trees and merges their predictions. It is versatile and can be used for both classification and regression tasks. Application: In the Framingham dataset, Random Forest could be employed to identify important features contributing to cardiovascular risk and provide robust predictions by aggregating outputs from multiple decision trees. This models performs the best and it is able to provide predictions irrespective of the features')
    st.write('Naive Bayes: Naive Bayes is a probabilistic classification algorithm based on Bayes theorem. Despite its simplicity, it often performs well, especially in text classification and simple datasets. Application: Naive Bayes can be applied to predict cardiovascular risk in the Framingham dataset by assuming independence between features, making it suitable for situations where this assumption is reasonable.')
    st.write('Gradient Boosting:Gradient Boosting is an ensemble technique that builds a series of weak learners (usually decision trees) sequentially, with each one correcting errors of its predecessor. Application: In the context of the Framingham data, Gradient Boosting can effectively capture complex relationships between features and the target variable, providing accurate predictions by combining the strengths of multiple weak models.')
    st.write('Experimenting with these models on the Framingham dataset allows for a nuanced understanding of their effectiveness in forecasting and dissecting cardiovascular risk. The choice of model depends on the specific characteristics of the data and the complexity of the scenarios being analyzed. By leveraging this diverse set of models, researchers and analysts can tailor their approach to gain comprehensive insights into the multifaceted nature of cardiovascular health and risk prediction.')
    # Plot top features
    plot_top_features(X, y)
    #st.subheader("How each model understands data ?")

with tab6:

    # Function to load and preprocess data
    def oad_data():
        data = pd.read_csv('Framingham_app/framingham.csv')
        data = data.sample(frac=0.6, random_state=42)

        # Preprocessing steps
        num_cols = data.select_dtypes(include=['int64', 'float64']).columns
        imputer = SimpleImputer(strategy='median')
        data[num_cols] = imputer.fit_transform(data[num_cols])

        data.replace([np.inf, -np.inf], np.nan, inplace=True)
        data.dropna(inplace=True)

        # Resampling to balance the dataset
        target1 = data[data['TenYearCHD'] == 1]
        target0 = data[data['TenYearCHD'] == 0]
        target1_resampled = resample(target1, replace=True, n_samples=len(target0), random_state=40)
        data_balanced = pd.concat([target0, target1_resampled])

        # Feature Selection
        X = data_balanced.iloc[:, :-1]
        y = data_balanced['TenYearCHD']
        best = SelectKBest(score_func=chi2, k=10)
        best.fit(X, y)
        top_features = [X.columns[i] for i in best.get_support(indices=True)]
        data_selected = data_balanced[top_features + ['TenYearCHD']]

        return data_selected, top_features

    data, top_features = oad_data()

    # Function to train the models
    def train_models(X_train, y_train):
        models = {
            'Logistic Regression': LogisticRegression(max_iter=1000),
            'Random Forest': RandomForestClassifier(n_estimators=100),
            'Naive Bayes': GaussianNB(),
            'Gradient Boosting': GradientBoostingClassifier(n_estimators=100)
        }
        for name, model in models.items():
            model.fit(X_train, y_train)
            models[name] = model
        return models

    # Main app
    st.title("Machine Learning Classifier Performance")

    # Split the data
    X = data[top_features]
    y = data['TenYearCHD']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    # User input for prediction
    with st.container():
        st.subheader("Make Predictions")
        columns = ['male','age','education','currentSmoker','cigsPerDay','BPMeds','prevalentStroke', 'prevalentHyp','diabetes','totChol','sysBP', 'diaBP', 'BMI', 'heartRate', 'glucose']

        input_data = {}
        for col in top_features:
            if col in ['male', 'currentSmoker', 'prevalentStroke', 'prevalentHyp', 'diabetes','BPMeds']:
                # Binary columns
                input_data[col] = st.selectbox(f"{col.capitalize()}", [0, 1],key=col)
            else:
                # Numerical columns
                # You might need to adjust min_value, max_value, and value based on the actual range of your data
                input_data[col] = st.number_input(f"{col.capitalize()}", min_value=0, max_value=100, value=50,key=col)

        if st.button("Predict"):
            input_df = pd.DataFrame([input_data])
        #input_data = {feature: st.number_input(f"{feature}", value=np.mean(X[feature])) for feature in top_features}
        #if st.button("Predict"):
            #input_df = pd.DataFrame([input_data])
            models = train_models(X_train, y_train)
            predictions = {name: model.predict(input_df)[0] for name, model in models.items()}

        # Displaying the predictions
            for model_name, prediction in predictions.items():
            	if model_name == 'Random Forest':
                	result = "Positive for CHD" if prediction == 1 else "Negative for CHD"
                	st.write(f"{model_name} Prediction: {result}")
            #models = train_models(X_train, y_train)
            #predictions = {name: model.predict(input_df)[0] for name, model in models.items()}
            #for model_name, prediction in predictions.items():
                #st.write(f"{model_name} Prediction: {prediction}")

        st.markdown("""<hr style="height:3px;border:none;color:#333;background-color:#333;" /> """, unsafe_allow_html=True)

        st.subheader("Conclusion")
        st.write("Our innovative web application, built upon the rich Framingham dataset, offers users a powerful and insightful platform for comprehensive data analysis and prediction in cardiovascular health.")
        st.write(" The univariate analysis component provides a meticulous examination of individual variables within the Framingham dataset. Users can delve into the distributions, central tendencies, and variations of key parameters, establishing a foundational understanding of each variable's characteristics. Advancing from univariate analysis, our app seamlessly integrates multivariate analysis capabilities, enabling users to uncover complex relationships and dependencies between various cardiovascular risk factors. This sophisticated exploration facilitates a holistic perspective, empowering users to discern intricate patterns and connections that contribute to a comprehensive understanding of cardiovascular health.")
        st.write("The true value of our application lies in its predictive prowess, driven by machine learning classifiers trained on the Framingham dataset. These models offer users the ability to anticipate potential cardiovascular events, assess risk factors, and make informed decisions for proactive health management. The predictive insights gleaned from our models contribute to a more personalized and preventive approach to cardiovascular care. Our user-friendly interface ensures accessibility for a diverse audience, from healthcare professionals to individuals keen on monitoring their cardiovascular health. By seamlessly integrating analytical tools and machine learning models, our app becomes an indispensable resource for deriving actionable insights from the Framingham dataset, ultimately contributing to enhanced cardiovascular risk assessment and personalized health strategies.")
        st.write("In summary, our web application on the Framingham dataset stands as a comprehensive solution, providing a deep dive into data analysis and predictive modeling specific to cardiovascular health. It is poised to make a meaningful impact on healthcare decision-making and individual well-being, aligning with the broader goals of proactive and personalized healthcare management.")

    # Optional: Add model performance metrics or other analyses here

with tab7:
    st.title("About the Developer ")

    col1, col2 = st.columns(2)

    col1.subheader("Sai Mohan Gajapaka")
    col1.text("Master's in Data Science, MSU")
    col1.write("As a dedicated Python programmer with a robust foundation in mathematical modeling and deep neural networks, I am currently advancing my journey in data science. My academic and research experiences have nurtured a strong proficiency in statistical analysis and machine learning, fueling my drive to tackle challenging problems with innovative solutions. My passion lies in applying my skills to real-world issues, particularly those that can make a positive social impact. I am constantly seeking opportunities that challenge me to grow and refine my abilities in this dynamic field. Beyond my academic pursuits, I have a keen interest in watching anime, which not only serves as a creative outlet but also often inspires my approach to complex problems. I'm deeply curious about the potential of deep learning and its applications, and I am committed to exploring its frontiers to contribute meaningfully to the field of data science.")

    try :
        col2.image("Framingham_app/profile.png")
    except:
     pass


import sqlite3 as sql
import json
import os
from datetime import datetime

db = sql.connect('MainScripts/JIRATable.sqlite')
c = db.cursor()
#
# c.execute('drop table if exists JIRAData')

c.execute('''create table if not exists JIRAData (Key text, Status text, Summary text,Reporter text,IssueCreatedOn text, IssueUpdatedOn text, RefreshDate text)''' )
#
ins = 'insert into JIRAData (Key,Status,Summary,Reporter,IssueCreatedOn,IssueUpdatedOn,RefreshDate) values (?,?,?,?,?,?,?)'
#
#
with open('MainScripts/JIRAData.json','r') as f:
    JData = json.load(f)
#
i = 0
#

for r in JData:
    RefreshDate = JData[i]['RefreshDate']
    val=(JData[i]['Key'],JData[i]['Status'],JData[i]['Summary'],JData[i]['Reporter'],JData[i]['IssueCreatedDate'],JData[i]['UpdatedDate'],RefreshDate)
    i = i+1
    c.execute(ins,val)
    print(c.fetchall())

db.commit()

# c.execute('select count(*) From JIRAData')
# res = c.fetchall()

# for row in res:
#     print(row)

# db.close()

# os.remove('JIRATable.sqlite')

# print(JData[0]['Key'])
# print(JData[1]['Key'])


import random
import time
from typing import Set

import schedule

from timmy import core
from timmy.data.war_state import WarState
from timmy.data.word_war import WordWar
from timmy.db_access import word_war_db

class WarTicker:
    def __init__(self):
        self.loaded_wars: Set[WordWar] = set()
        self.active_wars: Set[WordWar] = set()

    def reset_timer(self) -> None:
        schedule.clear('warticker')
        self.__init__()
        self.load_wars()

    def load_wars(self) -> None:
        self.loaded_wars = word_war_db.load_wars()
        schedule.every(1).seconds.do(war_update_loop).tag('warticker')

    def begin_war(self, war: WordWar) -> None:
        current_epoch = time.time()
        late_start = int(current_epoch - war.start_epoch)

        message = "{}: Starting now!".format(war.get_name())

        if late_start >= 5:
            message += " ({:d} seconds late. Sorry!)".format(late_start)

        core.bot_instance.connection.privmsg(war.channel, message)

        self.notify_war_members(war, message)

        war.begin_war()

    def end_war(self, war: WordWar) -> None:
        current_epoch = time.time()
        late_end = int(current_epoch - war.end_epoch)

        message = "{}: Ending now!".format(war.get_name())

        if late_end >= 5:
            message += " ({:d} seconds late. Sorry!)".format(late_end)

        core.bot_instance.connection.privmsg(war.channel, message)

        self.notify_war_members(war, message)

        if war.channel in core.bot_instance.channels:
            core.bot_instance.channels[war.channel].last_war_id = war.get_id()

        if war.current_chain >= war.total_chains:
            war.end_war()
            self.active_wars.remove(war)

            if war.channel in core.bot_instance.channels \
                    and core.bot_instance.channels[war.channel].newest_war_id == war.get_id():
                core.bot_instance.channels[war.channel].newest_war_id = ""
        else:
            war.current_chain += 1

            if war.randomness:
                war.start_epoch = war.end_epoch + war.base_break + (war.base_break * (random.randrange(20) - 10)) / 100
                war.end_epoch = war.start_epoch + war.base_duration + (
                        war.base_duration * (random.randrange(20) - 10)) / 100
            else:
                war.start_epoch = war.end_epoch + war.base_break
                war.end_epoch = war.start_epoch + war.base_duration

            war.start_break()
            self.war_start_count(war)

            if war.channel in core.bot_instance.channels:
                core.bot_instance.channels[war.channel].newest_war_id = war.get_id()

    @staticmethod
    def war_start_count(war: WordWar) -> None:
        time_to_start = int(war.start_epoch - time.time())

        if time_to_start < 60:
            message = "{}: Starting in {:d} {}.".format(
                    war.get_name(), time_to_start, "seconds" if time_to_start > 1 else "second"
            )
        else:
            minutes = time_to_start / 60
            if time_to_start % 60 == 0:
                message = "{}: Starting in {:d} {}.".format(
                        war.get_name(include_duration = True), int(minutes), "minutes" if minutes > 1 else "minute"
                )
            else:
                message = "{}: Starting in {:.1f} minutes.".format(war.get_name(include_duration = True), minutes)

        core.bot_instance.connection.privmsg(war.channel, message)

    @staticmethod
    def war_end_count(war: WordWar) -> None:
        time_to_end = int(war.end_epoch - time.time())

        if time_to_end < 60:
            message = "{}: {:d} {} remaining!".format(
                    war.get_name(), time_to_end, "seconds" if time_to_end > 1 else "second"
            )
        else:
            minutes = time_to_end // 60
            message = "{}: {:d} {} remaining.".format(
                    war.get_name(), minutes, "minutes" if minutes > 1 else "minute"
            )

        core.bot_instance.connection.privmsg(war.channel, message)

    @staticmethod
    def notify_war_members(war: WordWar, message: str) -> None:
        db_id = war.get_id()
        message += f" [ID {db_id}]"

        for nick in war.war_members:
            core.bot_instance.connection.privmsg(nick, message)

def war_update_loop() -> None:
    try:
        from timmy.core import bot_instance
        loaded_wars = core.war_ticker.loaded_wars.copy()

        for war in loaded_wars:
            if war.channel in bot_instance.channels.keys():
                core.war_ticker.active_wars.add(war)
                core.war_ticker.loaded_wars.remove(war)

                bot_instance.channels[war.channel].newest_war_id = war.get_id()

        wars = core.war_ticker.active_wars.copy()
        if wars is None or len(wars) <= 0:
            return

        current_epoch = time.time()

        for war in wars:
            if war.start_epoch >= current_epoch:
                time_difference = int(war.start_epoch - current_epoch)

                if time_difference in [600, 300, 60, 30, 5, 4, 3, 2, 1]:
                    core.war_ticker.war_start_count(war)
                elif time_difference == 0:
                    core.war_ticker.begin_war(war)
                elif time_difference >= 3600:
                    if time_difference % 3600 == 0:
                        core.war_ticker.war_start_count(war)
                elif time_difference >= 1800:
                    if time_difference % 1800 == 0:
                        core.war_ticker.war_start_count(war)
            else:
                if war.end_epoch >= current_epoch:
                    if war.state == WarState.PENDING:
                        core.war_ticker.begin_war(war)
                    else:
                        time_difference = int(war.end_epoch - current_epoch)

                        if time_difference in [600, 300, 60, 5, 4, 3, 2, 1]:
                            core.war_ticker.war_end_count(war)
                        elif time_difference == 0:
                            core.war_ticker.end_war(war)
                        elif time_difference >= 3600:
                            if time_difference % 3600 == 0:
                                core.war_ticker.war_end_count(war)
                        elif time_difference >= 1800:
                            if time_difference % 1800 == 0:
                                core.war_ticker.war_end_count(war)
                else:
                    core.war_ticker.end_war(war)
    except Exception:
        from timmy.utilities import irc_logger
        irc_logger.log_traceback()


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

import numpy as np
import librosa
from pathlib import Path

from microphone import record_audio

import matplotlib.mlab as mlab

from os import listdir
from os.path import isfile, join

import song_titles_artists as sta

def load_song_from_path(path: str):
    """
    Loads a song from a path.

    Returns the samples, sampling rate, and duration.

    Parameters
    ------------
    path: str
          The path for the specified audio file

    Returns
    -------
    Tuple[np.ndarray, int, float]
        The list of samples, the sampling rate and the duration of the song
    """
    song_path = Path(path)
    samples, sampling_rate = librosa.load(song_path, sr=None)
    duration = librosa.get_duration(y=samples, sr=sampling_rate)
    samples.astype("float32")
    samples /= np.max(samples)
    samples *= 2**15
    return samples, sampling_rate, duration

def load_music_files(directory: str):
    """
    Loads the files in a folder.

    Returns the samples from each file.

    Parameters
    ------------
    directory: str
          The path for the specified folder

    Returns
    -------
    List
        Names of all of the songs
    np.ndarray size: (M,N)
        The array of samples for each song
    """
    files = sorted([f for f in listdir(directory) if isfile(join(directory, f))])
    music_list = np.array([load_song_from_path(directory + paths)[0] for paths in files])
    id_dict = sta.song_name_to_ID(files)
    ids = [id_dict[title] for title in files]
    return ids, music_list

def return_specgram(samples: np.ndarray, sampling_rate: int):
    """
    Creates the spectrogram for a specific set of samples

    Returns the spectrogram, the frequencies, and the times

    Parameters
    ------------
    samples: np.ndarray
          The array of samples
    sampling_rate: int
          The sampling rate
    Returns
    -------
    Tuple[np.narray, np.narray, np.narray]
        The spectrogram 2d array, the frequencies and the timestamps
    """
    S, freqs, times = mlab.specgram(
        samples,
        NFFT=4096,
        Fs=sampling_rate,
        window=mlab.window_hanning,
        noverlap=int(4096 / 2),
        mode='magnitude'
    )
    return S, freqs, times

def record_sound(time: float):
    """
    Records sound for a specific duration of time

    Returns the frames and the sample rate

    Parameters
    ------------
    time: float
          The duration of the recording in seconds

    Returns
    -------
    Tuple[np.ndarray, int]
        The frames and the sample rate
    """
    listen_time = time  # seconds
    frames, sample_rate = record_audio(listen_time)
    samples = np.empty(0)
    for i in frames:
        samples = np.append(samples, np.frombuffer(i, np.int16))
    samples = samples.astype("float32")
    samples /= np.max(samples)
    samples *= 2 ** 15
    return samples, sample_rate