from typing import Any, Dict, Generator, Iterable, Optional, Union, Tuple, List

from aiosqlite.core import Connection
from aiosqlite.cursor import Cursor

from .utils import build_query, dict_factory

class MotorSqliteTable(object):
    def __init__(self, conn: Connection, table: str) -> None:
        self.db = None
        self.conn = conn
        self.table = table

        # SQL queries
        self.select_sql = f'SELECT * FROM {table} WHERE '
        self.update_sql = f'UPDATE {table} SET '
        self.insert_sql = f'INSERT INTO {table} '
        self.delete_sql = f'DELETE FROM {table} WHERE '
        self.drop_sql = f'DROP TABLE {table}'
        self.count_sql = f'SELECT COUNT(*) FROM {table}'

    async def _execute(
        self, query: str, values: Iterable[Any] = None
    ) -> Cursor:

        if self.db is None:
            self.db = await self.conn

        self.db.row_factory = dict_factory  # type: ignore
        cursor = await self.db.execute(query, values)
        await self.db.commit()

        return cursor

    async def find(
        self, _dict: Dict[str, Any]
    ) -> Generator[Dict[str, Union[str, int]], None, None]:
        if not _dict:
            cursor = await self._execute(self.select_sql.split(' WHERE')[0])
        else:
            query, values = build_query(self.select_sql, _dict)
            cursor = await self._execute(query, values)

        # async generator to keep it similar to motor api
        for res in await cursor.fetchall():
            yield res

    async def find_one(
        self, _dict: Dict[str, Any]
    ) -> Optional[Dict[str, Union[str, int]]]:

        try:
            return await self.find(_dict).__anext__()
        except StopAsyncIteration:
            return None

    def _update(
        self, _dict: Dict[str, Any], opts: Dict[str, Dict[str, Any]]
    ) -> Tuple[str, List[Any]]:
        query, values = build_query(self.update_sql, opts['$set'], ' = ?,')
        # such an ugly way to remove trailing `,` and add `WHERE`
        query = query[:-1] + ' WHERE '

        query, x = build_query(query, _dict)
        values += x

        return query, values

    async def update(
        self, _dict: Dict[str, Any], opts: Dict[str, Dict[str, Any]],
        one: bool = False
    ) -> int:
        query, values = self._update(_dict, opts)
        cursor = await self._execute(query, values)

        if one:
            query += ' LIMIT 1'

        return cursor.rowcount

    async def update_one(
        self, _dict: Dict[str, Any], opts: Dict[str, Dict[str, Any]]
    ) -> bool:
        return await self.update(_dict, opts, True) == 1

    async def insert(self, data: Dict[str, Any]) -> int:
        query = f"{self.insert_sql}({','.join(data.keys())}) VALUES ("
        query, values = build_query(query, data, '?,', False)

        # such an ugly way to remove trailing `,` and add `)`
        query = query[:-1] + ')'

        cursor = await self._execute(query, values)

        return cursor.rowcount

    async def insert_one(self, data: Dict[str, Any]) -> bool:
        return await self.insert(data) == 1

    async def execute_raw(
        self, sql: str, params: Iterable[Any] = None
    ) -> Cursor:
        return await self._execute(sql, params)

    async def drop_collection(self) -> Cursor:
        return await self._execute(self.drop_sql)

    async def delete(self, data: Dict[str, Any], one: bool = False) -> int:
        query, values = build_query(self.delete_sql, data)

        if one:
            query += ' LIMIT 1'

        cursor = await self._execute(query, values)

        return cursor.rowcount

    async def delete_one(self, data: Dict[str, Any]) -> bool:
        return await self.delete(data, True) == 1

    async def count_documents(self, _dict: Dict[str, Any] = None) -> int:
        query = self.count_sql
        values = None

        if _dict is not None:
            query += ' WHERE '
            query, values = build_query(query, _dict)

        cursor = await self._execute(query, values)

        return (await cursor.fetchone())['COUNT(*)']


import random, time
import paho.mqtt.client as paho
from serial import Serial

responses = {'u': 7, 'd': 6}
port = "/dev/ttyUSB0"

# if it doesn't work check the baudrate here and on the microcontroller (Serial begin (9600))
connection = Serial(port, timeout=1)

def send_command(cmd, response_len):
	connection.write(cmd.encode())	# cmd is a command

def on_message(client, user_data, message):
	time.sleep(1)
	data = str(message.payload.decode("utf-8"))
	send_command(data, responses[data])

broker = "broker.emqx.io"
client = paho.Client("client-isu-000000001")	# pass client id, it should be unique for pub and sub

client.on_message = on_message

print("Connecting to broker", broker)
client.connect(broker)
client.loop_start()

print("Subscribing")
client.subscribe("sergei/mcu/led")
time.sleep(30)

client.disconnect()
client.loop_stop()


import csv  # csv import
import operator  # dict 정렬
from sys import exit  # 프로그램 종료

# data 열기

try:
    f = open('전국무료와이파이표준데이터.csv', encoding='cp949')
except FileNotFoundError:
    print("No File T_T")
    exit(0)
else:
    data = csv.reader(f)

comp_dict = {}  # 서비스 제공사
place_dict = {}  # 시설군
city_dict = {}  # 시도
siz = 0  # 서비스 제공사 dict의 사이즈
psiz = 0  # 시설군 dict의 사이즈
csiz = 0  # 시도 dict의 사이즈

for row in data:
    if row[5] == "서비스제공사명": continue  # 첫 번째 line에는 이름이 기술되어 있으므로 pass
    if row[5] not in comp_dict:  # dict 생성
        siz += 1
        comp_dict.setdefault(row[5], 1)
    else:
        comp_dict[row[5]] += 1  # 이미 있는 경우 값 +1

    if row[4] not in place_dict:  # dict 생성
        psiz += 1
        place_dict.setdefault(row[4], 1)
    else:
        place_dict[row[4]] += 1  # 이미 있는 경우 값 +1

    if row[2] not in city_dict:  # dict 생성
        csiz += 1
        city_dict.setdefault(row[2], 1)
    else:
        city_dict[row[2]] += 1  # 이미 있는 경우 값+1

# 값에 따라 정렬
sorted_comp = sorted(comp_dict.items(), key=operator.itemgetter(1))
sorted_place = sorted(place_dict.items(), key=operator.itemgetter(1))
sorted_city = sorted(city_dict.items(), key=operator.itemgetter(1))

print("가장 많은 무료 와이파이를 설치한 업체:", sorted_comp[siz - 1][0], ',', sorted_comp[siz - 1][1], "개")  # dict의 마지막 위치에 존재
print("가장 많은 무료 와이파이가 설치된 시설군:", sorted_place[psiz - 1][0], ',', sorted_place[psiz - 1][1], "개")  # dict의 마지막 위치에 존재
f.close()  # 파일 닫기

# 파일 다시 열기
try:
    f = open('전국무료와이파이표준데이터.csv', encoding='cp949')
except FileNotFoundError:
    print("No File T_T")
    exit(0)
else:
    data = csv.reader(f)

# 값 비교를 통해 위도가 가장 높은 지역을 찾는다.

maxlong = 0
maxplace = ' '
for row2 in data:
    try:
        if float(row2[12]) < 90 and maxlong < float(row2[12]):  # 위도 없는 경우 99.999999로 되어 있어서 제외
            maxplace = row2[0]
            maxlong = float(row2[12])
    except ValueError:  # 숫자가 아닌 것을 float로 변환하려 할 경우 ValueError가 나타남
        continue
print("가장 높은 위도에 설치된 와이파이: ", maxplace, ',', maxlong)  # 출력

print("시도별 무료 와이파이 개수 랭킹(개)")  # 랭킹은 길기 때문에 가장 마지막에 출력
cnt = 17
while cnt > 0:
    print(18 - cnt, ":", sorted_city[cnt - 1][0], ',', sorted_city[cnt - 1][1])
    cnt -= 1


from __future__ import annotations

import logging
import operator
from typing import (Callable, Dict, Hashable, Iterable, List, Optional, Set,
                    Tuple, TypeVar)

from .enums import Amphipod
from .map import (FieldType, PossibleMove, get_allowed_moves, get_move_energy,
                  move)

logger = logging.getLogger(__name__)

IDType = TypeVar("IDType", bound=Hashable)

def dfs(
    *,
    starting_board: Dict[FieldType, Optional[Amphipod]],
    target_board: Dict[FieldType, Optional[Amphipod]],
    possible_moves: List[PossibleMove[FieldType]],
    board_hasher: Callable[[Dict[FieldType, Optional[Amphipod]]], IDType]
) -> Tuple[List[PossibleMove[FieldType]], int]:
    ALMOST_INFINITY = 2 ** 31
    best_energy = ALMOST_INFINITY
    no_moves: List[PossibleMove[FieldType]] = []

    score_sort_key = operator.itemgetter(1)

    cache: Dict[IDType, Tuple[List[PossibleMove[FieldType]], int]] = {}

    def get_moves(
        current_board: Dict[FieldType, Optional[Amphipod]], current_energy: int
    ) -> Iterable[Tuple[PossibleMove[FieldType], int]]:
        allowed_moves = get_allowed_moves(current_board, possible_moves)
        moves_with_energy = (
            (allowed_move, get_move_energy(current_board, allowed_move))
            for allowed_move in allowed_moves
        )
        promising_moves = (
            (possible_move, move_energy)
            for possible_move, move_energy in moves_with_energy
            if current_energy + move_energy < best_energy
        )
        # Explore the state space based on current move cost heuristic
        return sorted(promising_moves, key=score_sort_key)

    def recursive_search(
        current_board: Dict[FieldType, Optional[Amphipod]],
        current_energy: int,
        # moves_so_far: List[PossibleMove[FieldType]],
    ) -> Tuple[List[PossibleMove[FieldType]], int]:
        """Returns a tuple: (moves to terminal stage, energy to terminal stage)."""
        nonlocal best_energy
        if current_board == target_board:
            if current_energy < best_energy:
                logger.debug("Found best terminal state %d", current_energy)
                best_energy = current_energy
            return no_moves, 0

        current_board_id = board_hasher(current_board)
        if current_board_id in cache:
            return cache[current_board_id]

        results: List[Tuple[List[PossibleMove[FieldType]], int]] = []
        for possible_move, move_energy in get_moves(current_board, current_energy):
            possible_board = move(current_board, possible_move)
            result_moves, result_energy = recursive_search(
                possible_board,
                current_energy + move_energy,
                # moves_so_far + [possible_move],
            )
            results.append(
                ([possible_move] + result_moves, result_energy + move_energy)
            )
        if not results:
            # blind alley
            solution = no_moves, ALMOST_INFINITY
            cache[current_board_id] = solution
            return solution
        results.sort(key=score_sort_key)

        (best_possibility_moves, best_possibility_score), *other_possibilities = results
        if current_energy + best_possibility_score < best_energy:
            logger.debug("Found best state %d", current_energy + best_possibility_score)
            best_energy = current_energy + best_possibility_score

        solution = (best_possibility_moves, best_possibility_score)
        cache[current_board_id] = solution
        return solution

    return recursive_search(starting_board, 0)


from datetime import datetime
from datetime import date
import numpy as np
import pandas as pd
from pandas_datareader import data as wb
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
import yfinance as yf
import math
from get_all_tickers import get_tickers as gt
dict = ['GOOG', 'AAPL','MSFT','AMZN','NVDA']
valid_Input = False

# User ticker selection
while not valid_Input:
    x = 0
    val = -1
    tickerSelection = ""
    for tickers in dict:
        tickerSelection += tickers + " [" + str(x) + "] || "
        x += 1
    tickerSelection += "\n"
    try:
        val = int(input("Please enter the number for the ticker you would like to track: \n" + tickerSelection))
    except:
        print("Please input integer only...")
    # print("Yo"val)
    if val >= 0 and val <= len(dict) -1:
        valid_Input = True
    else:
        print("Invalid input please try again \n\n")

# Ticker data pull
ticker =  dict[val]
start = datetime(2019, 1, 1)
end = date.today()
data = yf.download(ticker, start , end)['Adj Close']
data.plot(figsize=(15,6))
plt.show()

# Plot daily log returns
log_returns = np.log(1 + data.pct_change())
sns.distplot(log_returns.iloc[1:])
plt.xlabel("Daily Return")
plt.ylabel("Frequency")
plt.show()

# Probablitiy calculations
u = log_returns.mean()
var = log_returns.var()
drift = u - (0.5*var)
stdev = log_returns.std()

# CAGR and initializations
days = 50
number_of_trials = 3000
time_elapsed = (data.index[-1] - data.index[0]).days
total_growth = (data[-1] / data[1])
number_of_years = time_elapsed / 365.0
cagr = total_growth ** (1/number_of_years) - 1
closing_prices = []
number_of_trading_days = 252

# Daily return percentages for the next 50 days and Monte Carlo Sim
for i in range(number_of_trials):
    daily_return_percentages = np.random.normal(cagr/number_of_trading_days, stdev/math.sqrt(number_of_trading_days),number_of_trading_days)+1
    price_series = [data[-1]]

    for j in daily_return_percentages:
        price_series.append(price_series[-1] * j)
    closing_prices.append(price_series[-1])
    plt.plot(price_series)
plt.show()

# Histogram of 50 day returns
plt.hist(closing_prices,bins=40)
plt.show()

# Expected price
mean_end_price = round(np.mean(closing_prices),2)
print("Expected price: $", str(mean_end_price))

# Modified histogram (Top & bottom 10 percentiles)
top_ten = np.percentile(closing_prices,100-10)
bottom_ten = np.percentile(closing_prices,10)
plt.hist(closing_prices,bins=40)
plt.axvline(top_ten,color='r',linestyle='dashed',linewidth=2)
plt.axvline(bottom_ten,color='r',linestyle='dashed',linewidth=2)
plt.axvline(data[-1],color='g', linestyle='dashed',linewidth=2)
plt.show()


from tkinter import messagebox
import tkinter as tk
import ctypes as ty
from calendario import Calendar
import datetime as dt

now=dt.datetime.now()
Any,Mes,Dia,Hora,Minut=now.year,now.month,now.day,now.hour,now.minute
calendari=Calendar(Any)

amplada, altura=ty.windll.user32.GetSystemMetrics(0), ty.windll.user32.GetSystemMetrics(1)

windows=tk.Tk()

windows.geometry(f'{amplada}x{altura-3}')
windows.title("Welcome to Covid Tracker app")
windows.configure(background="#4aacc5")

class dayCalendar(tk.Toplevel):

    def __init__(self,dia,master= None, *args, **kwargs):
        super().__init__(master = master)
        nday=dia.day
        if nday==1:
            sufix="st"
        elif nday==2:
            sufix="nd"
        elif nday==3:
            sufix="rd"
        else:
            sufix="th"

        header=f'{dia.month} {nday}{sufix}'
        self.dayLabel=tk.Label(self,text=header)
        self.dayLabel.grid(row=0)

        row=1
        for hour in dia.hours:

            if hour.disp:

                temp=tk.Button(self,text=hour.hour,foreground="black",command=lambda mem=hour:self.reservate(mem))
            else:
                temp=tk.Label(self,text=hour.hour,foreground="grey")

            temp.grid(row=row)
            row+=1

    def reservate(self,hour):

        ask=messagebox.askokcancel(title="Reservation confirmation",message="Do you wish to reserve?")

        if ask:
            hour.reservation()

class monthCalendar(tk.Toplevel):

    def __init__(self,mes,master= None, *args, **kwargs):

        super().__init__(master = master)
        self.monthLabel=tk.Label(self,text=mes.month)
        self.monthLabel.grid(row=0,columnspan=7)
        nD=1

        for setmana in range(5):

            for dia in range(7):

                if nD>mes.nDays:
                    temp=tk.Label(self,text="")

                else:
                    if nD<10:

                        temp=tk.Button(self,text=" "+str(nD)+" ",command=lambda mem=mes.days[nD-1]:dayCalendar(mem))
                    else:
                        temp=tk.Button(self,text=nD,command=lambda mem=mes.days[nD-1]:dayCalendar(mem))

                temp.grid(row=setmana+1,column=dia)
                nD+=1

class yearCalendar(tk.Toplevel):

    def __init__(self,master=None):
        super().__init__(master = master)
        self.yearLabel=tk.Label(self,text=Any)
        self.yearLabel.grid(columnspan=4)

        nM=0
        for row in range(1,4):
            for column in range(4):
                mes=calendari.monthsList[nM]
                temp=tk.Button(self,text=mes.month,command=lambda mem=mes : monthCalendar(mem))
                temp.grid(row=row,column=column,sticky="news")
                nM+=1

titleFrame=tk.Frame(windows,width=0.9*amplada,height=0.10*altura,background="#012160")
calendarFrame=tk.Frame(windows,width=0.4*amplada,height=0.10*altura,background="#8064a1")
casesFrame=tk.Frame(windows,width=0.4*amplada,height=0.10*altura,background="#b4d69b")
symptomsFrame=tk.Frame(windows,width=0.4*amplada,height=0.10*altura,background="#1f477c")
settingsFrame=tk.Frame(windows,width=0.4*amplada,height=0.10*altura,background="#f79646")

title=tk.Label(titleFrame,text="Covid Tracker", background="#012160", foreground="#ffffff")

calendar=tk.Button(calendarFrame, text="                     Calendar                  ", background="#8064a1", foreground="#ffffff",command=yearCalendar)
cases=tk.Button(casesFrame, text="                 Covid Cases               ", background="#b4d69b", foreground="#ffffff")
symptoms=tk.Button(symptomsFrame, text="                 Symptoms                  ", background="#1f477c", foreground="#ffffff")
settings=tk.Button(settingsFrame, text="                   Settings                    ", background="#f79646", foreground="#ffffff")

titleFrame.place(x=0.05*amplada, y=0.1*altura)
titleFrame.pack_propagate(0)
title.config(font=("Times New Roman",35))
title.pack()

calendarFrame.place(x=0.55*amplada, y=0.35*altura)
calendarFrame.pack_propagate(0)
calendar.config(font=("Times New Roman",30))
calendar.pack()

casesFrame.place(x=0.05*amplada, y=0.35*altura)
casesFrame.pack_propagate(0)
cases.config(font=("Times New Roman",30))
cases.pack()

symptomsFrame.place(x=0.55*amplada, y=0.7*altura)
symptomsFrame.pack_propagate(0)
symptoms.config(font=("Times New Roman",30))
symptoms.pack()

settingsFrame.place(x=0.05*amplada, y=0.7*altura)
settingsFrame.pack_propagate(0)
settings.config(font=("Times New Roman",30))
settings.pack()

windows.mainloop()


from tensorflow import keras
import tensorflow as tf
from utils import *

class Train_Evaluate_Deep():

  def __init__(self,
               predictions={},
               results={}):

      self.predictions = predictions
      self.results = results

  def build_cnn(self, input_size, units=128, drop_rate=0.25, filter=32, kernel_size=(1*9), output_size=1):
    input = keras.layers.Input((input_size))
    x = keras.layers.Conv1D(filters=filter//2, kernel_size=kernel_size, padding='same', activation='relu', name="conv1")(input)
    x = keras.layers.Conv1D(filters=filter, kernel_size=kernel_size, padding='same', activation='relu', name="conv2")(x)
    x = keras.layers.Conv1D(filters=filter*2, kernel_size=kernel_size, padding='same', activation='relu', name="conv3")(x)
    x = tf.keras.layers.Flatten()(x)
    classifier = keras.layers.Dense(units*4, activation='relu')(x)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(units, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(units//2, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    output = keras.layers.Dense(output_size, activation='sigmoid')(classifier)
    model = keras.Model(inputs=input, outputs=output)
    return model

  def build_lstm(self, input_size, units=128, drop_rate=0.25, lstm_units=16, output_size=1):
    input = keras.layers.Input((input_size))
    x = keras.layers.LSTM(units=lstm_units//2, input_shape=input_size, return_sequences=True, name="lstm1")(input)
    x = keras.layers.LSTM(units=lstm_units, input_shape=input_size, return_sequences=True, name="lstm2")(x)
    x = keras.layers.LSTM(units=lstm_units*2, input_shape=input_size, return_sequences=True, name="lstm3")(x)
    x = tf.keras.layers.Flatten()(x)
    classifier = keras.layers.Dense(units*4, activation='relu')(x)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(units, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(units//2, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    output = keras.layers.Dense(output_size, activation='sigmoid')(classifier)
    model = keras.Model(inputs=input, outputs=output)
    return model

  def build_mlp(self, input_size, hidden_layer_size=128, output_size=1, drop_rate=0.25):
    input = keras.layers.Input((input_size))
    x = keras.layers.Dense(hidden_layer_size//4, activation='relu')(input)
    x = keras.layers.Dense(hidden_layer_size//2, activation='relu')(x)
    x = keras.layers.Dense(hidden_layer_size, activation='relu')(x)
    x = tf.keras.layers.Flatten()(x)
    classifier = keras.layers.Dense(hidden_layer_size*4, activation='relu')(x)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(hidden_layer_size, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    classifier = keras.layers.Dense(hidden_layer_size//2, activation='relu')(classifier)
    classifier = keras.layers.Dropout(drop_rate)(classifier)
    output = keras.layers.Dense(output_size, activation='sigmoid')(classifier)
    model = keras.Model(inputs=input, outputs=output)
    return model

  def build_AE(self, input_size, latent_dim=128, filter=64, kernel_size=(1*9)):
    input = keras.layers.Input((input_size))
    encoder = keras.layers.Conv1D(filters=filter//2, kernel_size=kernel_size, padding='same', activation='relu', name="conv1")(input)
    encoder = keras.layers.Conv1D(filters=filter, kernel_size=kernel_size, padding='same', activation='relu', name="conv2")(encoder)
    encoder = tf.keras.layers.Flatten()(encoder)
    encoder = keras.layers.Dense(latent_dim*4, activation='relu')(encoder)
    encoder = keras.layers.Dense(latent_dim*2, activation='relu')(encoder)

    latent = keras.layers.Dense(latent_dim, activation='relu')(encoder)

    decoder = keras.layers.Dense(latent_dim*2, activation='relu')(latent)
    decoder = keras.layers.Dense(latent_dim*4, activation='relu')(decoder)
    decoder = keras.layers.Dense(filter*input_size[0], activation='relu')(decoder)
    decoder = keras.layers.Reshape((input_size[0], filter))(decoder)
    decoder = keras.layers.Conv1DTranspose(filters=filter, kernel_size=kernel_size, padding='same', activation='relu')(decoder)
    decoder = keras.layers.Conv1DTranspose(filters=filter//2, kernel_size=kernel_size, padding='same', activation='relu')(decoder)

    output = keras.layers.Conv1DTranspose(filters=input_size[-1], kernel_size=kernel_size, padding='same', activation='relu')(decoder)
    model = keras.Model(inputs=input, outputs=output)
    return model

  def train_deep_model(self,
                       model,
                       X_train,
                       y_train,
                       metrics,
                       loss_function,
                       optimizer,
                       callbacks,
                       class_weight=None,
                       epochs=100,
                       batch_size=128,
                       validation_split=0.2):

    print('----------------------------------')
    print(model.summary())
    print('----------------------------------')

    model.compile(optimizer=optimizer,
                  loss=loss_function,
                  metrics=metrics)

    if not class_weight is None:
      history = model.fit(X_train,
                          y_train,
                          batch_size = batch_size,
                          epochs = epochs,
                          shuffle = True,
                          class_weight = class_weight,
                          validation_split = validation_split,
                          callbacks = callbacks,
                          verbose = 1)
    else:
      history = model.fit(X_train,
                          y_train,
                          batch_size = batch_size,
                          epochs = epochs,
                          shuffle = True,
                          validation_split = validation_split,
                          callbacks = callbacks,
                          verbose = 1)
    return history

  def evaluate(self, model, X_test, y_test, batch_size=128, threshold=0.5, title='', model_name='', plot=True):
    prediction = model.predict(X_test, batch_size=batch_size)
    self.predictions[model_name] = prediction
    prediction = np.where(prediction >= threshold, 1, 0)
    if plot:
      print()
      print('1) Plot ROC Curve...')
      print()
      plot_roc_curve(y_test, prediction, title='ROC Curve of {model_name} Model'.format(model_name=model_name), model_name=model_name, file_name=None)
      print()
      print('2) Plot AUC Curve...')
      print()
      plot_auc_curve(y_test, prediction, title='AUC Curve of {model_name} Model'.format(model_name=model_name), model_name=model_name, file_name = None)
      print()
      print('3) Plot Percision_Recall Curve......')
      print()
      plot_precision_recall_curve(y_test, prediction, title='Percision_Recall Curve of {model_name} Model'.format(model_name=model_name), model_name=model_name, file_name=None)
    report = classification_report(y_test, prediction, output_dict=True)
    self.results[model_name] = report
    print()
    plot_confusion_matrix(confusion_matrix(y_test, prediction), title=title)
    print()
    return prediction

  def plot_learning_curves(self, history):
    print('1) Plot learning process based on different metrics...')
    print()
    plot_metrics(history)
    print()
    print('2) Plot learning curve...')
    print()
    return plot_history(history)


"""ola"""
import json
import requests
from app import app

token_whats = app.config['API_KEY_WHATS']
verify_token = app.config['VERIFY_TOKEN']

def send_msg(phone_number_id, from_number, respons):
    """ola"""
    payload = json.dumps({
        'messaging_product': 'whatsapp',
        "recipient_type": "individual",
        'to': from_number,
        "type": "text",
        'text': {
            "preview_url": False,
            'body': respons}
    })
    headers = {
        'Content-Type': 'application/json'
    }

    requests.post(
        f'https://graph.facebook.com/v16.0/{phone_number_id}/messages?access_token={token_whats}',
        headers=headers,
        data=payload
    )

def verify_webhook(mode, token, challenge):
    """ola"""
    if mode and token:
        if mode == 'subscribe' and token == verify_token:
            print('WEBHOOK_VERIFIED')
            return challenge, 200
        else:
            return 'Verification token mismatch', 403
    else:
        return 'Bad request', 400


# 343. Integer Break
# Medium
# 3.6K
# 364
# Companies
# Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

# Return the maximum product you can get.

# Example 1:
# Input: n = 2
# Output: 1
# Explanation: 2 = 1 + 1, 1 × 1 = 1.

# Example 2:
# Input: n = 10
# Output: 36
# Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

class Solution:
    def integerBreak(self, n: int) -> int:
        dp = [0] * (n + 1)
        dp[2] = 1
        for i in range(3, n + 1):
            for j in range(1, int(n / 2 + 1)):
                dp[i] = max(dp[i], (i - j) * j, dp[i - j] * j)
        return dp[-1]

solution = Solution()
answ = solution.integerBreak(10)

print(answ)


import unittest
import mock

from .const import SQLConstant

from . import parse

def mock_type_parser(lex):
    lex.expect('TYPE')
    return SQLConstant('TYPE')

def mock_parse_expression(lex):
    return SQLConstant(lex.parse_identifier())

class TestParser(unittest.TestCase):

    def assert_sql(self, val, fsql):
        expr = parse(val)
        self.assertEqual(str(expr), fsql)

        nsql = expr.as_sql(False)
        nexpr = parse(nsql)
        self.assertEqual(str(expr), str(nexpr))

    def test_basic_sql(self):
        self.assert_sql('/* x */ select E1 as x, E2, E3 as i',
                        'SELECT E1 AS x,E2,E3 AS i;')

    def test_select(self):
        self.assert_sql('/* x */ select EXPR as x, EXPR, EXPR as i',
                        'SELECT EXPR AS x,EXPR,EXPR AS i;')
        self.assert_sql('select EXPR as fieldA where EXPR group by fieldA',
                        'SELECT EXPR AS fieldA WHERE EXPR GROUP BY fieldA;')
        self.assert_sql('/* x */ select EXPR as x, EXPR, EXPR as i',
                        'SELECT EXPR AS x,EXPR,EXPR AS i;')
        self.assert_sql('SELECT EXPR UNION ALL SELECT EXPR',
                        'SELECT EXPR UNION ALL SELECT EXPR;')

    def test_withselect(self):
        self.assert_sql('with x as (select E1) select E2 as fieldA '
                        'where WEXPR group by fieldA;',
                        'WITH x AS(SELECT E1)SELECT E2 AS fieldA '
                        'WHERE WEXPR GROUP BY fieldA;')

    # TODO(scannell): Generate SQL for user defined functions as well!
    @mock.patch('sql_parser.types.SQLType.parse',
                mock.MagicMock(side_effect=mock_type_parser))
    def test_function(self):
        self.assert_sql('CREATE TEMPORARY FUNCTION TO_STRING(x TYPE) AS'
                        ' FExpr; SELECT F;',
                        'CREATE TEMPORARY FUNCTION TO_STRING(x TYPE)'
                        'AS FExpr;SELECT F;')
        self.assert_sql('CREATE TEMPORARY FUNCTION stuff(x TYPE) '
                        'RETURNS TYPE '
                        'LANGUAGE js AS """ javascript stuff """;'
                        'SELECT F;',
                        'CREATE TEMPORARY FUNCTION stuff(x TYPE)'
                        'RETURNS TYPE LANGUAGE '
                        'js AS \' javascript stuff \';SELECT F;')

    def test_order_by(self):
        self.assert_sql('SELECT x FROM t ORDER BY tx,tb ASC',
                        'SELECT x FROM t ORDER BY tx,tb ASC;')
        self.assert_sql('SELECT x FROM t ORDER BY tx DESC,tb ASC',
                        'SELECT x FROM t ORDER BY tx DESC,tb ASC;')

    def test_limit_offset(self):
        self.assert_sql('SELECT x FROM t LIMIT 10', 'SELECT x FROM t LIMIT 10;')
        self.assert_sql('SELECT x FROM t LIMIT 10 OFFSET 10',
                        'SELECT x FROM t LIMIT 10 OFFSET 10;')

    def test_query_table(self):
        self.assert_sql('SELECT E1 FROM(SELECT stuff FROM t)f',
                        'SELECT E1 FROM(SELECT stuff FROM t)AS f;')

    def test_sub_query(self):
        self.assert_sql('(SELECT F1 FROM stuff)ORDER BY F2',
                        '(SELECT F1 FROM stuff)ORDER BY F2;')
        self.assert_sql('(SELECT F1 FROM stuff ORDER BY f)ORDER BY F2',
                        '(SELECT F1 FROM stuff ORDER BY f)ORDER BY F2;')
        self.assert_sql('select F1 FROM stuff ORDER BY F2',
                        'SELECT F1 FROM stuff ORDER BY F2;')

    def test_having(self):
        self.assert_sql('SELECT Fx FROM t GROUP BY Tx HAVING E1',
                        'SELECT Fx FROM t GROUP BY Tx HAVING E1;')

    def test_select_type(self):
        self.assert_sql('SELECT DISTINCT f FROM t', 'SELECT DISTINCT f FROM t;')
        self.assert_sql('SELECT ALL f FROM t', 'SELECT ALL f FROM t;')

    def test_sets(self):
        self.assert_sql('SELECT x FROM t UNION ALL SELECT x FROM t',
                        'SELECT x FROM t UNION ALL SELECT x FROM t;')
        self.assert_sql('SELECT x FROM t UNION DISTINCT SELECT x FROM t',
                        'SELECT x FROM t UNION DISTINCT SELECT x FROM t;')
        self.assert_sql('SELECT x FROM t INTERSECT DISTINCT SELECT x FROM t',
                        'SELECT x FROM t INTERSECT DISTINCT SELECT x FROM t;')
        self.assert_sql('SELECT x FROM t EXCEPT DISTINCT SELECT x FROM t',
                        'SELECT x FROM t EXCEPT DISTINCT SELECT x FROM t;')

    # TODO(scannell)
    # Sub-query as table
    def test_select_expr(self):
        self.assert_sql('SELECT X FROM Y WHERE F IN (SELECT A FROM B)',
                        'SELECT X FROM Y WHERE F IN(SELECT A FROM B);')
        self.assert_sql('SELECT (SELECT 1)',
                        'SELECT(SELECT 1);')

    def test_join(self):
        self.assert_sql('SELECT X FROM Table Y JOIN Table X ON Expr1',
                        'SELECT X FROM Table AS Y INNER JOIN Table AS X '
                        'ON Expr1;')
        self.assert_sql('SELECT X FROM Table Y LEFT JOIN Table X',
                        'SELECT X FROM Table AS Y LEFT JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y INNER JOIN Table X',
                        'SELECT X FROM Table AS Y INNER JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y CROSS JOIN Table X',
                        'SELECT X FROM Table AS Y CROSS JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y, Table X',
                        'SELECT X FROM Table AS Y CROSS JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y LEFT OUTER JOIN Table X',
                        'SELECT X FROM Table AS Y LEFT OUTER JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y RIGHT OUTER JOIN Table X',
                        'SELECT X FROM Table AS Y RIGHT OUTER JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y RIGHT JOIN Table X',
                        'SELECT X FROM Table AS Y RIGHT JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y FULL OUTER JOIN Table X',
                        'SELECT X FROM Table AS Y FULL OUTER JOIN Table AS X;')
        self.assert_sql('SELECT X FROM Table Y FULL JOIN Table X',
                        'SELECT X FROM Table AS Y FULL JOIN Table AS X;')

    def test_truncate(self):
        self.assert_sql('TRUNCATE  TABLE /* b */ tt;',
                        'TRUNCATE TABLE tt;')
        self.assert_sql('truncate table td_address',
                        'TRUNCATE TABLE td_address;')

    def test_multiple(self):
        self.assert_sql('TRUNCATE  TABLE /* b */ tt;  SELECT  1;',
                        'TRUNCATE TABLE tt;SELECT 1;')

    def test_insert(self):
        self.assert_sql('INSERT INTO TABLE (a,b,c) SELECT 1,2;',
                        'INSERT INTO TABLE(a,b,c)SELECT 1,2;')
        self.assert_sql('INSERT INTO TABLE (SELECT 1,2);',
                        'INSERT INTO TABLE(SELECT 1,2);')

    def test_generate_stats(self):
        self.assert_sql('GENERATE   STATistics on blah;',
                        'GENERATE STATISTICS ON blah;')
        self.assert_sql('GROOM TABLE x RECORDS ALL;',
                        'GROOM TABLE x RECORDS ALL;')

    def test_update(self):
        self.assert_sql('UPDATE x SET f1=1, f2=a+b FROM y WHERE TRUE',
                        'UPDATE x SET f1=1,f2=a+b FROM y WHERE TRUE;')

    def test_trans(self):
        self.assert_sql('BEGIN;', 'BEGIN;')

    def test_sql_expr(self):
        self.assert_sql('select ((select 1) + 2)',
                        'SELECT((SELECT 1)+2);')

    def test_sql_delete(self):
        self.assert_sql('DELETE from y where true',
                        'DELETE FROM y WHERE TRUE;')

    def test_sql_create(self):
        self.assert_sql('CREATE OR replace TABLE y (i INT64, b BOOL) AS SELECT 1',
                        'CREATE OR REPLACE TABLE y(i INT64,b BOOL)AS SELECT 1;')


from random import randint

from PyQt5 import QtWidgets, QtCore, QtGui

from src.games.button_shooter.form_widget import FormWidget
from src.database_managers.game_database_management import GameDatabaseManagement
from src.games.game import Game

class ButtonShooterWindow(Game, FormWidget, QtWidgets.QWidget):
    database_path = "src/databases/button_shooter.csv"
    header = ["unlocked_level", "hit_targets"]
    default_values = [1, 0]
    max_level = 20

    def __init__(self, username):
        QtWidgets.QWidget.__init__(self)
        self.countdown = None
        self.game_database = None
        self.hit_targets = None
        self.missed_targets = None
        self.required_targets = None
        self.selected_button = None
        self.selected_level = None
        self.timer = None
        self.data_to_update = {"hit_targets": "hit_targets"}
        self.initialize_database(username)

    def initialize_database(self, username):
        self.game_database = GameDatabaseManagement(self.database_path, username, self.header)
        self.game_database.initialize_user_account(self.default_values)

    def play_game(self, selected_level):
        self.initialize_game(selected_level)
        self.show()
        text = f"Required Targets: {self.required_targets}.\nDo you want to start?"
        user_decision = self.show_start_screen(text)
        if user_decision == QtWidgets.QMessageBox.AcceptRole:
            self.timer.start(1000)
            self.show_buttons()
        elif user_decision == QtWidgets.QMessageBox.RejectRole:
            self.emit_game_menu_signal()

    def initialize_game(self, selected_level):
        self.countdown = 100
        self.hit_targets = 0
        self.missed_targets = 0
        self.required_targets = self.get_required_target(selected_level)
        self.selected_level = selected_level
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update_timer)
        FormWidget.__init__(self, self, self.selected_level, self.countdown)
        Game.__init__(self, self.game_database, self.selected_level)
        self.connect_buttons_to_game()

    @staticmethod
    def get_required_target(level):
        return level * 5 + 50

    def update_timer(self):
        self.countdown -= 1
        self.countdown_label.setText(f"Time left: {self.countdown}")
        if self.countdown == 0:
            self.timer.stop()
            self.end_the_game()

    def update_values(self):
        values = self.game_database.get_values()
        updated_values = {}
        for header_name, variable_name in self.data_to_update.items():
            value = getattr(self, variable_name)
            if value > values[header_name]:
                updated_values[header_name] = value
        self.game_database.update_values(updated_values)

    def end_the_game(self):
        self.update_values()
        if self.hit_targets >= self.required_targets:
            if self.selected_level == self.max_level:
                self.show_every_level_completed()
                self.emit_game_menu_signal()
            else:
                self.unlock_next_level(self.selected_level)
                text = f"Congratulation you won!\nYou hit {self.hit_targets} targets and you missed " \
                       f"{self.missed_targets} targets."
                user_decision = self.show_selection_for_next_game(text)
                self.game_database.save_user_data()
                if user_decision == QtWidgets.QMessageBox.AcceptRole:
                    self.emit_game_menu_signal()
                elif user_decision == QtWidgets.QMessageBox.RejectRole:
                    self.emit_play_next_level_signal()
        else:
            self.game_database.save_user_data()
            text = f"Unfortunately you lost! You only hit {self.hit_targets} targets of required " \
                   f"{self.required_targets} targets. You missed {self.missed_targets} targets."
            user_decision = self.show_losing_screen(text)
            if user_decision == QtWidgets.QMessageBox.DestructiveRole:
                self.emit_level_menu_signal()
            elif user_decision == QtWidgets.QMessageBox.AcceptRole:
                self.emit_game_menu_signal()
            elif user_decision == QtWidgets.QMessageBox.RejectRole:
                self.emit_play_level_again_signal()

    def connect_buttons_to_game(self):
        self.game_menu_button.clicked.connect(self.emit_game_menu_signal)
        self.level_selection_button.clicked.connect(self.emit_level_menu_signal)
        for button in self.button_list:
            button.clicked.connect(self.is_clicked_button_the_proper_target)

    def is_clicked_button_the_proper_target(self):
        if self.sender() is self.selected_button:
            self.change_button_background(self.selected_button, self.palette().color(QtGui.QPalette.Background))
            self.show_buttons()
            self.hit_targets += 1
            self.hit_target_label.setText(f"Hit Targets: {self.hit_targets}")
        else:
            self.change_button_background(self.selected_button, self.palette().color(QtGui.QPalette.Background))
            self.show_buttons()
            self.missed_targets += 1

    @staticmethod
    def change_button_background(button, color):
        button.setStyleSheet(f"background-color: {color}")

    def show_buttons(self):
        self.selected_button = self.button_list[randint(0, len(self.button_list)-1)]
        self.change_button_background(self.selected_button, "red")


from random import choice

from src.Pair import pair
from src.entity.Entity import Entity
from src.world_component.WorldComponent import WorldComponent

class FieldWorldComponent(WorldComponent):
    around4 = (pair(1, 0), pair(-1, 0), pair(0, 1), pair(0, -1))
    around8 = (pair(1, 0), pair(-1, 0), pair(0, 1), pair(0, -1), pair(1, -1), pair(-1, -1), pair(1, 1), pair(-1, 1))

    def __init__(self, x: int, y: int):
        self._cells: list[list[Entity]] = None
        self._x = x
        self._y = y
        self.clear_all()

    def __iter__(self):
        return self._cells.__iter__()

    def get_has_component_around(self, x, y, t):
        f = []
        for a in FieldWorldComponent.around8:
            x0 = x + a.first
            y0 = y + a.second
            if x0 < 0:
                continue
            if y0 < 0:
                continue
            if x0 >= self.x:
                continue
            if y0 >= self.y:
                continue
            e = self.get(x0, y0)
            if e is not None:
                if e.has(t):
                    f.append(e)
        return f

    def set(self, x: int, y: int, e: Entity):
        e0 = self._cells[y][x]
        if e0 is not None:
            raise KeyError(x, y, e0, e)
        self._cells[y][x] = e

    def get(self, x: int, y: int) -> Entity:
        return self._cells[y][x]

    def get_empty_around(self, x: int, y: int) -> pair[int, int]:
        f = []
        for a in FieldWorldComponent.around8:
            x0 = x + a.first
            y0 = y + a.second
            if x0 < 0:
                continue
            if y0 < 0:
                continue
            if x0 >= self.x:
                continue
            if y0 >= self.y:
                continue
            if self.get(x0, y0) is None:
                f.append(a)

        if len(f) == 0:
            return None

        f = choice(f)
        f = pair(f.first + x, f.second + y)

        return f

    def clear_all(self):
        self._cells = [[None for _ in range(self.x)] for _ in range(self.y)]

    def clear(self, x, y):
        self._cells[y][x] = None

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y


import tkinter as tk
from tkinter import ttk
from typing import Any, Collection, NamedTuple, Sequence

from .style import _Style

def _set_vscrollbar_style(bg: str, slider: str, active_slider: str) -> None:
    """flat, no arrow, bg=color of slider"""
    style = ttk.Style()
    style.theme_use("clam")
    style.layout(
        "Vertical.TScrollbar",
        [
            (
                "Vertical.Scrollbar.trough",
                {
                    "children": [("Vertical.Scrollbar.thumb", {"expand": "1", "sticky": "nswe"})],
                    "sticky": "ns",
                },
            )
        ],
    )
    style.configure(
        "Vertical.TScrollbar",
        background=slider,
        gripcount=0,
        bordercolor=bg,
        troughcolor=bg,
        relief="flat",
        lightcolor=bg,
        darkcolor=bg,
    )
    style.map("Vertical.TScrollbar", background=[("active", active_slider)])

class _Border(NamedTuple):
    bg: str
    size: float
    relief: str

def _get_border(border: _Border, **kwargs: Any) -> dict[str, Any]:
    return dict(highlightbackground=border.bg, highlightthickness=border.size, highlightcolor=border.bg, **kwargs)

# pylint: disable=too-many-ancestors
class _AutoScrollbar(ttk.Scrollbar):
    def set(self, first, last) -> None:
        if float(first) <= 0.0 and float(last) >= 1.0:
            self.grid_remove()
        else:
            self.grid()
        super().set(first, last)

class _VscrollCanvas(tk.Canvas):
    """
    Canvas with an automatic vertical scrollbar
    use _VAutoScrollableCanvas.frame to populate it
    """

    def __init__(self, master: tk.BaseWidget, **kwargs) -> None:
        super().__init__(master, bd=0, highlightthickness=0, **kwargs)  # w/o border
        # set the vertical scrollbar
        vscrollbar = _AutoScrollbar(master, orient="vertical")
        self.config(yscrollcommand=vscrollbar.set, yscrollincrement="2")
        vscrollbar.config(command=self.yview)
        self.scrollbar = vscrollbar
        # position everything
        vscrollbar.grid(row=0, column=1, sticky=tk.NS)
        self.grid(row=0, column=0, sticky=tk.NSEW)
        # Making the canvas expandable
        self.master.grid_rowconfigure(0, weight=1)
        self.master.grid_columnconfigure(0, weight=1)
        # creating the frame attached to self
        self.frame = tk.Frame(self, bg=self["bg"])
        self.create_window(0, 0, anchor=tk.NW, window=self.frame)
        # set the scroll region when the frame content changes
        self.frame.bind("<Configure>", self._on_configure)
        # bind the mousewheel
        self.bind_all("<MouseWheel>", self._on_mousewheel)

    def _on_configure(self, _) -> None:
        w, h = self.frame.winfo_reqwidth(), self.frame.winfo_reqheight()
        self.config(scrollregion=(0, 0, w, h), width=w, height=h)

    def _on_mousewheel(self, event: tk.Event) -> None:
        self.yview_scroll(int(-1 * (event.delta / 12)), "units")

class _Button(tk.Button):
    """
    button with a colored border
    with a mouseover color
    """

    def __init__(self, master: tk.BaseWidget, bg: str, mouseover: str, border: _Border, **kwargs: Any) -> None:
        # create a frame for the border, note: do not pack
        self._frame = tk.Frame(master, bg=bg, **_get_border(border))
        active = dict(activebackground=bg, activeforeground=kwargs.get("fg", "white"))
        # create the button
        super().__init__(self._frame, bg=bg, bd=0, **active, **kwargs)
        super().pack(fill="both", expand=True)
        # handle mouseover
        self.bind("<Enter>", lambda _: self.config(bg=mouseover), add="+")
        self.bind("<Leave>", lambda _: self.config(bg=bg), add="+")

    def grid(self, **kwargs) -> None:
        self._frame.grid(**kwargs)

    def grid_remove(self) -> None:
        self._frame.grid_remove()

    def pack(self, **kwargs) -> None:
        self._frame.pack(**kwargs)

class _ListView(tk.Frame):
    """
    List view with styled content and auto scroll
    Note: set_headers should be called before set_rows
    """

    # pylint: disable=too-many-arguments
    def __init__(self, master: tk.BaseWidget, bg_headers: str, bg_rows: str, bg_separator: str, pad: int) -> None:
        super().__init__(master)
        # headers
        self._frame_headers = tk.Frame(self, bg=bg_headers)
        self._frame_headers.pack(fill="both", expand=True)
        # headers separator
        sep = tk.Frame(self, bg=bg_separator)
        sep.pack(fill="both", expand=True)
        # rows
        frame_rows = tk.Frame(self)
        canvas = _VscrollCanvas(frame_rows, bg=bg_rows)
        self._frame_rows = canvas.frame
        frame_rows.pack(fill="both", expand=True)
        # for use later
        self._bg_headers = bg_headers
        self._bg_rows = bg_rows
        self._bg_separator = bg_separator
        self._pad = pad
        self._widths = []

    @staticmethod
    def _clear(what: tk.BaseWidget) -> None:
        for widget in what.winfo_children():
            widget.destroy()

    def set_headers(self, headers: Collection[_Style]) -> None:
        self._clear(self._frame_headers)
        pad = self._pad
        n_column = len(headers)
        self._widths = [0] * n_column
        for column, text in enumerate(headers):
            label = tk.Label(self._frame_headers, bg=self._bg_headers, **text.to_tk)
            label.grid(row=0, column=column, ipadx=pad, ipady=pad, sticky=tk.NSEW)
            self._widths[column] = max(label.winfo_reqwidth() + pad * 2, self._widths[column])
        self.set_column_widths()

    def set_rows(self, rows: Sequence[Collection[_Style]]) -> None:
        self._clear(self._frame_rows)
        pad = self._pad
        n_column = len(self._widths)
        for row, row_content in enumerate(rows):
            assert len(row_content) == n_column
            for column, text in enumerate(row_content):
                label = tk.Label(self._frame_rows, bg=self._bg_rows, **text.to_tk)
                label.grid(row=row * 2, column=column, ipadx=pad, ipady=pad, sticky=tk.NSEW)
                self._widths[column] = max(label.winfo_reqwidth() + pad * 2, self._widths[column])
                # row separator
                if row != len(rows) - 1:
                    sep = tk.Frame(self._frame_rows, bg=self._bg_separator)
                    sep.grid(row=row * 2 + 1, column=0, columnspan=n_column, sticky=tk.EW)
        if not rows:
            self._frame_rows.config(height=1)
        self.set_column_widths()

    def set_column_widths(self) -> None:
        for column, width in enumerate(self._widths):
            self._frame_headers.columnconfigure(column, minsize=width)
            self._frame_rows.columnconfigure(column, minsize=width)


n = int(input())
arr = []
for _ in range(n):
    arr.append(list(map(int, input().split())))

dp = []

for inner in arr:
    tmp = []
    for num in inner:
        tmp.append(0)
    dp.append(tmp)
dp[0][0] = arr[0][0]

for i in range(1, n):
    for j in range(len(arr[i])):
        if j - 1 >= 0:
            dp[i][j] = max(dp[i-1][j-1] + arr[i][j], dp[i][j])
        if j < len(arr[i]) - 1:
            dp[i][j] = max(dp[i][j], dp[i-1][j] + arr[i][j])

ans = 0
for i in dp[n - 1]:
    ans = max(ans, i)
print(ans)


# Bacon Eggs and Spam

food = {}
num = int(input())

while num > 0:
    people = num

    while people > 0:
        line = input().split()
        name = line[0]

        for x in range(1, len(line)):
            yummy = line[x]

            if yummy not in food.keys():
                food[line[x]] = []
                food[line[x]].append(line[0])
            else:
                food[yummy].append(name)

        people -= 1
    keys = sorted(food.keys())

    for key in keys:
        names = sorted(food[key])
        printout = key + ' '

        for name in names:
            printout += name + ' '

        printout = printout.strip()
        print(printout)

    food.clear()

    num = int(input())


from tvtk.api import tvtk
#创建一个长方体数据源，并且同时设置其长宽高
s = tvtk.CubeSource(x_length = 1.0,y_length = 2.0,z_length = 3.0)
# 使用 Polydatamapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input_connection = s.output_port)
#创建一个 Actor
a = tvtk.Actor(mapper = m)
#创建一个 Renderer，将 Actor添加进去
r = tvtk.Renderer(background = (0,0,0))
r.add_actor(a)
#＃创建一个 Renderwindow（窗口），将 Renderer添加进去
w = tvtk.RenderWindow(size = (300,300))
w.add_renderer(r)
#创建一个 Renderwindowinteractor（窗口的交互工具）
i = tvtk.RenderWindowInteractor(render_window = w)
#开启交互
i.initialize()
i.start()


import itertools
import json
import logging
from recordtype import recordtype
import requests

Department = recordtype('Department', ['id', 'name', 'superdepartment'])
Office = recordtype('Office', ['id', 'city', 'country', 'address'])
Employee = recordtype('Employee', ['id', 'first', 'last', 'manager', 'department', 'office'])

class Collection:

    def __init__(self):
        self._data = {}

    def add(self, elem):
        self._data[elem.id] = elem

    def adds(self, elems):
        self._data.update([(e.id, e) for e in elems])

    def get(self, limit, offset, expand=None):
        self._validate_params(limit, offset)
        max = len(self._data) if limit > len(self._data) else limit
        return [self._data.get(k) for k in range(offset + 1, max + 1)]

    def get_by_id(self, id, expand=None):
        return self._data.get(id)

    def _validate_params(self, limit, offset):
        if offset < 0:
            raise RuntimeError('Offset must be a positive number')
        if limit < 1 or limit > 1000:
            raise RuntimeError('Limit must be higher than 0 and less than 1000')

class EmployeesCollection(Collection):

    _URL = 'https://rfy56yfcwk.execute-api.us-west-1.amazonaws.com/bigcorp/employees'

    _IDS_PER_REQUEST = 100

    def __init__(self):
        super().__init__()
        self._pending_managers = set([])

    def _chunked_iterable(self, iterable, size):
        """Iterates iterable in chunks of size"""
        i = iter(iterable)
        while True:
            chunk = tuple(itertools.islice(i, size))
            if not chunk:
                break
            yield chunk

    def _get(self, params):
        return requests.get(self._URL, params).json()

    def _get_by_id(self, params):
        logging.info('Retrieving: {}'.format(str(['id={}'.format(p) for i, p in params])))
        return self._get(params)

    def _build_employee(self, json):
        office = Offices.get_by_id(json['office'])
        department = Departments.get_by_id(json['department'])
        return Employee(json['id'], json['first'], json['last'], json['manager'], department, office)

    def _process_employees(self, employees):
        """Build employees objects from json dict and store them"""
        for e in employees:
            employee = self._build_employee(e)
            manager = super().get_by_id(e['manager'])
            if e['manager'] and not manager:
                logging.info('Manager {} not found in collection'.format(e['manager']))
                self._pending_managers.add(e['manager'])
            else:
                employee.manager = manager
            super().add(employee)

    def _clear_collection(self):
        self._data = {}
        self._pending_managers = set([])

    def _process_response(self, data, expand):
        """Store the employees from json dict and retrieve pending managers"""
        self._clear_collection()
        self._process_employees(data)
        manager_count = max([sum(1 for m in e.split('.') if m == 'manager') for e in expand], default=0)
        self._retrieve_pending(manager_count+1)

    def get(self, limit, offset, expand=[]):
        self._validate_params(limit, offset)
        data = self._get({'limit': limit, 'offset': offset})
        self._process_response(data, expand)
        max = len(self._data) if limit > len(self._data) else limit + offset
        return [self._data.get(k) for k in range(offset + 1, max + 1)]

    def get_by_id(self, id, expand=[]):
        data = self._get_by_id([('id', id)])
        self._process_response(data, expand)
        return super().get_by_id(id)

    def _update_pending_managers(self, managers):
        """Update manager objects on stored employees"""
        for manager in managers:
            obj = super().get_by_id(manager)
            for k, v in self._data.items():
                if v.manager == manager:
                    v.manager = obj

    def _retrieve_pending(self, levels=0):
        """Retrieve pending managers using _pending_managers"""
        if levels:
            pending_managers = list(self._pending_managers)
            logging.info('Pending managers to retrieve: {} - level {}'.format(len(pending_managers), levels))
            self._pending_managers = set([])
            for chunks in self._chunked_iterable(pending_managers, self._IDS_PER_REQUEST):
                params = [('id', manager) for manager in chunks]
                data = self._get_by_id(params)
                self._process_employees(data)
                self._update_pending_managers(chunks)

            if self._pending_managers and levels > 0:
                self._retrieve_pending(levels-1)

def _load_data_from_files():
    departments = Collection()
    offices = Collection()

    with open('data/departments.json') as file:
        for d in json.load(file):
            superdepartment = departments.get_by_id(d['superdepartment'])
            new_department = Department(d['id'], d['name'], superdepartment)
            departments.add(new_department)

    with open('data/offices.json') as file:
        offices.adds(json.load(file, object_hook=lambda o: Office(**o)))

    return departments, offices

Departments, Offices = _load_data_from_files()
Employees = EmployeesCollection()


from ninja import Router
from app_camera.models import CameraSetting
from app_event.models import ColorROIControl
from .util.detect import Color

router = Router()
color = Color()

@router.get('/result/{camera_id}', tags=['color', 'detect'])
def get_color_result(request, camera_id:int):
    from app_camera.apps import AppCameraConfig
    try:
        cam_name = CameraSetting.objects.get(id=camera_id).camera_name
    except:
        return {'is_saved' : False}

    try:
        roi_object = ColorROIControl.objects
        roi_control = roi_object.filter(camera_id=camera_id)
        if len(roi_control) == 0:
            raise f'query empty {roi_control}'
    except:
        roi_object.create(camera_id=camera_id, color_select='red')
        roi_object.create(camera_id=camera_id, color_select='green')
        roi_object.create(camera_id=camera_id, color_select='blue')
        roi_control = roi_object.filter(camera_id=camera_id)
    data = dict()

    for cam, rtsp, name in AppCameraConfig.camera_list:
        if name == cam_name:
            data = cam.q.get()

    if len(data) == 0 :
        print('color data missing')
        print(AppCameraConfig.camera_list)
        return {'is_saved' : False}

    is_alive = data['is_alive']
    if not is_alive:
        print(f'is_alive : {is_alive}')
        return {'is_saved' : False}

    image = data['image']
    roi_list = list()
    for roi in roi_control:
        roi_list.append((roi.color_x, roi.color_y, roi.color_w, roi.color_h))

    JSON = color.color(image, roi_list)

    # log save
    from app_log.models import ColorLog
    log = ColorLog.objects
    log.create(
        camera_id = camera_id,
        red = JSON['color']['red'],
        green = JSON['color']['green'],
        blue = JSON['color']['blue'],
    )

    return JSON


# Descrição do Problema
# Conside o seguinte:

# Felipe começa na posição 0km.
# Felipe consegue guardar uma quantidade infinita de água na sua garrafa.
# A cada 1km andado, 1L de água será consumido.
# Felipe não consegue andar adiante com 0L de água.
# Se Felipe chegar no destino com 0L ou mais de água, a jornada é considerada concluída. Da mesma forma, se Felipe chegar em uma parada com 0L de água, ele pode reabastecer.
# Quando para e reabastece, Felipe leva toda a água disponível no local.
# Felipe não é obrigado a reabastecer em parada nenhuma.
# Nenhuma parada ocupa o mesmo lugar que outra.
# As paradas serão dadas em ordem crescente de distância.
# Você deve encontrar, se possível, a menor quantidade de paradas necessárias para se chegar ao destino. Podem haver mais de uma combinação de paradas que chegue ao destino, inclusive mais de uma combinação com o mínimo tamanho possível. Você só precisa descobrir qual é esse tamanho.

# A entrada seguirá o seguinte formato:

# DESTINO AGUA_INICIAL -> Felipe deve caminhar DESTINO kilômetros com AGUA_INICIAL litros iniciais.
# N -> Número N de paradas no meio do caminho.
# Logo ápos virão N linhas da forma:
# POSi CAPi -> Posição da i-ésima parada(POSi) e a quantidade de água disponível na parada (CAPi).
# Constraints
# 1 <= DESTINO <= 4 * 1e6
# 1 <= AGUA_INICIAL <= 8 * 1e5
# 1 <= N <= 8 * 1e5
# 1 <= POSi < DESTINO
# 0 <= CAPi <= 8 * 1e5

import sys
def quick(lista, ini, f):
    if len(lista) == 1:
        return lista #eh pivo
    if ini < f:
        posicao = part(lista, ini, f) #posicao do pivo
        quick(lista, ini, posicao - 1) #o fim eh o pivo - 1
        quick(lista, posicao + 1, f)

def part(lista, inicio, fim):
    pivo = lista[fim][1] #ordenando a qtd de agua
    index = inicio - 1#barra amarela
    for j in range(inicio, fim): #j barra roxa
        if lista[j][1] <= pivo:
            index = index + 1
            lista[index], lista[j] = lista[j], lista[index]
    #trocar a posicao do pivo botando ele no meio
    lista[index+1], lista [fim] = lista[fim], lista[index+1]
    return index+1

def main():

    felipe, felipe_agua = input().split() #um input eu vou pegar a linha inteira
    felipe = int(felipe)
    felipe_agua = int(felipe_agua)
    n = int(input())
    lista = []
    #lista ordenada da qtd de água (do maior, para o menor)
    for i in range(n): #quantidade de linhas que vai ter abaixo dos primeiros valores (2ª linha)
        linha1, linha2 = input().split() #linha1 = posição, linha2 = qtd de agua
        aux = [int(linha1), int(linha2)]
        lista.append(aux) #colocando tudo nessa lista
    quick(lista, 0, len(lista) - 1)
    lista.reverse()

    fim = False
    w = 0
    qtd_parada = 0

    while True:
        if felipe <= felipe_agua:
            print('E preciso no minimo {} paradas para chegar no destino.'.format(qtd_parada))
            fim = True
            return fim
        elif w < len(lista):
            if lista[w][0] <= felipe_agua:
                qtd_parada = qtd_parada +1
                felipe_agua = felipe_agua + lista[w][1]
                del(lista[w])
                w = 0 #zerando a variavel
            else:
                w = w + 1 #se a posicação é menos que a quantidade de agua, eu vou incrementar, indo para onde tem mais agua
        else:
            return fim

if __name__ == '__main__':
    felipe = main()
    if felipe == False:
        print("Nao e possivel chegar no destino, RIP.")


import math

print("Scientific Calculator")
print("Enter 'quit' to exit")

while True:
    # take input from user
    user_input = input("Enter an equation: ")

    # exit program if user enters 'quit'
    if user_input == 'quit':
        break

    # evaluate the expression
    try:
        result = eval(user_input)
    except:
        print("Invalid input")
        continue

    # print the result
    print("Result:", result)


import json
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornado.web import Application
from tornado.httpserver import HTTPRequest
from unittest import mock
import backend.app
from backend.app import make_app
import backend.handlers

class TestMainHandler(AsyncHTTPTestCase):
    def get_app(self):
        with mock.patch("backend.app.setup_db") as _:
            return make_app()

    def test_get_ok(self):
        resp = self.fetch("/")
        assert resp.code == 200

@mock.patch("backend.handlers.frequency_analysis")
@mock.patch("backend.handlers.CELERY")
class TestAnalysisHandler(AsyncHTTPTestCase):
    def get_app(self):
        with mock.patch("backend.app.setup_db") as _:
            return make_app()

    def test_get_missing_task_id(self, *_):
        resp = self.fetch("/tasks")
        assert resp.code == 404

    def test_get_task_not_ready(self, celery_mock, *_):
        task_mock = mock.MagicMock()
        task_mock.ready.return_value = False
        celery_mock.AsyncResult.return_value = task_mock

        resp = self.fetch("/tasks/some-task")
        assert resp.code == 204

    def test_get_task_ready(self, celery_mock, *_):
        task_mock = mock.MagicMock()
        task_mock.ready.return_value = True
        dummy_result = {"done": True}
        task_mock.result = dummy_result
        celery_mock.AsyncResult.return_value = task_mock

        resp = self.fetch("/tasks/some-task")
        assert resp.code == 200
        assert json.loads(resp.body) == dummy_result

    def test_get_task_failure(self, celery_mock, *_):
        task_mock = mock.MagicMock()
        task_mock.ready.return_value = True
        task_mock.result = Exception()
        celery_mock.AsyncResult.return_value = task_mock

        resp = self.fetch("/tasks/some-task")
        assert resp.code == 400

    def test_post_task_malformed_payload(self, *_):
        payload = ["this is", "sparta"]

        resp = self.fetch("/tasks", method="POST", body=json.dumps(payload))
        assert resp.code == 400

    def test_post_task(self, celery_mock, freq_analysis_mock):
        mocked_task = mock.MagicMock()
        mocked_task.id = "dummy-task"
        freq_analysis_mock.delay.return_value = mocked_task

        payload = {"url": "http://dummy.com"}
        resp = self.fetch("/tasks", method="POST", body=json.dumps(payload))
        assert resp.code == 202
        resp_body = json.loads(resp.body)
        assert resp_body["id"] == "dummy-task"

@mock.patch("backend.handlers.Token")
class TestTokensHandler(AsyncHTTPTestCase):
    def get_app(self):
        with mock.patch("backend.app.setup_db") as _:
            return make_app()

    def test_get_(self, mocked_token):
        tokens = [
            {"token": "sparta", "frequency": 2},
            {"token": "tomato", "frequency": 14},
        ]
        total = 10
        mocked_token.get_page.return_value = (tokens, total)

        resp = self.fetch("/tokens?size=2&page1")
        assert resp.code == 200
        resp_body = json.loads(resp.body)
        assert list(  # There's an element with with token==tomato in the list
            filter(lambda x: x["token"] == "tomato", resp_body["tokens"])
        )
        assert resp_body["total"] == total


from sys import argv
from time import sleep, time

import pandas as pd
import requests

def get_pushshift(subreddit_name=None, before=None, after=None, searchType='submission'):
    suffix=''
    if (before is not None):
        suffix += f'&before={before}'
    if (after is not None):
        suffix += f'&after={after}'
    if (subreddit_name is not None):
        suffix += f'&subreddit={subreddit_name}'

    url = f'https://api.pushshift.io/reddit/search/{searchType}?sort=desc&size=1500{suffix}'
    #print('loading '+url)
    r = requests.get(url)
    data = r.json()
    if len(data['data']) > 0:
        prev_end_date = data['data'][-1]['created_utc']
    else:
        prev_end_date = None
    return (data, prev_end_date)

if __name__=="__main__":
    try:
        subreddit_name = str(argv[1]).strip()
    except:
        print('error: please input the name of subreddit as a first argument. ex: python subreddit_downloader.py [subreddit name]')
        exit()

    # scraping posts
    """
    scraping columns:
        data.
            id, title, author, selftext, link_flair_text, created_utc, num_comments, url(attatched url), permalink
    """
    print(f"Scraping posts in subreddit '{subreddit_name}'")
    df_posts = pd.DataFrame([], columns=['id', 'title',  'author', 'selftext', 'link_flair_text', 'created_utc', 'num_comments', 'url', 'permalink'])

    prev_end_date = 9999999999
    while prev_end_date is not None:
        submissions, prev_end_date = get_pushshift(subreddit_name=subreddit_name, before=prev_end_date-1, after='5y', searchType='submission')
        if prev_end_date is not None:
            for post in submissions['data']:
                df_posts.loc[len(df_posts)] = [
                    post.get('id',''), post.get('title',''), post.get('author',''), post.get('selftext',''), post.get('link_flair_text',''),
                    post.get('created_utc',''), post.get('num_comments',''), post.get('url',''), post.get('permalink','')
                    ]
        sleep(1)

    # scraping comments
    """
    scraping columns:
        data.
            id, parent_id, author, body, created_utc, permalink
    """

    print(f"Scraping comments in subreddit '{subreddit_name}'")
    df_comments = pd.DataFrame([], columns=['id', 'parent_id', 'author', 'body', 'created_utc', 'permalink'])

    prev_end_date = 9999999999
    while prev_end_date is not None:
        comments, prev_end_date = get_pushshift(subreddit_name=subreddit_name, before=prev_end_date-1, after='5y', searchType='comment')
        if prev_end_date is not None:
            for comment in comments['data']:
                df_comments.loc[len(df_comments)] = [
                    comment['id'], comment['parent_id'], comment['author'], comment['body'], comment['created_utc'], comment['permalink']
                    ]
        sleep(1)

    # saving to excel files
    time_current = round(time())
    path_save = f"subreddit_{subreddit_name}_{time_current}.xlsx"

    with pd.ExcelWriter(path_save) as writer:
        df_posts.to_excel(writer, sheet_name='posts', index=False)
        df_comments.to_excel(writer, sheet_name='comments', index=False)
    print(f"File was saved with the name of '{path_save}'")


from domain.spectacol import Spectacol

class SpectacolRepo:
    def __init__(self):
        self.spectacole = []
        self.filename = "spectacole.txt"
        self.read_from_file()

    def read_from_file(self):
        """
        Citire din fisier
        pozitia 1 - titlu
        pozitia 2 - artist
        pozitia 3 - gen
        pozitia 4 - durata
        """
        with open(self.filename, 'r') as f:
            for line in f:
                line = line.strip().split(";")
                spectacol = Spectacol(titlu=line[0], artist=line[1], gen=line[2], durata=line[3])
                self.spectacole.append(spectacol)

    def update_file(self):
        """
        scriere in fisier
        """
        with open(self.filename, 'w') as f:
            for spectacol in self.spectacole:
                f.write(str(spectacol)+'\n')

    def add(self, spectacol):
        self.spectacole.append(spectacol)
        self.update_file()

    def update(self, titlu, artist, gen, durata):
        ok = 0
        for spectacol in self.spectacole:
            if spectacol.get_titlu() == titlu and spectacol.get_artist() == artist:
                ok = 1
                spectacol.set_gen(gen)
                spectacol.set_durata(durata)
        if ok:
            self.update_file()
            return True
        return False

    def sortare(self):
        lista = sorted(sorted(self.spectacole, key=lambda x: x.get_artist()), key=lambda x: x.get_titlu(), reverse=False)
        # lista_finala = sorted(lista, key=lambda x: x.get_artist())
        return lista

Semestrul 1/FP/practic FP/rezolvari practic/spectacole/repository/spectacol_repo.py


import sys
import urllib.parse as urlparse

import backoff
from airbyte_cdk.logger import AirbyteLogger
from facebook_business.exceptions import FacebookRequestError
from requests.status_codes import codes as status_codes

logger = AirbyteLogger()

class InstagramAPIException(Exception):
    """General class for all API errors"""

class InstagramExpectedError(InstagramAPIException):
    """Error that we expect to happen, we should continue reading without retrying failed query"""

def retry_pattern(backoff_type, exception, **wait_gen_kwargs):
    def log_retry_attempt(details):
        _, exc, _ = sys.exc_info()
        logger.info(str(exc))
        logger.info(f"Caught retryable error after {details['tries']} tries. Waiting {details['wait']} more seconds then retrying...")

    def should_retry_api_error(exc: FacebookRequestError):
        # Retryable OAuth Error Codes
        if exc.api_error_type() == "OAuthException" and exc.api_error_code() in (1, 2, 4, 17, 341, 368):
            return True

        # Rate Limiting Error Codes
        if exc.api_error_code() in (4, 17, 32, 613):
            return True

        if (
            exc.http_status() == status_codes.INTERNAL_SERVER_ERROR
            and exc.api_error_code() == 1
            and exc.api_error_message() == "Please reduce the amount of data you're asking for, then retry your request"
        ):
            return True

        if (
            exc.http_status() == status_codes.INTERNAL_SERVER_ERROR
            and exc.api_error_code() == 1
            and exc.api_error_message() == "An unknown error occurred"
        ):
            return True

        if exc.http_status() == status_codes.TOO_MANY_REQUESTS:
            return True

        if (
            exc.api_error_type() == "OAuthException"
            and exc.api_error_code() == 10
            and exc.api_error_message() == "(#10) Not enough viewers for the media to show insights"
        ):
            return True

        # Issue 4028, Sometimes an error about the Rate Limit is returned with a 400 HTTP code
        if exc.http_status() == status_codes.BAD_REQUEST and exc.api_error_code() == 100 and exc.api_error_subcode() == 33:
            return True

        if exc.api_transient_error():
            return True

        # The media was posted before the most recent time that the user's account
        # was converted to a business account from a personal account.
        if exc.api_error_type() == "OAuthException" and exc.api_error_code() == 100 and exc.api_error_subcode() == 2108006:
            return False

        return False

    return backoff.on_exception(
        backoff_type,
        exception,
        jitter=None,
        on_backoff=log_retry_attempt,
        giveup=lambda exc: not should_retry_api_error(exc),
        **wait_gen_kwargs,
    )

def remove_params_from_url(url, params):
    parsed = urlparse.urlparse(url)
    query = urlparse.parse_qs(parsed.query, keep_blank_values=True)
    filtered = dict((k, v) for k, v in query.items() if k not in params)
    return urlparse.urlunparse(
        [parsed.scheme, parsed.netloc, parsed.path, parsed.params, urlparse.urlencode(filtered, doseq=True), parsed.fragment]
    )


import csv
import matplotlib.pyplot as plt
import os
import jieba
import jieba.analyse
from wordcloud import WordCloud, STOPWORDS
import numpy    #numpy计算包
from datetime import datetime
import re

#时间与电影数量折线图
def movie_date_amount(fileName):
    #获取每列
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        #print(header_row)
        '''
        for index, column_header in enumerate(header_row):
             print(index, column_header)
        '''
        #对数据进行筛选生成对应坐标数组
        dict1 = {}
        keys,data = [],[]
        for row in reader:
            if row[18] in dict1.keys():
                dict1[row[18]] = dict1[row[18]]+1
            else:
                dict1.setdefault(row[18],1)
        dict1.pop('0')
        for key in dict1.keys():
            keys.append(key)
            data.append(dict1[key])
    #创建画板
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    fig1 = plt.figure(figsize=(30,5))
    plt.xticks(size='small', rotation=90, fontsize=5)
    #plt.plot(横坐标数组，纵坐标数组，颜色)
    plt.plot(keys,data,'red')
    plt.title("年份与电影数量图")
    #plt.show()
    pic_path = "D:/Python_Programs/Lab/result/movie_date_amount.png"
    plt.savefig(pic_path)

#个别国家的时间与电影数量折线图
def area_date_amount(filename):
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        list_Chian = []
        list_USA = []
        list_India = []
        for row in reader:
            if '中国大陆' in row[13]:
                list_Chian.append(row)
            elif '美国' in row[13]:
                list_USA.append(row)
            elif '印度' in row[13]:
                list_India.append(row)
        dict1,dict2,dict3 = {},{},{}
        for list in list_Chian:
            if list[18] in dict1.keys():
                dict1[list[18]] = dict1[list[18]]+1
            else:
                dict1.setdefault(list[18],1)
        for list in list_USA:
            if list[18] in dict2.keys():
                dict2[list[18]] = dict2[list[18]]+1
            else:
                dict2.setdefault(list[18],1)
        for list in list_India:
            if list[18] in dict3.keys():
                dict3[list[18]] = dict3[list[18]]+1
            else:
                dict3.setdefault(list[18],1)
        time,amount1,amount2,amount3 = [],[],[],[]
        for key in dict1.keys():
            time.append(key)
            amount1.append(dict1[key])
        set_index = []
        for index,year in enumerate(time):
            if year in dict2.keys():
                amount2.append(dict2[year])
            else:
                set_index.append(index)
        for it in set_index:
            time.pop(it)
            amount1.pop(it)
            for i in range(len(set_index)):
                set_index[i] -= 1
        set_index2 = []
        for index, year in enumerate(time):
            if year in dict3.keys():
                amount3.append(dict3[year])
            else:
                set_index2.append(index)
        for it in set_index2:
            time.pop(it)
            amount2.pop(it)
            amount1.pop(it)
            for i in range(len(set_index2)):
                set_index2[i] -= 1
        time.pop()
        amount1.pop()
        amount2.pop()
        amount3.pop()
        # 创建画板
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        fig1 = plt.figure(figsize=(15, 5))
        plt.xticks(size='small', rotation=90, fontsize=10)
        # plt.plot(横坐标数组，纵坐标数组，颜色)
        plt.plot(time, amount1, '-',label='中国')
        plt.plot(time, amount2, '-',label='美国')
        plt.plot(time, amount3, '-',label='印度')
        plt.xticks(time)
        plt.xlabel('年份')
        plt.title("各地区年份与电影数量图")
        #显示每条线的label
        plt.legend()
        #plt.show()
        pic_path = "D:/Python_Programs/Lab/result/area_date_amount.png"
        plt.savefig(pic_path)

#语言与电影数量柱状图
def lan_amount(filename):
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        dict1 = {}
        list_lans_amount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        list_lans = ['汉语','英语','法语','德语','韩语','意大利语','日语','葡萄牙语','泰语','罗马尼亚语','阿拉伯语','尼泊尔语','丹麦语','捷克语']
        for row in reader:
            if '汉语' in row[10] or '粤语' in row[10] or '闽南' in row[10] or '藏语' in row[10]:
                list_lans_amount[0] += 1
            elif '英语' in row[10]:
                list_lans_amount[1] += 1
            elif '法语' in row[10]:
                list_lans_amount[2] += 1
            elif '德语' in row[10]:
                list_lans_amount[3] += 1
            elif '韩语' in row[10]:
                list_lans_amount[4] += 1
            elif '意大利语' in row[10]:
                list_lans_amount[5] += 1
            elif '日语' in row[10]:
                list_lans_amount[6] += 1
            elif '葡萄牙语' in row[10]:
                list_lans_amount[7] += 1
            elif '泰语' in row[10]:
                list_lans_amount[8] += 1
            elif '罗马尼亚语' in row[10]:
                list_lans_amount[9] += 1
            elif '阿拉伯语' in row[10]:
                list_lans_amount[10] += 1
            elif '尼泊尔语' in row[10]:
                list_lans_amount[11] += 1
            elif '丹麦语' in row[10]:
                list_lans_amount[12] += 1
            elif '捷克语' in row[10]:
                list_lans_amount[13] += 1
        # 创建画板
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        fig1 = plt.figure(figsize=(15, 6))
        plt.xticks(size='small', rotation=90, fontsize=8)
        # plt.bar(横坐标数组，纵坐标数组)
        plt.bar(list_lans, list_lans_amount,alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='语言与电影数量图', lw=1)
        plt.title("语言与电影数量图")
        plt.legend()
        #plt.show()
        pic_path = "D:/Python_Programs/Lab/result/lan_amount.png"
        plt.savefig(pic_path)

#语言与电影数量饼状图
def lan_amount_pie(filename):
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        dict1 = {}
        list_lans_amount = [0,0,0,0,0,0,0,0,0,0]
        list_lans = ['汉语','英语','法语','德语','韩语','意大利语','西班牙语','日语','瑞典语','其他']
        for row in reader:
            if ('汉语' in row[10]) or ('普通话' in row[10]) or ('粤语' in row[10]) or ('闽南' in row[10])or('上海' in row[10]) or ('藏语' in row[10]) or ('方言' in row[10]) or ('彝语' in row[10]) or ('客家话' in row[10]) or ('武汉话' in row[10]):
                list_lans_amount[0] += 1
            elif '英语' in row[10]:
                list_lans_amount[1] += 1
            elif '法语' in row[10]:
                list_lans_amount[2] += 1
            elif '德语' in row[10]:
                list_lans_amount[3] += 1
            elif '韩语' in row[10]:
                list_lans_amount[4] += 1
            elif '意大利语' in row[10]:
                list_lans_amount[5] += 1
            elif '葡萄牙语' in row[10]:
                list_lans_amount[6] += 1
            elif '日语' in row[10]:
                list_lans_amount[7] += 1
            elif '瑞典语' in row[10]:
                list_lans_amount[8] += 1
            elif row[10] != '':
                list_lans_amount[9] += 1
                if row[10] in dict1.keys():
                    dict1[row[10]] = dict1[row[10]] + 1
                else:
                    dict1.setdefault(row[10], 1)
        # 创建画板
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        fig1 = plt.figure(figsize=(8, 6))
        #plt.xticks(size='small', rotation=90, fontsize=7)
        explode = (0,0,0,0,0,0,0,0,0,0)
        plt.pie(list_lans_amount,explode=explode,labels=list_lans,autopct='%1.1f%%',shadow=False,startangle=150,
                textprops={'fontsize':10,'color':'black'})
        plt.title("语言与电影数量饼状图")
        #plt.show()
        pic_path = "D:/Python_Programs/Lab/result/lan_amount_pie.png"
        plt.savefig(pic_path)

#国家与电影数量柱状图
def area_amount(filename):
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        list_area_amount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        list_areas = ['中国','美国','日本','韩国','印度','意大利','加拿大','西班牙','巴西','英国','德国','法国','俄罗斯','瑞典','澳大利亚']
        for row in reader:
            if '中国' in row[13] :
                list_area_amount[0] += 1
            elif '美国' in row[13]:
                list_area_amount[1] += 1
            elif '日本' in row[13]:
                list_area_amount[2] += 1
            elif '韩国' in row[13]:
                list_area_amount[3] += 1
            elif '印度' in row[13]:
                list_area_amount[4] += 1
            elif '意大利' in row[13]:
                list_area_amount[5] += 1
            elif '加拿大' in row[13]:
                list_area_amount[6] += 1
            elif '西班牙' in row[13]:
                list_area_amount[7] += 1
            elif '巴西' in row[13]:
                list_area_amount[8] += 1
            elif ('英国' in row[13]) or ('爱尔兰' in row[13]):
                list_area_amount[9] += 1
            elif '德国' in row[13]:
                list_area_amount[10] += 1
            elif '法国' in row[13]:
                list_area_amount[11] += 1
            elif '俄罗斯' in row[13]:
                list_area_amount[12] += 1
            elif '瑞典' in row[13]:
                list_area_amount[13] += 1
            elif '澳大利亚' in row[13]:
                list_area_amount[14] += 1

        # 创建画板
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        fig1 = plt.figure(figsize=(15, 6))
        plt.xticks(size='small', rotation=90, fontsize=8)
        # plt.bar(横坐标数组，纵坐标数组)
        plt.bar(list_areas, list_area_amount,alpha=0.5, width=0.3, color='yellow', edgecolor='red', label='国家与电影数量图', lw=1)
        plt.title("国家与电影数量柱状图")
        plt.legend()
        #plt.show()
        pic_path = "D:/Python_Programs/Lab/result/area_amount.png"
        plt.savefig(pic_path)

#评分和电影数柱状图
def score_count(fileName):
    dict1={}
    score,amount = [],[]
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        print(header_row)
        for row in reader:
            if row[6] in dict1.keys():
                dict1[row[6]] += 1;
            elif row[6] != '0.0':
                dict1.setdefault(row[6],1)
        for key in dict1.keys():
            score.append(key)
            amount.append(dict1[key])
    # 创建画板
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    fig1 = plt.figure(figsize=(15, 6))
    plt.xticks(size='small', rotation=90, fontsize=8)
    # plt.bar(横坐标数组，纵坐标数组)
    plt.bar(score, amount, alpha=0.5, width=0.3, color='yellow', edgecolor='red',
             label='评分与电影数量柱状图', lw=1)
    plt.title("评分与电影数量柱状图")
    plt.legend()
    #plt.show()
    pic_path = "D:/Python_Programs/Lab/result/score_count.png"
    plt.savefig(pic_path)

#不同国家每年发行电影的平均评分
def date_averageScover(filename):
    country = ['中国','美国','日本','韩国']
    date = []
    for i in range(1948,2020):
        date.append(i)
    list_Chian = []
    list_USA = []
    list_Japan = []
    with open(fileName, encoding='utf-8', errors='ignore') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        header_row[0] = header_row[0][2:-1]
        for row in reader:
            if '中国' in row[13]:
                list_Chian.append(row)
            elif '美国' in row[13]:
                list_USA.append(row)
            elif '日本' in row[13]:
                list_Japan.append(row);
    Ave_China = []
    Ave_USA = []
    Ave_Japan = []
    for year in date:
        sum,count = 0,0
        average = 0
        for row in list_Chian:
            if (str(year) in row[18]) and (row[6] != '0.0'):
                count += 1
                sum += float(row[6])
        if(count > 0):
            average = sum / count
        Ave_China.append(average)
    for year in date:
        sum,count = 0,0
        average = 0
        for row in list_USA:
            if (str(year) in row[18]) and (row[6] != '0.0'):
                count += 1
                sum += float(row[6])
        if (count > 0):
            average = sum / count
        Ave_USA.append(average)
    for year in date:
        sum,count = 0,0
        average = 0
        for row in list_Japan:
            if (str(year) in row[18]) and (row[6] != '0.0'):
                count += 1
                sum += float(row[6])
        if (count > 0):
            average = sum / count
        Ave_Japan.append(average)
    # 创建画板
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    fig1 = plt.figure(figsize=(15, 5))
    plt.xticks(size='small', rotation=90, fontsize=10)
    # plt.plot(横坐标数组，纵坐标数组，颜色)
    plt.plot(date, Ave_China, '-', label='中国')
    plt.plot(date, Ave_USA, '-', label='美国')
    plt.plot(date, Ave_Japan, '-', label='日本')
    plt.xticks(date)
    plt.xlabel('年份')
    plt.title("部分国家年份与平均评分折线图")
    # 显示每条线的label
    plt.legend()
    #plt.show()
    pic_path = "D:/Python_Programs/Lab/result/date_averageScover.png"
    plt.savefig(pic_path)

#生成豆瓣评分top20的电影csv文件
def createtop20(filename):
    data = csv.reader(open(filename,encoding='utf-8'), delimiter=',')
    sortedlist = sorted(data, key=lambda x: x[6], reverse=True)
    #按评分排列所有影片，取评分前20生成score_top20.csv
    with open("score_top20.csv", "w",encoding='utf-8-sig', newline='') as f:
        fileWriter = csv.writer(f, delimiter=',')
        for i in range (1,21):
            #print(row)
            fileWriter.writerow(sortedlist[i])
    f.close()

#评分top20生成词云
def createwordcloud(filename1,filename2):
    data = csv.reader(open(filename1, encoding='utf-8'), delimiter=',')
    movie_id = []
    for row in data:
        #print(row[0])
        movie_id.append(row[0])
    #根据id对每个top20电影生成词云

    #获取评论
    for id in movie_id:
        data = csv.reader(open(filename2, encoding='utf-8'), delimiter=',')
        txtname = "tmp"+id.encode('utf-8').decode('utf-8-sig')+".txt"
        flag = os.path.exists(txtname)
        if flag != True:
            for row in data:
                if row[2] == id:
                    f = open(txtname, "a", encoding='utf-8-sig')
                    f.write(row[3])

    #生成词云
    for id in movie_id:
        txtname = 'tmp'+id.encode('utf-8').decode('utf-8-sig')+'.txt'
        flag = os.path.exists(txtname)
        if flag:
            data = open(txtname.encode('utf-8').decode('utf-8-sig'), encoding='utf-8-sig').read()
            #print(type(data))
            pattern = re.compile(r'[\u4e00-\u9fa5]+')
            filterdata = re.findall(pattern, data)
            cleaned_comments = ''.join(filterdata)
            # 使用jieba分词进行中文分词,topK为返回关键词个数,withWeight为是否一并返回关键词权重值,默认值为 False
            result=jieba.analyse.textrank(cleaned_comments,topK=80,withWeight=True)
            keywords = dict()
            for i in result:
                keywords[i[0]] = i[1]
            print("删除停用词前", keywords)  # {'演员': 0.18290354231824632, '大片': 0.2876433001472282}
            # 停用词集合
            stopwords = set(STOPWORDS)
            f = open('./StopWords.txt', encoding="utf8")
            while True:
                word = f.readline()
                if word == "":
                    break
                stopwords.add(word[:-1])

            keywords = {x: keywords[x] for x in keywords if x not in stopwords}
            print("\n删除停用词后", keywords)
            # 用词云进行显示,font_path字体路径
            wordcloud = WordCloud(font_path="simhei.ttf", background_color="white",
                                  max_font_size=80, stopwords=stopwords)
            word_frequence = keywords
            myword = wordcloud.fit_words(word_frequence)
            plt.imshow(myword)  # 展示词云图
            plt.axis("off")
            #plt.show()
            pic_path = "D:/Python_Programs/Lab/result/wordcloud"+id.encode('utf-8').decode('utf-8-sig')+'.png'
            plt.savefig(pic_path)

fileName = 'moviedata\movies.csv'
fileName1= 'moviedata\comments.csv'
fileName2 = 'score_top20.csv'
'''
movie_date_amount(fileName)
area_date_amount(fileName)
lan_amount(fileName)
lan_amount_pie(fileName)
area_amount(fileName)
score_count(fileName)
date_averageScover(fileName)
createtop20(fileName)
'''
createwordcloud(fileName2,fileName1)

项目/23组_豆瓣电影数据的爬取、分析与建模/23组_豆瓣电影数据的爬取、分析与建模/数据分析/Data_visualization.py


import pandas as pd
import numpy as np
import scipy as sp
import math as m
import matplotlib.pyplot as plt
import os
import re

#path, dirs, files = next(os.walk("/mnt/partition-2/data/FMO_data/init_1"))
gamma_1 = np.arange(25.0,325.0,25.0) # generate values 25-500 with step-25
lamb_1 = np.arange(10.0,340.0,30.0)
temp_1 = np.arange(30.0,330.0,20.0)
#
file_count = len(gamma_1)*len(lamb_1)*len(temp_1)
print("number of files = ", file_count)
n_traj = file_count;
files = []
for i in range(0,len(gamma_1)):
    for j in range(0,len(lamb_1)):
        for k in range(0,len(temp_1)):
            filename="7_initial-1_wc-" + str(int(gamma_1[i])) + "_lambda-" + str(int(lamb_1[j])) + "_temp-" + str(int(temp_1[k])) + ".npy"
            files.append(filename)
gamma = np.zeros((file_count), dtype=float)
lamb = np.zeros((file_count), dtype=float)
temp = np.zeros((file_count), dtype=float)
initial = np.zeros((file_count), dtype=int)
for i in range(0, file_count):
    # extract the values of gamma, lambda and temperature from the file name
    x = re.split(r'_', files[i])
    y = re.split(r'-', x[1])
    initial[i] = y[1]
    y = re.split(r'-', x[2]) # extracting value of gamma
    gamma[i] = y[1]
    y = re.split(r'-', x[3]) # extract value of lambda
    lamb[i] = y[1]
    y = re.split(r'-', x[4])
    x = re.split(r'.npy', y[1]) # extract value of temperature
    temp[i] = x[0]

# Initialise distances to inf
dists = np.zeros(n_traj, dtype=float)
dists[:] = float('inf')
points_left = np.arange(n_traj);
sample_inds = np.zeros(n_traj, dtype='int')
# choose an initial trajs
selected = 0
print(files[selected])
#print("7_initial-1_wc-" + str(int(gamma[selected])) + "_lambda-" + str(int(lamb[selected])) + "_temp-" + str(int(temp[selected])) + ".npy")
points_left = np.delete(points_left, selected)
for i in range(1, n_traj):
    last_added = sample_inds[i-1]
    k = 0
    dist_to_last_added_point = np.zeros(len(points_left), dtype=float)
    for j in points_left:
        # Find the distance to the last added traj in selected
        # and all the others
        dist_to_last_added_point[k] =  np.sqrt((gamma[last_added] - gamma[j])**2 + (lamb[last_added] - lamb[j])**2 + (temp[last_added] - temp[j])**2)
        k = k + 1
        # If closer, updated distances
    dists[points_left] = np.minimum(dist_to_last_added_point, dists[points_left])
    # We want to pick the one that has the largest nearest neighbour
    # distance to the sampled trajectories
    selected = np.argmax(dists[points_left])
    sample_inds[i] = points_left[selected]
    # update the indices of the left trajectories
    print(files[sample_inds[i]])#, (dists[points_left][selected]))
    points_left = np.delete(points_left, selected)


""" Currency update """
import requests
import xmltodict
from model import currency
import config
from util import backup

_EXECUTED_TODAY = False

def execute(run_backup: bool = True):
    """ Runs currency update """
    global _EXECUTED_TODAY

    if _EXECUTED_TODAY:
        return

    _EXECUTED_TODAY = True

    try:
        # Backup
        if run_backup:
            backup.execute()

        # Currencies from TCMB
        resp = requests.get(config.CONSTANTS["CURRENCY_CONV_URL"], verify=False, timeout=5)
        resp_as_dict = xmltodict.parse(resp.text)

        # Gold conversion
        gold_resp = requests.get(config.CONSTANTS["CURRENY_GOLD_URL"], verify=False, timeout=5)
        pos1 = gold_resp.text.find('name:"Altın",buying:gj,selling:') + 31
        pos2 = gold_resp.text.find(",", pos1)
        gold_price_txt = gold_resp.text[pos1:pos2]
        gold_price = float(gold_price_txt)
        dgc_dict = {
            "@CrossOrder": "0",
            "@Kod": "DGC",
            "@CurrencyCode": "DGC",
            "Unit": "1",
            "Isim": "Gold",
            "CurrencyName": "Gold",
            "ForexBuying": gold_price,
            "ForexSelling": gold_price,
            "BanknoteBuying": gold_price,
            "BanknoteSelling": gold_price
        }
        resp_as_dict["Tarih_Date"]["Currency"].append(dgc_dict)

        # Save
        currency.save_currency_conv(resp_as_dict)

    except Exception as error:
        print(f"Currency update error: {str(error)}")


# Let's represent an integer in a linked list format by having each node represent a digit in the number.
# The nodes make up the number in reversed order.

# For example, the following linked list:

# 1 -> 2 -> 3 -> 4 -> 5
# is the number 54321.

# Given two linked lists in this format, return their sum in the same linked list format.

# For example, given

# 9 -> 9
# 5 -> 2
# return 124 (99 + 25) as:

# 4 -> 2 -> 1

class Node:

    def __init__(self, data = None):
        self.data = data
        self.next = None

    def __str__(self):
        return self.data

class LinkedList:

    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

    def append(self, data):
        node = Node(data)
        if self.tail:
            self.tail.next = node
            self.tail = node
        else:
            self.head = node
            self.tail = node
        self.count += 1

    def iter(self):
        current = self.head
        while current:
            val = current.data
            yield val
            current = current.next

def reverse(n):
    rev = 0
    while n != 0:
        rem = n % 10
        rev = rev * 10 + rem
        n //= 10
    return rev

def solution(r1, r2):
    arr1 = []
    arr2 = []
    arr3 = []

    obj1 = LinkedList()
    obj2 = LinkedList()
    obj3 = LinkedList()

    str1 = list(str(r1))
    str2 = list(str(r2))

    for elm in str1:
        obj1.append(elm)

    print("1st number in reversed format in Linked List: ")
    x = 0
    for i in obj1.iter():
        arr1.append(i)
        x += 1
        print(i, end="")
        if x != obj1.count:
            print("->", end="")

    print("\n")

    for elm in str2:
        obj2.append(elm)

    print("2nd number in reversed format in Linked List: ")
    y = 0
    for i in obj2.iter():
        arr2.append(i)
        y += 1
        print(i, end="")
        if y != obj2.count:
            print("->", end="")

    print("\n")

    n1 = int("".join(arr1[::-1]))
    n2 = int("".join(arr2[::-1]))

    sum = n1 + n2
    rev_sum = reverse(sum)
    print(f"Sum of both numbers in reversed format: {rev_sum}")

    str3 = list(str(rev_sum))

    for elm in str3:
        obj3.append(elm)

    print("\nRepresentation of numbers in sum through Linked List:")
    c = 0
    for i in obj3.iter():
        arr3.append(i)
        c += 1
        print(i, end="")
        if c != obj3.count:
            print("->", end="")
    print("\n")
    return int("".join(arr3[::-1]))

r1 = reverse(int(input("Enter 1st number: ")))
r2 = reverse(int(input("Enter 2nd number: ")))

print(solution(r1, r2))


graph1={0:[1,2],1:[3],2:[3],3:[0]}
graph3={0:[1,2],1:[2],2:[3,4],3:[6],4:[5,6],5:[4],6:[]}
graph2={1:[2],2:[3,13],3:[4],4:[5,7,9],5:[6],6:[2],7:[8],8:[2],9:[10],10:[11,12],11:[3],12:[2],13:[]}
l=[]
s=''
def fin(i,a,l,g):
    c=[]
    for y in a:
        c.append(y)

    if(i in c and i!=c[0]):
        l.append(c)

    elif(i in c and i==c[0]):
               # s=s+i
        c.append(i)
        l.append(c)
    else:
        d=c
        d.append(i)
        if(len(g[i])==0):
            l.append(d)
        else:
            for t in g[i]:
                fin(t,d,l,g)

for key in graph2:
    #s=s+key
    a=[]
    fin(key,a,l,graph2)

#print(l)
temp=[]
tt=[]

for i in l:
    if(i not in temp):
        temp.append(i)
l2=[]
for i in temp:
    l2.append(i)
def compare(p1,p2,tt):
    s1=""
    s2=""
    for i in p1:
        s1=s1+str(i)+","
    for j in p2:
        s2=s2+str(j)+","
    if(s1!=s2 and s1 in s2):
        if(p1 not in tt):
            tt.append(p1)
for p1 in temp:
    for p2 in l2:
        compare(p1,p2,tt)
#print(tt)
for i in tt:
    temp.remove(i)
print(str(len(temp)))
for p in temp:
    print (p)


import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self, imsize):
        super(Net, self).__init__()
        self.downsample = ((imsize-4)/2)
        if self.downsample % 2 == 0:
            self.finalsize = int((self.downsample-4)/2)
        else:
            self.finalsize = int((self.downsample - 5) / 2)
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * self.finalsize * self.finalsize, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * self.finalsize * self.finalsize)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

if __name__ == '__main__':
    net = Net()