from dash_website.app import APP
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import pandas as pd
import numpy as np

from dash_website.utils.aws_loader import load_feather
from dash_website.utils.controls import get_item_radio_items
from dash_website.utils.graphs import (
    heatmap_by_clustering,
    heatmap_by_sorted_dimensions,
    add_custom_legend_axis,
    histogram_correlation,
)
from dash_website import CUSTOM_DIMENSIONS, ORDER_TYPES, GRAPH_SIZE, DOWNLOAD_CONFIG, DIMENSIONS_SUBDIMENSIONS_INDEXES
from dash_website.genetics import DIMENSIONS_TO_DROP_CORRELATIONS

def get_controls_genetics_correlations():
    return dbc.Card(get_item_radio_items("order_type_genetics_correlations", ORDER_TYPES, "Order by:"))

@APP.callback(
    [
        Output("graph_genetics_correlations", "figure"),
        Output("title_genetics_correlations", "children"),
        Output("histogram_genetics_correlations", "figure"),
    ],
    [
        Input("order_type_genetics_correlations", "value"),
        Input("memory_genetics_correlations", "data"),
        Input("memory_scores_genetics_correlations", "data"),
        Input("memory_heritability_genetics_correlations", "data"),
    ],
)
def _fill_graph_genetics_correlations(order_by, data_genetics_correlations, data_scores, data_heritability):
    correlations = pd.DataFrame(data_genetics_correlations)

    scores = pd.DataFrame(data_scores).set_index(["dimension", "subdimension", "sub_subdimension", "algorithm"])
    scores.drop(index=scores.index[~scores.index.isin(CUSTOM_DIMENSIONS)], inplace=True)
    scores.reset_index(["sub_subdimension", "algorithm"], drop=True, inplace=True)

    heritabilities = pd.DataFrame(data_heritability).set_index(["dimension", "subdimension"])

    for number in [1, 2]:
        correlations.set_index([f"dimension_{number}", f"subdimension_{number}"], inplace=True)
        correlations[f"r2_{number}"] = scores["r2"]
        correlations[f"r2_std_{number}"] = scores["r2_std"]
        correlations[f"h2_{number}"] = heritabilities["h2"]
        correlations[f"h2_std_{number}"] = heritabilities["h2_std"]
        correlations.reset_index(inplace=True)

    custom_dimensions = DIMENSIONS_SUBDIMENSIONS_INDEXES.drop(DIMENSIONS_TO_DROP_CORRELATIONS)

    table_correlations = correlations.pivot(
        index=["dimension_1", "subdimension_1"],
        columns=["dimension_2", "subdimension_2"],
        values="correlation",
    ).loc[custom_dimensions, custom_dimensions]
    np.fill_diagonal(table_correlations.values, np.nan)

    customdata_list = []
    for customdata_item in [
        "correlation_std",
        "r2_1",
        "r2_std_1",
        "h2_1",
        "h2_std_1",
        "r2_2",
        "r2_std_2",
        "h2_2",
        "h2_std_2",
    ]:
        customdata_value = (
            correlations.pivot(
                index=["dimension_1", "subdimension_1"],
                columns=["dimension_2", "subdimension_2"],
                values=customdata_item,
            )
            .loc[custom_dimensions, custom_dimensions]
            .values
        )

        if customdata_item == "correlation_std":
            np.fill_diagonal(customdata_value, np.nan)

        customdata_list.append(customdata_value)
    stacked_customdata = list(map(list, np.dstack(customdata_list)))

    customdata = pd.DataFrame(None, index=custom_dimensions, columns=custom_dimensions)
    customdata[customdata.columns] = stacked_customdata

    hovertemplate = "Correlation: %{z:.3f} +- %{customdata[0]:.3f}

Dimensions 1: %{x}
R²: %{customdata[1]:.3f} +- %{customdata[2]:.3f}
h²: %{customdata[3]:.3f} +- %{customdata[4]:.3f}
Dimensions 2: %{y}
R²: %{customdata[5]:.3f} +- %{customdata[6]:.3f}
h²: %{customdata[7]:.3f} +- %{customdata[8]:.3f}
<extra></extra>"

    if order_by == "clustering":
        fig = heatmap_by_clustering(table_correlations, hovertemplate, customdata)
    elif order_by == "r2":
        sorted_dimensions = (
            correlations.set_index(["dimension_1", "subdimension_1"])
            .sort_values(by="r2_1", ascending=False)
            .index.drop_duplicates()
        )

        sorted_table_correlations = table_correlations.loc[sorted_dimensions, sorted_dimensions]
        sorted_customdata = customdata.loc[sorted_dimensions, sorted_dimensions]

        fig = heatmap_by_sorted_dimensions(sorted_table_correlations, hovertemplate, sorted_customdata)

    else:  # order_by == "custom"
        fig = heatmap_by_sorted_dimensions(table_correlations, hovertemplate, customdata)
        fig = add_custom_legend_axis(fig, table_correlations.index)
        fig = add_custom_legend_axis(fig, table_correlations.index, horizontal=False)

    if order_by != "custom":
        fig.update_layout(font={"size": 8})

    fig.update_layout(
        yaxis={"showgrid": False, "zeroline": False},
        xaxis={"showgrid": False, "zeroline": False},
        width=GRAPH_SIZE,
        height=GRAPH_SIZE,
        margin={"l": 0, "r": 0, "b": 0, "t": 0},
    )

    return (
        fig,
        f"Average correlation = {correlations['correlation'].mean().round(3)} +- {correlations['correlation'].std().round(3)}",
        histogram_correlation(table_correlations),
    )

LAYOUT = dbc.Container(
    [
        dcc.Loading(
            [
                dcc.Store(
                    id="memory_genetics_correlations",
                    data=load_feather("genetics/correlations/correlations.feather").to_dict(),
                ),
                dcc.Store(
                    id="memory_scores_genetics_correlations",
                    data=load_feather(
                        "age_prediction_performances/scores_all_samples_per_participant.feather"
                    ).to_dict(),
                ),
                dcc.Store(
                    id="memory_heritability_genetics_correlations",
                    data=load_feather(f"genetics/heritability/heritability.feather").to_dict(),
                ),
            ]
        ),
        html.H1("Genetics - Correlations"),
        html.Br(),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    [
                        get_controls_genetics_correlations(),
                        html.Br(),
                        html.Br(),
                    ],
                    width={"size": 3},
                ),
                dbc.Col(
                    [
                        dcc.Loading(
                            [
                                html.H2(id="title_genetics_correlations"),
                                dcc.Graph(id="graph_genetics_correlations", config=DOWNLOAD_CONFIG),
                            ]
                        )
                    ],
                    width={"size": 9},
                ),
            ]
        ),
        dbc.Row(
            [
                dbc.Col(
                    [
                        dcc.Loading(
                            [
                                html.H4("Histogram of the above correlations"),
                                dcc.Graph(id="histogram_genetics_correlations", config=DOWNLOAD_CONFIG),
                            ]
                        )
                    ],
                    width={"size": 6, "offset": 3},
                ),
            ]
        ),
    ],
    fluid=True,
)


import warnings

warnings.filterwarnings('ignore')

import pandas as pd

import numpy as np

import seaborn as sns

import matplotlib.pyplot as plt

import pandas_profiling

from sklearn.preprocessing import LabelEncoder

from sklearn.preprocessing import OneHotEncoder

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

from sklearn.metrics import accuracy_score
df_train = pd.read_csv('../input/cat-in-the-dat/train.csv')

df_train.head()
df_train.shape
df_train.isnull().sum()
df_train.dtypes
fig, ax =plt.subplots(2,2,figsize=(16,8))

sns.countplot(df_train['bin_0'], ax=ax[0,0])

sns.countplot(df_train['bin_1'], ax=ax[0,1])

sns.countplot(df_train['bin_2'], ax=ax[1,0])

sns.countplot(df_train['bin_3'], ax=ax[1,1])

fig.show()
plt.figure(figsize=(10,3))

sns.countplot(df_train['bin_4'])
fig, ax =plt.subplots(2,2,figsize=(16,12))

sns.countplot(df_train['nom_0'], ax=ax[0,0])

sns.countplot(df_train['nom_1'], ax=ax[0,1])

sns.countplot(df_train['nom_2'], ax=ax[1,0])

sns.countplot(df_train['nom_3'], ax=ax[1,1])

fig.show()
plt.figure(figsize=(10,3))

sns.countplot(df_train['nom_4'])
fig, ax =plt.subplots(3,2,figsize=(16,12))

sns.countplot(df_train['ord_0'], ax=ax[0,0])

sns.countplot(df_train['ord_1'], ax=ax[0,1])

sns.countplot(df_train['ord_2'], ax=ax[1,0])

sns.countplot(df_train['ord_3'].sort_values(), ax=ax[1,1])

sns.countplot(df_train['ord_4'].sort_values(), ax=ax[2,0])

sns.countplot(df_train['ord_5'].sort_values(), ax=ax[2,1])

fig.show()
plt.figure(figsize=(10,3))

sns.distplot(df_train['day'])
plt.figure(figsize=(10,3))

sns.distplot(df_train['month'])
plt.figure(figsize=(10,3))

sns.countplot(df_train['target'])
pd.value_counts(df_train['target'])
x = df_train.drop(['target'],axis=1)

y = df_train['target']
train = pd.DataFrame()

label=LabelEncoder()

for c in  x.columns:

    if(x[c].dtype=='object'):

        train[c]=label.fit_transform(x[c])

    else:

        train[c]=x[c]
train.head()
x_train, x_test, y_train, y_test = train_test_split(train, y, test_size=0.3, random_state=0)
lg = LogisticRegression()
lg.fit(x_train,y_train)
pred = lg.predict(x_test)
print('Accuracy : ',accuracy_score(y_test,pred))
x.head()
one=OneHotEncoder()

one.fit(x)

train=one.transform(x)

print('train data set has got {} rows and {} columns'.format(train.shape[0],train.shape[1]))
x_train, x_test, y_train, y_test = train_test_split(train, y, test_size=0.3, random_state=0)
lg1 = LogisticRegression()
lg1.fit(x_train, y_train)
pred1 = lg1.predict(x_test)
print('Accuracy : ',accuracy_score(y_test,pred1))
df_test = pd.read_csv('../input/cat-in-the-dat/test.csv')

df_test.head()
test_id = df_test['id']

df_test = df_test.drop(['id','nom_5','nom_6','nom_7','nom_8','nom_9'], axis=1)

x =x.drop(['id','nom_5','nom_6','nom_7','nom_8','nom_9'], axis=1)
hot = OneHotEncoder()

hot.fit(df_test)

test=hot.transform(df_test)

print('test data set has got {} rows and {} columns'.format(test.shape[0],test.shape[1]))
one=OneHotEncoder()

one.fit(x[:200000])

train=one.transform(x[:200000])

print('train data set has got {} rows and {} columns'.format(train.shape[0],train.shape[1]))
final_lg = LogisticRegression()
final_lg.fit(train,y[:200000])
actual_pred = final_lg.predict(test)
predict = pd.DataFrame(actual_pred)

id_t = pd.DataFrame(test_id)
submission = pd.concat([id_t,predict], axis=1)

submission.columns = ["id", "target"]
submission.head()
submission.to_csv('submission.csv',index=False)


import argparse
import os
import gzip
import mimetypes
import sys
from Bio import SeqIO

try:
    import argparse_parents
except ImportError:
    sys.path.append(os.path.dirname(__file__))
    try:
        import argparse_parents
    finally:
        sys.path.remove(os.path.dirname(__file__))

def read_lengths_from_fastx_file(fastx_file):
    """

    @param fastx_file: file path
    @type fastx_file: str
    @rtype: dict[str, int]
    """
    file_type = mimetypes.guess_type(fastx_file)[1]
    if file_type == 'gzip':
        f = gzip.open(fastx_file, "rt")
    elif not file_type:
        f = open(fastx_file, "rt")
    else:
        raise RuntimeError("Unknown type of file: '{}".format(fastx_file))

    length = {}
    if os.path.getsize(fastx_file) == 0:
        return length

    file_format = None
    line = f.readline()
    if line.startswith('@'):
        file_format = "fastq"
    elif line.startswith(">"):
        file_format = "fasta"
    f.seek(0)

    if not file_format:
        raise RuntimeError("Invalid sequence file: '{}".format(fastx_file))

    for seq_record in SeqIO.parse(f, file_format):
        length[seq_record.id] = len(seq_record.seq)

    f.close()

    return length

def add_column(mapping_file, fasta_file):
    lengths = read_lengths_from_fastx_file(fasta_file)
    sequence_id_column_index = 0
    with open(mapping_file, 'r') as read_handler:
        for line in read_handler:
            line = line.rstrip('\n')
            if line.startswith('@@'):
                for index, column_name in enumerate(line[2:].split('\t')):
                    if column_name == 'SEQUENCEID':
                        sequence_id_column_index = index
                print('%s\t_LENGTH' % line)
                continue

            if len(line.strip()) == 0 or line.startswith('#') or line.startswith('@'):
                print(line)
                continue

            row_data = line.split('\t')
            sequence_id = row_data[sequence_id_column_index]
            print('%s\t%d' % (line, lengths[sequence_id]))

def main():
    parser = argparse.ArgumentParser(description="Add length column _LENGTH to gold standard mapping and print mapping on the standard output")
    parser.add_argument("-g", "--gold_standard_file", help=argparse_parents.HELP_GOLD_STANDARD_FILE, required=True)
    parser.add_argument("-f", "--fasta_file", help="FASTA or FASTQ file with sequences of gold standard", required=True)
    args = parser.parse_args()
    add_column(args.gold_standard_file, args.fasta_file)

if __name__ == "__main__":
    main()


N = int(input())

for k in range(N+3):
  if k*(k-1)//2 == N: break

if k==N+2:
  print('No')
  exit()

print('Yes')
print(k)
S = [[] for _ in range(k)]
c = 1
for i in range(k):
  for j in range(i+1, k):
    S[i].append(c)
    S[j].append(c)
    c += 1

for s in S:
  print(len(s), ' '.join(map(str, s)))


import os
import numpy as np
import pickle
import argparse

import librosa
import librosa.display
import matplotlib.pyplot as plt

from utils import maybe_make_directory
from feature_extraction import extract_mel_spectrogram

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataset', type=str,
                        required=True, choices=['train', 'valid', 'test'],
                        help='Dataset to load the filenames pickle. (required) (default: %(default)s)')
    parser.add_argument('--data_path', type=str,
                        required=True,
                        help='Directory path to the datasets. (required) (default: %(default)s)')
    parser.add_argument('--input_dir', type=str,
                        default='./out',
                        help='Directory path to the pickle files. (default: %(default)s)')
    parser.add_argument('--output_dir', type=str,
                        default='./melspec',
                        help='Directory path to the melspectrograms output. (default: %(default)s)')
    parser.add_argument('--n_mels', type=int,
                        default=128,
                        help='Number of Mel bands to generate. (default: %(default)s)')
    parser.add_argument('--fmax', type=int,
                        default=8000,
                        help='Highest frequency (in Hz). (default: %(default)s)')
    parser.add_argument('--hop_length', type=int,
                        default=1024,
                        help='Number of samples between successive frames. (default: %(default)s)')

    args = parser.parse_args()

    maybe_make_directory(args.input_dir)
    maybe_make_directory(os.path.join(args.output_dir, args.dataset))

    return args

args = parse_args()

DATASET_PATH = args.data_path
AUDIO_FILEPATH = "audio"

FILENAMES_PICKLE_PATH = os.path.join(args.input_dir, f'filenames_{args.dataset}.pickle')

with open(FILENAMES_PICKLE_PATH, 'rb') as f:
    filenames_examples = pickle.load(f)

for idx, filename in enumerate(filenames_examples):
    mel_spectrogram = extract_mel_spectrogram(os.path.join(DATASET_PATH, AUDIO_FILEPATH, filename + '.wav'), n_mels=args.n_mels, hop_length=args.hop_length, fmax=args.fmax)
    class_file = filename.split('_')[0]
    plt.figure(figsize=(10,4))
    librosa.display.specshow(librosa.power_to_db(mel_spectrogram, ref=np.max),
                         y_axis='mel', fmax=args.fmax, x_axis='time')
    plt.colorbar(format='%+2.0f dB')
    plt.title("Mel spectrogram for " + class_file)
    plt.savefig(os.path.join(args.output_dir, args.dataset, f'{class_file}_mel_spectro_{str(idx)}.png'), bbox_inches='tight', transparent=True, pad_inches=0)
    plt.close()
print(f'Mel spectrograms saved in {args.output_dir} directory')


# -*- coding:utf-8 -*-
# title           :地月拉格朗日点模拟
# description     :地月拉格朗日点模拟(对理想的位置进行了调整)
# author          :Python超人
# date            :2023-05-01
# link            :https://gitcode.net/pythoncr/
# python_version  :3.8
# ==============================================================================
import math

from bodies import Earth, Moon
from common.consts import SECONDS_PER_HOUR
from objs import Satellite
from sim_scenes.func import ursina_run, camera_look_at
from simulators.ursina.entities.body_timer import TimeData, BodyTimer
from simulators.ursina.ursina_event import UrsinaEvent
from simulators.ursina.ursina_mesh import create_connecting_lines

# 月球绕地球的半径
R = 363104
# 创建地月
earth = Earth(init_position=[0, 0, 0], texture="earth_hd.jpg",
              init_velocity=[0, 0, 0], size_scale=0.8e1)  # 地球放大 8 倍，地月距离保持不变
moon = Moon(init_position=[0, 0, R],  # 距地距离约: 363104 至 405696 km
            init_velocity=[-1.054152222, 0, 0], size_scale=1.2e1)  # 月球放大 12 倍，地月距离保持不变

# region 在拉格朗日点 L1, L2, L3, L4, L5 (对理想的位置进行了调整)上创建卫星
def create_satellite(name, init_position, init_velocity):
    """
    在 L1, L2, L3, L4, L5 创建卫星
    @param name:
    @param init_position:
    @param init_velocity:
    @return:
    """
    satellite = Satellite(name=name, mass=1.4e10, size_scale=3.2e3, color=(255, 200, 0),
                          init_position=init_position,
                          init_velocity=init_velocity, gravity_only_for=[earth, moon])
    return satellite

# 在 L1 位置上创建一个具有初速度的卫星
satelliteL1 = create_satellite(name=f'卫星L1', init_position=[0, 0, 308536.672],
                               init_velocity=[-0.890136271716, 0, 0])
# 在 L2 位置上创建一个具有初速度的卫星
satelliteL2 = create_satellite(name=f'卫星L2', init_position=[0, 0, 423338.5083198447],
                               init_velocity=[-1.24, 0, 0])
vel_L345 = 1.048
# 在 L3 位置上创建一个具有初速度的卫星
satelliteL3 = create_satellite(name=f'卫星L3', init_position=[0, 0, -364941.3043941873],
                               init_velocity=[vel_L345, 0, 0])
# 在 L4 位置上创建一个具有初速度的卫星
satelliteL4 = create_satellite(name=f'卫星L4', init_position=[314457.2882157448, 0, 177142.46945395062],
                               init_velocity=[-math.sin(math.pi * 30 / 180) * vel_L345, 0,
                                              math.cos(math.pi * 30 / 180) * vel_L345])
# 在 L5 位置上创建一个具有初速度的卫星
satelliteL5 = create_satellite(name=f'卫星L5', init_position=[-314457.2882157448, 0, 177142.46945395062],
                               init_velocity=[-math.sin(math.pi * 30 / 180) * vel_L345, 0,
                                              -math.cos(math.pi * 30 / 180) * vel_L345])
# endregion

if __name__ == '__main__':
    from ursina import camera
    def on_ready():
        # 运行前触发
        # 摄像机看向地球
        camera_look_at(earth)
        camera.rotation_y = -90

    def on_timer_changed(time_data: TimeData):
        # 实时删除和创建连接线
        from ursina import destroy
        if hasattr(earth, "lines"):
            for line in earth.lines:
                destroy(line)
        if int(time_data.total_hours) % 8 == 0:
            # 创建连接线（将卫星列表用线条连接起来）
            earth.lines = create_connecting_lines([
                [satelliteL2, satelliteL3],
                [satelliteL4, satelliteL1], [satelliteL5, satelliteL1],
                [satelliteL4, satelliteL2], [satelliteL5, satelliteL2],
                [satelliteL4, satelliteL3], [satelliteL5, satelliteL3],
            ])

    # 订阅事件后，上面的函数功能才会起作用
    # 运行前会触发 on_ready
    UrsinaEvent.on_ready_subscription(on_ready)
    # 运行中，每时每刻都会触发 on_timer_changed
    UrsinaEvent.on_timer_changed_subscription(on_timer_changed)
    # 设置计时器的最小时间单位为分钟
    BodyTimer().min_unit = BodyTimer.MIN_UNIT_MINUTES
    bodies = [earth, moon,
              satelliteL1, satelliteL2, satelliteL3, satelliteL4, satelliteL5]
    # 使用 ursina 查看的运行效果
    # 常用快捷键： P：运行和暂停  O：重新开始  I：显示天体轨迹
    # position = 左-右+、上+下-、前+后-
    ursina_run(bodies, SECONDS_PER_HOUR * 5,
               # position=(-300000, 1500000, -100),
               position=(0, 1500000, 0),
               show_timer=True,
               # show_trail=True
               )


from random import randint
from time import sleep
from operator import itemgetter
jogadores = {}
ranking = {}
for c in range(1, 5):
    jogadores['Jogador'] = randint(1, 6)
    sleep(1)
    print(f'Jogador{c} tirou {jogadores["Jogador"]} no dado')
    ranking[f'Jogador{c}'] = jogadores['Jogador']
print('-='*24)
ranking = sorted(ranking.items(), key=itemgetter(1), reverse=True)
print('  -=-= Ranking dos jogadores -=-=')
for c, i in enumerate(ranking):
    print(f'{c+1}º lugar: {i[0]} com {i[1]}')


try:
  import telebot
  from requests import *
  from telebot import TeleBot,types
  import time
except:
	import os
	os.system("pip install telebot")
	os.system("pip install time")
	os.system("pip install requests")
token = "5490297673:AAGHTc_3UG5mq0_bF-zKuyN4WuJ9sNvNjkU"
bot = TeleBot(token)
@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, text="  •قم بل اشتراك في هاذهي القناة : @deferent_404 •")
    time.sleep(5)
    first = message.from_user.first_name
    bot.send_message(message.chat.id, text="  • SeNd UsEr InstaGram •")
@bot.message_handler(content_types = ['text'])
def basha(m):
 ba = m.text
 try:
  hd = {
'user-agent':'Mozilla/5.0 (Linux; Android 11; SM-A205F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.40 Mobile Safari/537.36',
'viewport-width':'412',
'x-asbd-id':'198387',
'x-ig-app-id':'1217981644879628',
'x-ig-www-claim':'hmac.AR1GMxGxYNiyJ_Qr59WPgznfqJKtnAogUcpBr_5hDMSoxwjz'}
  rr=get(f'https://i.instagram.com/api/v1/users/web_profile_info/?username={ba}',headers=hd).json()
  Name = rr['data']['user']['full_name']
  FOLO=rr['data']['user']['edge_followed_by']['count']
  bayo = rr['data']['user']['biography']
  ID = rr['data']['user']['id']
  lok = get(f"https://o7aa.pythonanywhere.com/?id={ID}").json()['date']
  FLO = (rr['data']['user']['edge_follow']['count'])
  tlg =(f"""𝁵 deferent  𝁵
𓏳𓏳𓏳𓏳𓏳𓏳𓏳
𓊒 𝑁𝐴𝑀𝐸 :- {Name}
𓊒 𝑈𝑆𝐸𝑅 :- {ba}
𓊒 𝐹𝑂𝐿𝐿𝑂𝑊𝐸𝑅𝑆 :- {FOLO}
𓊒 𝐹𝑂𝐿𝐿𝑂𝑊𝐼𝑁𝐺 :- {FLO}
𓊒 id : {ID}
𓊒 𝐷𝐴𝑇𝐸 :- {lok}
𓊒 BaYo :- {bayo}
𓊒 𝐿𝐼𝑁𝐾 :- https://www.instagram.com/{ba}
bv : @deferent_404
𓏳𓏳𓏳𓏳𓏳𓏳𓏳
.""")

  bot.send_message(m.chat.id,tlg)
  bot.send_message(m.chat.id, text="• SeNd UsEr InstaGram •")
 except:
  bot.send_message(m.chat.id, text="  - USER NOT FOUND !\n- TRY ? SEND USER :")

bot.polling()


from BoardController import BoardController

class Player:
    def __init__(self, number, bc):
        self.player = number
        self.b_controller = bc

    def get_number(self):
        return self.player

    def play_turn(self):

        validmove = False
        while not validmove:
            column = None
            row = None
            while column not in range(1, 4):
                print("Input a valid column (1-3):")
                column = int(input())
                # column = 1
            while row not in range(1, 4):
                print("Input a valid row (1-3):")
                row = int(input())
                # row = 3
            column -= 1
            row -= 1

            validmove = self.b_controller.put_piece(row, column, self.player)
            if not validmove:
                print('-- Please enter a valid move!!')


import sys
input = sys.stdin.readline

n = int(input())
m = int(input())

graph = [x for x in range(n+1)]

def find(x):
    if graph[x] != x:
        graph[x] = find(graph[x])
        return graph[x]
    return x

def union(x, y):
    x, y = find(x), find(y)
    graph[x] = y

for i in range(1, n+1):
    tmp = [0] + list(map(int, input().split()))
    for j in range(i+1, len(tmp)):
        if tmp[j] == 1:
            union(i, j)

for i in range(1, n+1):
    find(i)

arr = list(map(int, input().split()))
start = graph[arr[0]]

for i in range(1, m):
    if start != graph[arr[i]]:
        print("NO")
        exit()

print("YES")


import math
import numpy as np

def testFunction(theta, phi):
    return np.sin(theta) * np.sin(phi)

class GWDetectorNetwork:

    def __init__(self, detectorList):

        """ Takes a list of dictionaries which contain data for detectors and finds the antenna power patterns and detection values for them """

        #Converts detector settings list into detector objects
        self.detectorList = []
        for detector in detectorList:
            detectorObject = GWDetector(detector["beta"], detector["lambd"], detector["chi"], detector["eta"], detector["name"], detector["visibility distance"])
            self.detectorList.append(detectorObject)

    def getAntennaPowerPattern(self, theta, phi, psi):

        """ sums all antenna pattern """

        antennaPowerPatternList = []
        for detector in self.detectorList:
            antennaPowerPatternList.append(detector.getAntennaPowerPattern(theta, phi, psi))

        return sum(antennaPowerPatternList)

class GWDetector:

    """ Class for a GW detector contains antenna power patterns mostly, params include longitude, lattitude, orientation, and seperation """

    def __init__(self, _beta, _lambda, _chi, _eta, _name, _horizonDistance):

        """ Beta is lattitude, lambda is longitude, chi is orientation measured counter clockwise from east, opening angle of arms is eta """

        self.beta = _beta
        self.lambd = _lambda
        self.chi = _chi
        self.eta = _eta
        self.name = _name
        self.dv = _horizonDistance

        self.appList, self.crossList, self.plusList, self.aList, self.bList = ([], [], [], [], [])

    def getAntennaPowerPattern(self, theta, phi, psi):
        a = self.afunction(theta, phi)
        b = self.bfunction(theta, phi)

        plus = self.AP_PLUS(a, b, psi)
        cross = self.AP_CROSS(a, b, psi)

        powerPattern = (plus ** 2) + (cross ** 2)
        self.appList.append(powerPattern)
        return powerPattern

    def afunction(self, theta, phi):

        ret = ((1/16) * math.sin(2 * self.chi) * (3 - math.cos(2 * self.beta)) * (3 - math.cos(2 * theta))\
        * math.cos(2 * (phi + self.lambd)))\
        + ((1/4) * math.cos(2 * self.chi) * math.sin(self.beta) * (3 - math.cos(2 * theta))\
        * math.sin(2 * (phi + self.lambd)))\
        + ((1/4) * math.sin(2 * self.chi) * math.sin(2 * self.beta)\
        * math.sin(2 * theta) * math.cos(phi + self.lambd))\
        + ((1/2) * math.cos(2 * self.chi) * math.cos(self.beta)\
        * math.sin(2 * theta) * math.sin(phi + self.lambd))\
        + ((3/4) * math.sin(2 * self.chi) * (math.cos(self.beta) ** 2) * (math.sin(theta) ** 2))

        self.aList.append(ret)

        return ret

    def bfunction(self, theta, phi):

        ret = (math.cos(2 * self.chi) * math.sin(self.beta)\
        * math.cos(theta) * math.cos(2 * (phi + self.lambd)))\
        - ((1/4) * math.sin(2 * self.chi) * (3 - math.cos(2 * self.beta))\
        * math.cos(theta) * math.sin(2 * (phi + self.lambd)))\
        + (math.cos(2 * self.chi) * math.cos(self.beta)\
        * math.sin(theta) * math.cos(phi + self.lambd))\
        - ((1/2) * math.sin(2 * self.chi) * math.sin(2 * self.beta)\
        * math.sin(theta) * math.sin(phi + self.lambd))\

        self.bList.append(ret)

        return ret

    def AP_PLUS(self, a, b, psi):
        ret = math.sin(self.eta) * ((a * math.cos(2 * psi)) + (b * math.sin(2 * psi)))

        self.plusList.append(ret)

        return ret

    def AP_CROSS(self, a, b, psi):
        ret = math.sin(self.eta) * ((b * math.cos(2 * psi)) - (a * math.sin(2 * psi)))

        self.crossList.append(ret)

        return ret

    @staticmethod
    def Single_AP_PLUS(theta, phi, psi):
        ret = ((1/2) * (1 + (math.cos(theta) ** 2)) * math.cos(2 * phi) * math.cos(2 * psi)) - (math.cos(theta) * math.sin(2 * phi) * math.sin(2 *\
            psi))
        return ret

    @staticmethod
    def Single_AP_CROSS(theta, phi, psi):
        ret = ((1/2) * (1 + (math.cos(theta) ** 2)) * math.cos(2 * phi) * math.sin(2 * psi)) + (math.cos(theta) * math.sin(2 * phi) * math.cos(2 *\
        psi))
        return ret

    @staticmethod
    def getSingleAntennaPowerPattern(theta, phi, psi):
        ret = (GWDetector.Single_AP_CROSS(theta, phi, psi) ** 2) + (GWDetector.Single_AP_PLUS(theta, phi, psi) ** 2)
        return ret

    @staticmethod
    def inclinationMultiplier(psi):
        return (1/8) * (1 + (6 * (math.cos(psi) ** 2)) + (math.cos(psi) ** 4))

    @staticmethod
    def DMS_TO_DEGREES(degs, mins, secs):
        ret = degs + (mins/60) + (secs/3600)
        return ret

#GW Detectors
#chi is orientation from East in degrees
#input different detector locations and orientations, beta and lambda are lattitude and longitude
eta_AP = math.pi/2

#Livingston Louisiana LIGO
beta_LOUIS = math.radians(GWDetector.DMS_TO_DEGREES(30,33,46.4))
lambd_LOUIS = math.radians(GWDetector.DMS_TO_DEGREES(-90,-46,-27.3))
chi_LOUIS = math.radians(208)
Dv_LOUIS = 190
LouisianaDict = {"beta" : beta_LOUIS, "lambd" : lambd_LOUIS, "chi" : chi_LOUIS, "eta" : eta_AP, "name" : "LIGO Louisiana", "visibility distance" : Dv_LOUIS}

#Hanford Washington LIGO
beta_WASH = math.radians(GWDetector.DMS_TO_DEGREES(46,27,18.5))
lambd_WASH = math.radians(GWDetector.DMS_TO_DEGREES(-119,-24,-27.6))
chi_WASH = math.radians(279)
Dv_WASH = 190
WashingtonDict = {"beta" : beta_WASH, "lambd" : lambd_WASH, "chi" : chi_WASH, "eta" : eta_AP, "name" : "LIGO Washington", "visibility distance" : Dv_WASH}

#VIRGO
beta_VIRGO = math.radians(GWDetector.DMS_TO_DEGREES(43,37,53))
lambd_VIRGO = math.radians(GWDetector.DMS_TO_DEGREES(10,30,16))
chi_VIRGO = math.radians(333.5)
Dv_VIRGO = 170
VirgoDict = {"beta" : beta_VIRGO, "lambd" : lambd_VIRGO, "chi" : chi_VIRGO, "eta" : eta_AP, "name" : "VIRGO Italy", "visibility distance" : Dv_VIRGO}

#KAGRA
beta_KAGRA = math.radians(GWDetector.DMS_TO_DEGREES(36, 15, 0))
lambd_KAGRA = math.radians(GWDetector.DMS_TO_DEGREES(137, 10, 48))
chi_KAGRA = math.radians(20.)
Dv_KAGRA = 170
KAGRADict = {"beta" : beta_KAGRA, "lambd" : lambd_KAGRA, "chi" : chi_KAGRA, "eta" : eta_AP, "name" : "KAGRA Japan", "visibility distance" : Dv_KAGRA}

#Test detector
beta_Test = math.radians(GWDetector.DMS_TO_DEGREES(0, 0, 0))  + math.pi/2
lambd_Test = math.radians(GWDetector.DMS_TO_DEGREES(0, 0, 0))
chi_Test = 0
Dv_Test = 170
TestDict = {"beta" : beta_Test, "lambd" : lambd_Test, "chi" : chi_Test, "eta" : eta_AP, "name" : "VIRGO Italy", "visibility distance" : Dv_Test}

Virgo = GWDetector(VirgoDict["beta"], VirgoDict["lambd"], VirgoDict["chi"], VirgoDict["eta"], VirgoDict["name"], VirgoDict["visibility distance"])

Test = GWDetector(TestDict["beta"], TestDict["lambd"], TestDict["chi"], TestDict["eta"], TestDict["name"], TestDict["visibility distance"])

Washington = GWDetector(WashingtonDict["beta"], WashingtonDict["lambd"], WashingtonDict["chi"], WashingtonDict["eta"], WashingtonDict["name"], WashingtonDict["visibility distance"])

Louisiana = GWDetector(LouisianaDict["beta"], LouisianaDict["lambd"], LouisianaDict["chi"], LouisianaDict["eta"], LouisianaDict["name"], LouisianaDict["visibility distance"])

detectorToTest = Virgo

detectorDictList = [VirgoDict, WashingtonDict, LouisianaDict]
earthDetectorNetwork = GWDetectorNetwork(detectorDictList)


import argparse
from cmds import upd_connect
from os import path

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('-d', '--direction', choices=['active-gsheet', 'gsheet-active'],
                    default='gsheet-active',
                    help="Compare A vs B, missing means present in A and not B.")
    ap.add_argument('--script-path', dest='script_path', help="Path for active script",
                    default='default')
    ap.add_argument('--archive-path', dest='archive_path', help="Path for script archive.",
                    default='___cm_updates')
    ap.add_argument('--arc_csv', help="For testing: flag for read/write of gsheet (r/w/n)",
                    choices=['read', 'write', 'none', 'r', 'w', 'n'], default='n')
    ap.add_argument('--time_tag', help='Flag to add time to node csv filename', action='store_true')
    ap.add_argument('--archive_gsheet', help="Path to move gsheet archive.  Use '__' to include script-path.",
                    default='___cm_updates/repo/gsheet')
    ap.add_argument('-v', '--verbose', help="Turn verbosity on.", action='store_true')
    ap.add_argument('-a', '--alert', help="Emails to alert if change.", default='ddeboer@seti.org')
    args = ap.parse_args()
else:
    args = argparse.Namespace(archive_path=None, script_path='./', node_csv='n', verbose=True)
    print(args)
    cron_script = None

script_type = 'connupd'
cronjob_script = 'conn_update.sh'

if args.time_tag:
    args.time_tag = '_%y%m%d'

update = upd_connect.UpdateConnect(script_type=script_type,
                                   script_path=args.script_path,
                                   verbose=args.verbose)

if args.archive_path.startswith('___'):
    args.archive_path = path.join(update.script_path, args.archive_path[3:])
if args.archive_gsheet.startswith('___'):
    args.archive_gsheet = path.join(update.script_path, args.archive_gsheet[3:])

update.load_gsheet(split=False, arc_csv=args.arc_csv, path=args.archive_gsheet, time_tag=args.time_tag)
update.make_sheet_connections()
update.compare_connections(args.direction)
update.add_missing_parts()
update.add_missing_connections()
update.add_partial_connections()
update.add_different_connections()
update.finish(cronjob_script=cronjob_script, archive_to=args.archive_path, alert=args.alert)


from dataclasses import dataclass
from itertools import filterfalse
from pprint import pformat
from typing import Optional, Iterable, Dict, Tuple, Set

from pysmt.fnode import FNode
from pysmt.shortcuts import *
from pysmt.shortcuts import Not, And
from pysmt.typing import PySMTType, BOOL
from pysmt.walkers import IdentityDagWalker

@dataclass
class SolverOptions:
    timeout: int = None
    with_repetitions: bool = False
    use_ta: bool = True
    phase_caching: bool = True

def get_allsat(formula: FNode, atoms: Optional[Iterable[FNode]] = None,
               solver_options: Optional[SolverOptions] = None) -> \
        Tuple[Iterable[Set[FNode]], int]:
    """
    Enumerates a list of (partial) models of the given formula.
    :param formula: the formula to enumerate models for
    :param atoms: the atoms to project the models on (if None, all atoms in the formula are used)
    :param solver_options: options for the solver
    :return: a list of models and the total number of models
    """
    formula = rewalk(formula)

    if atoms is None:
        atoms = get_boolean_variables(formula)
    if len(atoms) == 0:
        return [], 0
    atoms = sorted(atoms, key=lambda x: x.symbol_name())

    if solver_options is not None:
        solver_options_dict = get_solver_options_dict(solver_options)
    else:
        solver_options_dict = {}

    models = []
    with Solver(name="msat", solver_options=solver_options_dict) as solver:
        solver.add_assertion(formula)
        solver.all_sat(important=atoms, callback=lambda model: _allsat_callback(model, solver.converter, models))

    total_models_count = sum(
        map(lambda model: 2 ** (len(atoms) - len(model)), models)
    )
    return models, total_models_count

def _allsat_callback(model, converter, models):
    py_model = {converter.back(v) for v in model}
    assert IdentityDagWalker().walk(And(py_model)) == And(py_model)
    models.append(py_model)
    return 1

def check_sat(formula: FNode):
    formula = rewalk(formula)
    with Solver(name="msat") as solver:
        return solver.is_sat(formula)

def get_solver_options_dict(solver_options: SolverOptions) -> Dict[str, str]:
    solver_options_dict = {}
    if solver_options.with_repetitions:
        solver_options_dict["dpll.allsat_allow_duplicates"] = "true"
    if not solver_options.phase_caching:
        solver_options_dict["dpll.branching_cache_phase"] = "0"
        solver_options_dict["dpll.branching_initial_phase"] = "0"
        solver_options_dict["dpll.branching_random_frequency"] = "0"
    if solver_options.use_ta:
        solver_options_dict["dpll.allsat_minimize_model"] = "true"
        solver_options_dict["dpll.allsat_allow_duplicates"] = "false"
        solver_options_dict["preprocessor.toplevel_propagation"] = "false"
        solver_options_dict["dpll.branching_initial_phase"] = "0"
    return solver_options_dict

def get_boolean_variables(formula: FNode):
    return _get_variables(formula, BOOL)

def get_real_variables(formula: FNode):
    return _get_variables(formula, REAL)

def _get_variables(formula: FNode, type_: PySMTType):
    return {a for a in formula.get_free_variables() if a.get_type() == type_}

def get_lra_atoms(formula: FNode):
    return {a for a in formula.get_atoms() if a.is_theory_relation()}

def get_functions(formula: FNode):
    return {a for a in formula.get_atoms() if a.is_function_application()}

def get_dict_model(mu):
    mu_dict = {}
    for a in mu:
        if a.is_not():
            mu_dict[a.arg(0)] = FALSE()
        else:
            mu_dict[a] = TRUE()
    return mu_dict

def check_models(ta, phi):
    """
    Check that the given list of models is correct and complete for the given formula.
    :param ta: the list of models
    :param phi: the formula
    :return: True if the list of models is correct and complete for the given formula, False otherwise
    """
    assert ta_is_correct(phi, ta), "ta is not correct: {}\n{}".format(phi, pformat(ta))
    assert ta_is_complete(phi, ta), "ta is not complete: {}\n{}".format(phi, pformat(ta))

def ta_is_correct(phi, ta):
    """
    Check that each model in the list satisfies the formula.
    :param phi: the formula
    :param ta: the list of models
    :return: True if each model in the list satisfies the formula, False otherwise
    """
    for mu in ta:
        model = And(mu)
        formula = And(phi, model)
        if not check_sat(formula):
            return False
    return True

def ta_is_complete(phi, ta):
    """
    Check that each total model of the formula is a super-model of one of the models in the list.
    :param phi: the formula
    :param ta: the list of models
    :return: True if each total model of the formula is a super-model of one of the models in the list, False otherwise
    """
    atoms = get_boolean_variables(phi).union(
        {a for a in get_lra_atoms(phi) if not a.is_equals()}
    )
    tta, _ = get_allsat(phi, atoms=atoms)
    # check that for every model in tta there is a corresponding supermodel in ta
    for eta in tta:
        if not any(eta.issuperset(rewalk(mu)) for mu in ta):
            return False
    return True
    # equiv = Iff(phi, Or(map(And, ta)))
    # return _is_valid(equiv)

def rewalk(phi):
    if isinstance(phi, list):
        return [rewalk(a) for a in phi]
    if isinstance(phi, tuple):
        return tuple(rewalk(a) for a in phi)
    if isinstance(phi, set):
        return {rewalk(a) for a in phi}
    return IdentityDagWalker().walk(phi)

def _is_valid(phi):
    phi = rewalk(phi)
    return is_valid(phi)

def is_atom(atom):
    return atom.is_symbol(BOOL) or atom.is_theory_relation() or atom.is_bool_constant()

def is_literal(literal):
    return is_atom(literal) or (literal.is_not() and is_atom(literal.arg(0)))

def is_clause(phi):
    return is_literal(phi) or (phi.is_or() and all(is_literal(a) for a in phi.args()))

def is_cnf(phi):
    return is_clause(phi) or (phi.is_and() and all(is_clause(a) for a in phi.args()))

def negate_literal(literal):
    return Not(literal).simplify()

def unique_everseen(iterable, key=None):
    """
    Source: https://docs.python.org/3/library/itertools.html#itertools-recipes
    """
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element


"""empty message

Revision ID: bf1a9db21afa
Revises: 47e06af68e7b
Create Date: 2019-09-23 13:14:32.989500

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'bf1a9db21afa'
down_revision = '47e06af68e7b'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('images')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('images',
    sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
    sa.Column('photo_id', sa.INTEGER(), autoincrement=False, nullable=True),
    sa.PrimaryKeyConstraint('id', name='images_pkey'),
    sa.UniqueConstraint('id', name='images_id_key'),
    sa.UniqueConstraint('photo_id', name='images_photo_id_key')
    )
    # ### end Alembic commands ###


val = list(range(1, 5))
print(val)
pessoas = [['Pedro', 25], ['Maria', 12], ['José', 25]]
print(pessoas[2][1])
num = [2, 8, 4, 7]
num.pop()
num.insert(1,3)
num.append(6)
print(num)
num = [8, 2, 4, 2, 5, 2]
print(num.count(2))
num = [6, 2, 1, 4, 3]
num.sort(reverse=True)
print(num)
paises = ('Brasil', 'Argentina', 'Alemanha')
print(f'{paises[0]} {paises[-1]}')
letras = ('J', 'X', 'M', 'O', 'A', 'K')
print(letras.index('A'))


# standard imports
import matplotlib.pyplot as plt

# project imports
import lib.models.tools as modeltools
from handlecall import handle_call

def plot_scc(args, datlst):

    for env, optimal, dpc, timevec, sample, descr, _ in datlst:

        dx = 1e-0
        timevec = list(filter(lambda t: t < 2305, timevec))
        experiment = env.get_experiment()
        nodes = dpc.get_n_approx_nodes()[0]

        sample = dpc.sample_forward_trajectory()
        env_nonoise = modeltools.load_model(
            modeltype=env.get_modeltype(),
            noise=False,
            stepsize=env.get_stepsize(),
            experiment=env.get_experiment(),
        )
        # calculate DP & optimal SCC along optimal trajectory
        dp_scc = []
        opt_scc = []
        for t in range(len(timevec)):
            v = t < args.verbose
            dp_scc.append(
                dpc.estimate_SCC(t, sample.trajectory[t], sample.sotwvec[t], dx, v)
            )
            # if not args.noise:
            opt_scc.append(modeltools.scc(env_nonoise, t, verbose=v, dx=dx))
            # else:
            #     opt_scc.append(1)
            if (t < args.print_result or args.print_result == -1) and t >= args.verbose:
                print(
                    "Year: {} | SOTW: {}| DP SCC: {:.2f} | Optimal SCC: {:.2f} | Ratio: {}".format(
                        timevec[t],
                        sample.sotwvec[t],
                        dp_scc[-1],
                        opt_scc[-1],
                        dp_scc[-1] / opt_scc[-1],
                    )
                )

            if args.savefile is not None and timevec[t] in [2015, 2205]:
                with open(args.savefile, "a+") as f:
                    f.write(
                        "% {} SCC difference experiment {}, nodes {}: {}%\n".format(
                            timevec[t],
                            experiment,
                            nodes,
                            (dp_scc[t] / opt_scc[t] - 1) * 100,
                        )
                    )
                    f.write(
                        "\\num\\def\\sccdif{}{}{}{{{:.1f}\\%}}%\n\n".format(
                            nodes,
                            timevec[t],
                            experiment,
                            (dp_scc[t] / opt_scc[t] - 1) * 100,
                        )
                    )

        plt.plot(timevec, dp_scc, "-", label="DP SCC ({}y)".format(env.get_stepsize()))

        # if not args.noise:
        plt.plot(
            timevec, opt_scc, "--", label="NLO SCC ({}y)".format(env.get_stepsize())
        )

    # plt.xlim([2005, 2305])
    plt.xlabel("Time (years)")
    plt.ylabel("SCC")
    plt.legend()

    if args.savefile is None:
        plt.show()

if __name__ == "__main__":
    handle_call(plot_scc)


import sqlite3

class Manager():
    def __init__(self, emp_id=[]):
        self.emp_id = emp_id

    def admins_home(self):
        print("\nWelcome to the Admins section. Only admins are allowed.\n")
        print("1. Create Bank's Admin account.")
        print("2. Sign in as an Admin.")
        print("3. Exit application.\n")

    def admins_actions(self):
        print("\nChooce the admin Action to Perfeorm")
        print("1. Get customers info.")
        print("2. Get admins info.")
        print("3. Delete a customer's account.")
        print("4. Delete an admin's account")
        print("5. Logout application.\n")

    def account_registration(self):
        print("\nRegister as an admin Here")

        try:

            name = str(input("\nName: "))
            employee_id = int(input("Enter Employee ID(Should be 8 integersi.e 12345678): "))

        except:
            print("\nEnter valid inputs\n")

        else:

            if (employee_id < 0) or (len(str(employee_id)) < 8):
                print("\nEnter a valid employee Id\n")

            else:
                try:
                    with sqlite3.connect("profiles.sqlite3")  as conn:
                        command = "INSERT INTO Admin VALUES(?, ?)"
                        conn.execute(command, (name, employee_id))
                        conn.commit()

                except:
                    print(f"\naccount with id: {employee_id} already exists.Try another employee Id")

                else:
                    print("")
                    print("\nYou've successfully created an account as an admin.\n")

    def sign_in(self):
        print("\nEnter employee id to sign in")

        try:
            # email = str(input("Email: "))
            employee_id = int(input("\nEmployee Id(Should be 8 integers.i.e 12345678): "))

        except:
            return "Failed "

        else:
            try:
                with sqlite3.connect("profiles.sqlite3") as conn:
                    command = "SELECT EmployeeId FROM Admin WHERE EmployeeId = ?"
                    cursor = conn.cursor()

                    # getting info with the id entered
                    info = tuple(cursor.execute(command, (employee_id,)))
                    #used for debugging
                    # print(info[0])

                    # Approving the existence of the employee id in details
                    if employee_id in info[0]:
                        print("\nAdministrative actions ahead: Be keen")
                        self.emp_id.append(employee_id)

            except:
                return "Failed"

            else:
                pass

    def delete_client_account(self):
        client_account = str(input("\nEnter the clients account's email to delete: "))

        emails = []
        try:
            with sqlite3.connect("profiles.sqlite3") as conn:
                get_info = "SELECT Email from PersonInfo"
                cursor = conn.cursor()
                mails = tuple(cursor.execute(get_info))

                for email in mails:
                    emails.append(email[0])

                if client_account in emails:
                    delete_command = "DELETE FROM PersonInfo WHERE Email = ?"
                    cursor.execute(delete_command,(client_account,))

                    print(f"\n{client_account} has been sucessfully deleted.\n")

                else:
                    print("\nInvalid account email")

        except:
            print("\nSome errors...\n")

        else:
            pass

    def display_admins(self):

        with sqlite3.connect("profiles.sqlite3") as conn:
            get_admins = "SELECT * FROM Admin"

            cursor = conn.cursor()

            admins_response = tuple(cursor.execute(get_admins))

            print("\n\nBelow are the Admins Info.")
            for admin in admins_response:
                name, employee_id = admin
                print(f"\nName: {name}\t\tEmployee Id: {employee_id}")

    def display_customers(self):

        with sqlite3.connect("profiles.sqlite3") as conn:
            get_customers = "SELECT * FROM PersonInfo"

            cursor = conn.cursor()

            customers_response = tuple(cursor.execute(get_customers))

            print("\n\nBelow are the Customers Info.")
            for customer in customers_response:
                name, email, account_bal = customer
                print(f"\nName: {name}\t\tEmail:{email}\t\tAcount Balance: Sh {account_bal}")

    def delete_admin(self):
        admin_id_to_delete = int(input("\nEnter the admin account id to delete: "))

        emp_ids = []
        try:
            with sqlite3.connect("profiles.sqlite3") as conn:
                get_info = "SELECT EmployeeId from Admin"
                cursor = conn.cursor()
                admins_info_response = tuple(cursor.execute(get_info))

                # checking response for debugging
                # print(admins_info_response)
                for admin in admins_info_response:
                    emp_ids.append(admin[0])

                # checking emp_ids for debugging
                # print(emp_ids)
                if admin_id_to_delete in emp_ids:
                    delete_command = "DELETE FROM Admin WHERE EmployeeId = ?"
                    cursor.execute(delete_command,(admin_id_to_delete,))

                    print(f"\n{admin_id_to_delete} has been sucessfully deleted.")

                else:
                    print("\nInvalid admin's id\n")

        except:
            print("\nSome errors...\n")

        else:
            pass


import os
import json
import shutil

def data_and_model_prep(dst_dir:str="new_dataset", repo_url:str="", ds_origin:str="http", json_dir:str="data_uri.json"):
    os.makedirs(dst_dir, exist_ok=True)
    os.makedirs("version", exist_ok=True)
    download_model(json_dir=json_dir)

    if ds_origin == "http":
        from_http_in_json(dst_dir, json_dir)

    elif ds_origin == "dvc_repo":
        from_dvc_repo(repo_url, dst_dir)

    else: raise ValueError("'http' and 'dvc_repo' are the only supported options")
    return

def from_dvc_repo(repo_url:str, dst_dir:str="./"):
    if repo_url.split(".")[-1] != "git":
        raise ValueError("repo is not a git uri")

    repo_name = dvc_pull(repo_url)
    repo_files = os.listdir(repo_name)

    pulled_dataset = [x for x in repo_files if x.endswith(".dvc") and not x.startswith(".")]
    default=0
    pulled_dataset = pulled_dataset[default]
    pulled_dataset_path = pulled_dataset.split(".")[0]

    if os.path.isdir(os.path.join(repo_name, pulled_dataset_path)):
        print(os.listdir(os.path.join(repo_name, pulled_dataset_path)))
        for ds in os.listdir(os.path.join(repo_name, pulled_dataset_path)):
            shutil.copytree(src=os.path.join(repo_name, pulled_dataset_path, ds),
                            dst=os.path.join(dst_dir, ds))
    else:
        shutil.copy(src=os.path.join(repo_name, pulled_dataset_path),
                    dst=os.path.join(dst_dir))

    shutil.rmtree(repo_name)
    return

def dvc_pull(repo_url):
    repo_name = repo_url.split("/")[-1].split(".")[0]
    cwd = os.getcwd()
    os.system(f"git clone {repo_url}")
    os.chdir(repo_name)
    os.system("dvc pull")
    os.chdir(cwd)
    return repo_name

def from_http_in_json(dst_dir, json_dir:str="data_uri.json"):
    f = open(json_dir)
    uri_obj = json.load(f)
    os.environ["MODEL_URI"] = uri_obj["model"]
    os.environ["DATASET_URI"] = uri_obj["dataset"]
    os.environ["DST_DIR"] = dst_dir
    os.system('chmod +x ./dataset-extractor.sh')
    os.system('./dataset-extractor.sh')
    f.close()
    return 0

def download_model(uri=None, json_dir:str="data_uri.json"):
    if uri is None:
        f = open(json_dir)
        uri_obj = json.load(f)
        os.environ["MODEL_URI"] = uri_obj["model"]
    else: os.environ["MODEL_URI"] = uri
    os.system('chmod +x ./model-downloader.sh')
    os.system('./model-downloader.sh')


num = 0

dic = {3:num} #list는 못 들어옴, tuple은 들어올 수 있음 <수정불가능해서그럼>

print(dic[3])

{}
d=set([1,23,4,5,23,45,5,6,5,4]) #집합이라 그렇구만
print(d)


"""Contains view, than edits buckets.

Classes:
 * BucketEdit
"""

from django.views.generic import TemplateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.shortcuts import get_object_or_404
from myrm_app.models import Bucket
from myrm_app.view_classes.forms.bucket import BucketForm
from myrm_app.view_classes.forms.parametrs import ParametrsForm

class BucketEdit(TemplateView):
    """Edits buckets.
    """

    template_name = 'bucket_edit.html'

    bucket_form = None
    parametrs_form = None
    success_url = reverse_lazy("bucket_list")

    def get(self, request, *args, **kwargs):
        bucket = get_object_or_404(Bucket, pk=kwargs['id'])
        parametrs = bucket.parametrs
        self.bucket_form = BucketForm(instance=bucket, prefix='bucket_form')
        self.parametrs_form = ParametrsForm(instance=parametrs, prefix='parametrs_form')
        return super(BucketEdit, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(BucketEdit, self).get_context_data(**kwargs)
        context['bucket_form'] = self.bucket_form
        context['parametrs_form'] = self.parametrs_form
        return context

    def post(self, request, *args, **kwargs):
        bucket = get_object_or_404(Bucket, pk=kwargs['id'])
        parametrs = bucket.parametrs
        self.bucket_form = BucketForm(request.POST, instance=bucket, prefix='bucket_form')
        self.parametrs_form = ParametrsForm(request.POST, instance=parametrs,  prefix='parametrs_form')
        if self.bucket_form.is_valid() and self.parametrs_form.is_valid():
            self.parametrs_form.save()
            self.bucket_form.save()
            return redirect(BucketEdit.success_url)
        else:
            return super(BucketEdit, self).get(request, *args, **kwargs)


from openpyxl import Workbook, load_workbook
from openpyxl.drawing.image import Image
from common_utils import load_json, get_xlsx_file_name, get_worksheet_name, get_apart_object

import sys
from pprint import pprint

from datetime import date

from colorama import Fore, Back, Style

from constants import 단지명_to_지역구, FIRST_ITEM_ROW_INDEX

def insert_image_with_cell_height(ws, image_path, cell):
    img = Image(image_path)
    ws.add_image(img, cell.coordinate)

# def is_image_cell(ws, cell):
#     return any(image.anchor == cell.coordinate for image in ws._images)

def is_image_cell(image_obj, cell):
    return cell.coordinate in image_obj.anchors

def 사진체크하기(image_obj, ws, row):

    현관사진_cell = ws.cell(row=row, column=1)
    큐알사진_cell = ws.cell(row=row, column=3)

    return is_image_cell(image_obj, 현관사진_cell) and is_image_cell(image_obj, 큐알사진_cell)

def count_images(ws, image_obj, n):

    image_count = 0

    for idx in range(n):
        row_index = FIRST_ITEM_ROW_INDEX + 2 * idx
        if 사진체크하기(image_obj, ws, row_index):
            image_count += 1

    return image_count

def get_image_object(ws):
    image_obj = {
        "images": ws._images,
        "anchors": { img.anchor: img for img in ws._images },
    }
    return image_obj

def 워크시트_하나_조사하기(ws, n):

    image_obj = get_image_object(ws)

    cnt = count_images(ws, image_obj, n)

def 워크시트_유니크_사진수(ws):
    # count = len(set([ img.anchor for img in ws._images ]))
    count = len([ img for img in ws._images ])
    return count

def 워크시트_작업량(ws):
    return 워크시트_유니크_사진수(ws) // 2

def 진행률체크위한_사진체크하기(아파트객체, 엑셀파일명):

    단지명 = 아파트객체["단지명"]
    동호수목록 = 아파트객체["동호수목록"]
    대상세대수 = 아파트객체["대상세대수"]

    # 1. 타겟 파일 열기
    파일경로 = get_xlsx_file_name(단지명)
    wb = load_workbook(filename = 파일경로)

    # 2. 워크시트를 전체를 순회하면서, 각 시트에서 이미지 카운트 => 누적
    # 완료세대수 = sum([ 워크시트_하나_조사하기(wb[get_worksheet_name(단지명, 몇동)], len(호수목록)) for 몇동, 호수목록 in 동호수목록.items() ])
    완료세대수 = sum([ 워크시트_작업량(wb[get_worksheet_name(단지명, 몇동)]) for 몇동 in 동호수목록.keys() ])

    # 3. 열었던 타겟파일은 닫기
    wb.close()

    return 완료세대수

def 아파트단지_하나_카운팅(config, 단지명, 프린트여부 = True, 파일업데이트여부 = False):

    아파트목록 = config['아파트목록']
    # 설정파일명 = config["설정파일명"]
    엑셀파일명 = config['엑셀파일명']

    아파트객체 = get_apart_object(config, 단지명)

    완료세대수 = 진행률체크위한_사진체크하기(아파트객체, 엑셀파일명)
    대상세대수 = 아파트객체["대상세대수"]

    # 1. 프린트
    if 프린트여부:
        진행률 = (완료세대수 / 대상세대수) * 100
        print(f"{단지명}: {완료세대수}호 / 전체 {대상세대수} 호 = {진행률}%")

    순번_열 = 1
    지역구_열 = 2
    단지명_열 = 3
    대상세대수_열 = 4
    완료세대수_열 = 5

    START_INDEX = 1

    # 2. 요약 파일 업데이트
    if 파일업데이트여부:
        wb = load_workbook(filename = 엑셀파일명)
        ws = wb.active

        cell = ws.cell(아파트객체["순번"] + 1, 완료세대수_열)
        cell.value = 완료세대수

        wb.save(엑셀파일명)
        wb.close()

def 카운팅_업데이트(config, 결과객체모음, 프린트여부 = True, 파일업데이트여부 = False):
    작업회차 = 2
    작업날짜 = "20230704" or date.today().strftime('%Y%m%d')

    # 아파트목록 = config['아파트목록']
    엑셀파일명 = config['엑셀파일명']

    for 단지명, 결과객체 in 결과객체모음.items():

        아파트객체 = get_apart_object(config, 단지명)

        작업량 = 결과객체["작업량"]
        신규_작업리스트 = 작업량["신규"]
        업데이트_작업리스트 = 작업량["업데이트"]

        완료세대수 = 작업량["기존"] + len(신규_작업리스트)
        대상세대수 = 아파트객체["대상세대수"]

        # pprint(신규_작업리스트)
        # pprint(업데이트_작업리스트)
        # print(f'작업량: 기존:{작업량["기존"]}, 신규:{len(신규_작업리스트)}, 업데이트:{len(업데이트_작업리스트)}')

        # 1. 프린트
        if 프린트여부:
            진행률 = (완료세대수 / 대상세대수) * 100
            print(f"{Fore.RED}{단지명}{Style.RESET_ALL}: 기존:{작업량['기존']}, 신규{len(신규_작업리스트)}호, 업데이트{len(업데이트_작업리스트)}호 진행 => {완료세대수}호 / 전체 {대상세대수} 호 = {Fore.BLUE}{진행률:.0f}%{Style.RESET_ALL}")

        순번_열 = 1
        지역구_열 = 2
        단지명_열 = 3
        대상세대수_열 = 4
        완료세대수_열 = 5
        퍼센트계산_열 = 6

        START_INDEX = 1

        # 2. 요약 파일 업데이트
        if 파일업데이트여부:
            wb = load_workbook(filename = 엑셀파일명)
            ws = wb.active

            해당작업회차_기입할_열 = 퍼센트계산_열 + 작업회차

            # 0. 날짜 기입
            if not ws.cell(1, 해당작업회차_기입할_열).value:
                ws.cell(1, 해당작업회차_기입할_열).value = 작업날짜

            # 1. 완료세대수 업데이트
            완료세대수_cell = ws.cell(아파트객체["순번"] + 1, 완료세대수_열)
            완료세대수_cell.value = 완료세대수

            # 2. 오늘 작업량에 대한 업데이트
            기록_cell = ws.cell(아파트객체["순번"] + 1, 해당작업회차_기입할_열)
            기록_cell.value = f"신규{len(신규_작업리스트)}/업데이트{len(업데이트_작업리스트)}"

            wb.save(엑셀파일명)
            wb.close()

if __name__ == '__main__':

    config = load_json('./apartments.json')
    프린트여부 = True
    파일업데이트여부 = True
    for 단지명 in 단지명_to_지역구.keys():
        try:
            아파트단지_하나_카운팅(config, 단지명, 프린트여부, 파일업데이트여부)
        except:
            print(f"{단지명} 카운팅 실패")


# coding: utf-8

# In[59]:

from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.callbacks import ModelCheckpoint,LearningRateScheduler,TensorBoard
import h5py
import timeit
from keras.preprocessing.image import ImageDataGenerator

from keras import backend as K
import tensorflow as tf
with K.tf.device('/gpu: 1'):
    config = tf.ConfigProto(intra_op_parallelism_threads=4, \
                            inter_op_parallelism_threads=4, allow_soft_placement=True,\
                            device_count = {'CPU' : 1, 'GPU' : 1 })
    session = tf.Session(config=config)
    K.set_session(session)

# In[60]:

classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
#classifier.summary()

# In[71]:

#Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
classifier.load_weights('model.h5')

# In[72]:

test_datagen = ImageDataGenerator(rescale = 1./255)

# In[79]:

test_set = test_datagen.flow_from_directory('dataset/dataset/test_set',
                                           target_size = (64, 64),
                                            batch_size = 10,
                                           class_mode = 'binary')

classifier.save_weights('testing_weights.h5')
# In[80]:
# Save Model
classifier.save('classifier1.h5')
checkpoint=ModelCheckpoint('testing.h5',
                            monitor='val_acc',
                            verbose= 1,
                            save_best_only=True,
                            save_weights_only=False,
                            mode='auto',
                            period=1)

X,y=test_set.next()

# In[81]:

classifier.predict_classes(X,batch_size=10,verbose=1)

# In[82]:

test_set = test_datagen.flow_from_directory('dataset/dataset/test_set',
                                           target_size = (64, 64),
                                            batch_size = 10,
                                           class_mode = 'binary')

# In[83]:

X,y=test_set.next()

# In[84]:

classifier.predict_classes(X,batch_size=10,verbose=1)


import os
import sys
# sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
# sys.path.insert(0, 'scripts/')

from airflow.models import DAG
from airflow.utils.dates import days_ago
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta

from scripts import (
    upload_to_s3,
    download_to_mongo
)

def upload_amplitude_data():
    upload_to_s3()

def download_s3_data():
    download_to_mongo()

default_args = {
    'owner': 'Lydia',
    'start_date': datetime(2021, 5, 7),
    'email': 'some@mail.com',
    'email_on_failure': True,
    'email_on_retry': True,
    'retries': 1,
    'retry_delay': timedelta(minutes=20)
}

data_transfer_dag = DAG(
    dag_id='prepare_data',
    default_args=default_args,
    schedule_interval='@daily'
)

upload_amplitude_data_task = PythonOperator(
    task_id='upload_amplitude_data',
    python_callable=upload_amplitude_data,
    dag=data_transfer_dag
)

download_s3_data_task = PythonOperator(
    task_id='download_s3_data',
    python_callable=download_s3_data,
    dag=data_transfer_dag
)

upload_amplitude_data_task >> download_s3_data_task


first_number=None
second_number=None
while first_number is None:
    try:
        first_number= float(input("Enter first number: "))
    except:
        print('Please enter a number only')
while second_number is None:
    try:
        second_number= float(input("Enter second number: "))
    except:
        print('Please enter a number only')

summation=first_number+second_number
subtraction=first_number-second_number
multiplication=first_number*second_number
division= first_number/second_number
power=first_number**second_number
remainder=first_number%second_number

print("Sum is",summation, "\nSubtarction is",subtraction, "\nmultiplcation is",multiplication, "\ndivision is", division, "\npower is", power, "\nremainder is", remainder  )

##second Task

third_number=None
while third_number is None:
    try:
      third_number= float(input("Enter first number: "))
    except:
        print('Please enter a number only')

summation_new=summation+third_number
subtraction_new=subtraction-third_number
multiplication_new=multiplication*third_number
division_new= division/third_number
power_new=power**third_number
remainder_new=remainder%third_number

print("Sum is",summation_new, "\nSubtarction is",subtraction_new, "\nmultiplcation is",multiplication_new, "\ndivision is", division_new, "\npower is", power_new, "\nremainder is", remainder_new  )


import streamlit as st
from joblib import load
import pandas as pd
from PIL import Image
from sklearn.feature_extraction.text import CountVectorizer

clf = load('filename.joblib')

vocabulary = load('vectorizer')
cv = CountVectorizer(vocabulary=vocabulary)

st.title("SENTIMENT ANALYSIS")
image = Image.open('IMG-20200904-WA0251.jpg')
st.image(image, width=800)
review = st.text_input('Enter your short review :')
df = {'review': review}
df = pd.DataFrame(df, index=[0])
to_pred = df.iloc[:, 0]
result = clf.predict(cv.transform(to_pred))
if(st.button('Predict')):
    st.write(result[0])


class Car:
    is_police = False

    def __init__(self, speed, color, name):
        self.speed = speed
        self.color = color
        self.name = name

    def go(self):
        print(f'{self.name}, go!')
        self.show_speed()

    def stop(self):
        print(f'{self.name}, stop.')
        self.speed = 0
        self.show_speed()

    def turn(self, direction):
        if direction.lower() == 'left' or direction.lower() == 'right':
            print(f'{self.name} turned {direction}.')
        else:
            print(f"You made a spelling mistake '{direction}'. {self.name} didn't turn around.")
        self.show_speed()

    def show_speed(self):
        if self.speed == 0:
            print(f'The {self.name} stopped. Speed {self.speed} km/h.')
        else:
            print(f'The {self.name} is moving at a speed of {self.speed} km/h.')

class TownCar(Car):
    speed_limit = 60

    def show_speed(self):
        super().show_speed()
        if self.speed > self.speed_limit:
            print(f'Bringing the speed to {self.speed - self.speed_limit}!!!')

class SportCar(Car):
    pass

class WorkCar(Car):
    speed_limit = 40

    def show_speed(self):
        super().show_speed()
        if self.speed > self.speed_limit:
            print(f'Bringing the speed to {self.speed - self.speed_limit}!!!')

class PoliceCar(Car):
    is_police = True

auto_1 = TownCar(65, 'yellow', 'Volkswagen')
auto_1.go()
auto_1.turn('Righht')
auto_1.stop()
auto_2 = SportCar(170, 'red', 'Ferrari')
auto_2.go()
auto_2.turn('Right')
auto_2.stop()
auto_3 = WorkCar(42, 'white', 'Renault')
auto_3.go()
auto_3.turn('left')
auto_3.stop()
auto_4 = PoliceCar(80, 'blue', 'Lada')
auto_4.go()
auto_4.turn('LEFT')
auto_4.stop()


import subprocess

class SubProcess:
    mocking = False
    calls = []
    outputs = []

    @classmethod
    def reset(cls, mocking=False, outputs=None):
        assert isinstance(mocking, bool)
        cls.mocking = mocking
        cls.calls.clear()
        cls.outputs.clear()
        if outputs:
            assert mocking is True
            for value in outputs:
                assert isinstance(value, bytes)
                cls.outputs.append(value)

    @classmethod
    def check_call(cls, cmd, **kw):
        assert isinstance(cmd, list)
        if cls.mocking:
            cls.calls.append(('check_call', cmd, kw))
        else:
            return subprocess.check_call(cmd, **kw)

    @classmethod
    def check_output(cls, cmd, **kw):
        assert isinstance(cmd, list)
        if cls.mocking:
            cls.calls.append(('check_output', cmd, kw))
            return cls.outputs.pop(0)
        else:
            return subprocess.check_output(cmd, **kw)


import pygame
import os

os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"

pygame.font.init()
FONT = pygame.font.SysFont("monospace", 10)
pygametext = ""
def py_print(s):
	global pygametext
	pygametext += str(s).replace("\t", "    ") + "\n"
def render_all_text():
	lines = pygametext.split("\n")
	rendered = []
	for t in lines:
		if len(t):
			color = 255 * (t[0] == ">")
			if color == 255 or show_other:
				if not show_other: rendered.append(FONT.render(t[2:], True, (0, 0, 0)))
				else: rendered.append(FONT.render(t[2:], True, (255 - color, color, 0)))
	widths = list(map(lambda x: x.get_width(), rendered))
	maxwidth = max(*widths)
	height = FONT.render("0", True, (0, 0, 0)).get_width() * len(rendered)
	result = pygame.Surface((maxwidth, height))
	result.fill((255, 255, 255))
	cum_y = 0
	for r in rendered:
		result.blit(r, (0, cum_y))
		cum_y += r.get_height()
	return result

f = open("orig.py", "r")
orig = f.read().split("\n")
f.close()

f = open("done.py", "r")
done = f.read().split("\n")
f.close()

donelineno = 0
lineno = 0
while donelineno < len(done):
	o = orig[lineno]
	if done[donelineno] == o:
		py_print("> " + o)
		donelineno += 1
	else:
		py_print("  " + o)
	lineno += 1
while lineno < len(orig):
	o = orig[lineno]
	py_print("  " + o)
	lineno += 1

show_other = True

screen = pygame.display.set_mode(render_all_text().get_size())

running = True
c = pygame.time.Clock()
while running:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = False
		elif event.type == pygame.MOUSEBUTTONUP:
			show_other = not show_other
			screen = pygame.display.set_mode(render_all_text().get_size())
	screen.fill((100, 100, 100))
	screen.blit(render_all_text(), (0, 0))
	pygame.display.flip()
	c.tick(60)


# i番目の重みws[i], 価値vs[i]
def solve(N, W, ws, vs):
    # V = 全ての品物の価値の総和
    V = sum(vs)

    # 初期値は価値0以外の重さを上限より大きく
    dp = [W+1] * (V + 1)
    dp[0] = 0
    for i in range(N):
        # 価値v, 重さw
        v = vs[i]; w = ws[i]
        for j in range(V, v-1, -1):
            dp[j] = min(dp[j-v] + w, dp[j])

    # 重さが上限以下の価値のうち、最大の価値が解
    return max(i for i in range(V+1) if dp[i] <= W)


# coding:utf-8
x = 'hello'

res = [x for x in 'ABC']

print(x)

'''
输出结果为：
hello

解释：
列表推导、生成器表达式，以及同它们很相似的集合（set）推导和字典（dict）推导，
在Python 3中都有了自己的局部作用域，就像函数似的。
表达式内部的变量和赋值只在局部起作用，表达式的上下文里的同名变量还可以被正常引用，局部变量并不会影响到它们。
'''

流畅的Python/第二章 序列构成的数组/1-局部作用域.py


from menu import Menu
from juice_maker import JuiceMaker
from money_machine import MoneyMachine
from admin import Admin
from art import logo

menu = Menu()
juice_maker = JuiceMaker()
money_machine = MoneyMachine()
admin = Admin()

machine_run = True

while machine_run:
    options = menu.get_items()
    print(logo)
    print("Welcome To Our Juice Vending Machine. Here you can create your own juice from your preference.")
    print(f"Menu -\n{options}")
    flavor_choice = input("What would you like to have? - ").lower()

    if flavor_choice == 'ajbrohi':
        admin.admin_process()

    else:
        juice = menu.find_drink(flavor_choice)
        size_choice = input(
            "What size of cup would you like to have? (Large/Regular) - ").lower()
        sugar_choice = input("Do you like to have suger? (Yes/No) - ").lower()

        if juice_maker.is_resource_sufficient(juice.name) and money_machine.make_payment(juice.cost, juice.price):
            juice_maker.make_juice(juice.name, size_choice, sugar_choice)


# Import the required libraries
try:
    from AppKit import NSWorkspace
except ImportError:
    print("Can't import AppKit -- maybe you're running python from brew?")
    print("Try running with Apple's /usr/bin/python instead.")
    exit(1)

from datetime import datetime
from time import sleep
import subprocess
from tkinter import *
import threading

last_active_name = None

def exec_applescript(script):
    p = subprocess.Popen(['osascript', '-e', script], stdout=subprocess.PIPE)
    line = p.stdout.readline()
    if line:
        print(line.rstrip())

def generate_command_for_app(appName):
    command_string = "tell application \"" + appName + "\" to get the {bounds, name}  of front window"
    slack_apps_list = ["Code", "Microsoft Teams", "Slack"]
    if (appName in slack_apps_list):
        command_string = "tell application \"System Events\" to get {position, size, name}  of every window of process \"Electron\""
    return command_string

def bounding_info():
    global last_active_name
    active_app = NSWorkspace.sharedWorkspace().activeApplication()
    if active_app['NSApplicationName'] != last_active_name:
        last_active_name = active_app['NSApplicationName']
        print("-------------------------------")
        print('%s: %s [%s]' % (
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            active_app['NSApplicationName'],
            active_app['NSApplicationPath']
        ))
        command_for_bounds = generate_command_for_app(active_app['NSApplicationName'])
        print(command_for_bounds)
        exec_applescript(command_for_bounds)

def move_ball():
    global xspeed, yspeed
    root.update()
    canvas.move(ball, xspeed, yspeed)
    (leftpos, toppos, rightpos, bottompos) = canvas.coords(ball)
    if leftpos <= 0 or rightpos >= 700:
        xspeed = -xspeed
    if toppos <= 0 or bottompos >= 350:
        yspeed = -yspeed

    canvas.after(30, move_ball)

# Create an instance of tkinter frame or window
root = Tk()
# Set the size of the window
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# root.attributes('-fullscreen',True)
# root.overrideredirect(True)
# Make the root window always on top
root.wm_attributes("-topmost", True)
# Turn off the window shadow
root.wm_attributes("-transparent", True)
# Set the root window background color to a transparent color
root.config(bg='systemTransparent')
root.attributes('-alpha', 0.4)
# root.wm_attributes("-transparentcolor", "white")
# Create a canvas widget
canvas = Canvas(root,
                width=screen_width,
                height=screen_height,
                highlightthickness=0)
canvas.pack()

# Create an oval or ball in the canvas widget
ball = canvas.create_oval(10, 10, 50, 50, fill="green3")
active_rect = canvas.create_rectangle(100, 100, 200, 200, fill="blue")
print(active_rect)
# Move the balls
xspeed = yspeed = 3
canvas.after(0, move_ball)
root.mainloop()


from rest_framework import viewsets
from .serializers import BotUsersSerializers, BotSchedulePicturesSerializers, BotScheduleUlSTUSerializers, \
    BotUsersRetrieveSerializers
from ..models import BotUsers, BotSchedulePictures, BotScheduleUlSTU
from rest_framework.response import Response
from rest_framework.decorators import action

# from rest_framework import permissions

class TableUsersView(viewsets.ModelViewSet):
    queryset = BotUsers.objects.all()
    serializer_class = BotUsersSerializers

    # permission_classes = [permissions.IsAuthenticated]

    # action_to_serializer = {
    #     'list': BotUsersRetrieveSerializers,
    #     'retrieve': BotUsersRetrieveSerializers
    #
    # }
    #
    # def get_serializer_class(self):
    #     return self.action_to_serializer.get(
    #         self.action,
    #         self.serializer_class
    #     )

    @action(detail=False, methods=['get'])
    def get_ids(self, request):
        array_vk_ids = []
        users = BotUsers.objects.all()
        for user in users:
            array_vk_ids.append(user.user_id)
        return Response({'vk_ids': array_vk_ids})

    @action(detail=False, methods=['get'])
    def get_specific_ids(self, request):
        query_params = self.request.query_params
        users = BotUsers.objects.all()
        groups = query_params.get('groups', None)
        groups = groups.split(',')

        array_vk_ids = []

        for group in groups:
            for user in users:
                group = group.lower()
                group_name = user.group_name.lower()
                if group == group_name:
                    array_vk_ids.append(user.user_id)

        return Response({'vk_ids': array_vk_ids})

    @action(detail=False, methods=['get'])
    def get_id_faculty(self, request):
        query_params = self.request.query_params
        faculties = query_params.get('faculties', None)
        faculties = faculties.split(',')
        users = BotUsers.objects.filter(faculty__in=faculties)
        array_vk_ids = []
        for user in users:
            array_vk_ids.append(user.user_id)
        return Response({
            'vk_ids': array_vk_ids
        })

class TableSchedulePictureView(viewsets.ModelViewSet):
    queryset = BotSchedulePictures.objects.all()
    serializer_class = BotSchedulePicturesSerializers
    # permission_classes = [permissions.IsAuthenticated]

class TableScheduleDaysView(viewsets.ModelViewSet):
    queryset = BotScheduleUlSTU.objects.all()
    serializer_class = BotScheduleUlSTUSerializers
    # permission_classes = [permissions.IsAuthenticated]


import numpy as np

class PCA:
    def __init__(self, D):
        mu = np.mean(D, axis=0)
        Z = D - mu
        cov_matrix = np.cov(np.transpose(Z), bias=True)
        self.eigenvalues, self.eigenvectors = self.__eigen_sorted(cov_matrix)

    def __eigen_sorted(self, matrix):
        eigen_values, eigen_vectors = np.linalg.eigh(matrix)
        idx = eigen_values.argsort()[::-1]
        eigen_values = eigen_values[idx]
        eigen_vectors = eigen_vectors[:, idx]
        return eigen_values, eigen_vectors

    def project_data(self, training_data, test_data, alpha):
        projection_matrix = self.__calculate_projection_matrix(alpha)
        return np.matmul(training_data, projection_matrix), np.matmul(test_data, projection_matrix)

    def __calculate_projection_matrix(self, alpha):
        eigen_sum = np.sum(self.eigenvalues)
        eigen_i = 0
        r = 0

        for eigenvalue in self.eigenvalues:
            r = r + 1
            eigen_i += eigenvalue
            if (eigen_i / eigen_sum) >= alpha:
                break
        return self.eigenvectors[:, :r]

def write_mat(mat, alpha):
    np.savetxt("PCA alpha = " + str(alpha) + ".txt", mat)


import sys

def solution(n, m, nums):
    start = 0
    end = nums[-1]
    while start <= end:
        mid = (start + end) // 2
        cnt = 0
        for elem in nums:
            cnt += max(elem - mid, 0)
        if cnt >= m:
            start = mid + 1
        else:
            end = mid - 1
    return end

N, M = tuple(map(int, sys.stdin.readline().rstrip().split(' ')))
L = list(map(int, sys.stdin.readline().rstrip().split(' ')))
print(solution(N, M, sorted(L)))


def get_dartboard(size):
    dartboard = []
    for r in range(size):
        dartboard.append(input().split())
    return dartboard

def multiply_sector(row, col, datrboard, size, mulyiply_by):
    up = int(datrboard[size - size][col])
    down = int(datrboard[size - 1][col])
    left = int(datrboard[row][size - 1])
    right = int(datrboard[row][size - size])
    result_points = (up + down + left + right) * mulyiply_by
    return result_points

def in_range(index, size):
    return 0 <= index < size

def swap(players):
    players[0], players[1] = players[1], players[0]
    return players

def reduce_player_points(current_player, points):
    current_player[1] -= points
    return current_player

DARTBOARD_SIZE = 7
INITIAL_POINTS = 501
DOUBLE_SECTOR = 2
TRIPLE_SECTOR = 3

first_player_name, second_player_name = input().split(", ")

datrboard = get_dartboard(DARTBOARD_SIZE)

first_player = [first_player_name, INITIAL_POINTS, 0]

second_player = [second_player_name, INITIAL_POINTS, 0]

trow = input()

players = [first_player, second_player]

while trow:
    is_player_win = False
    result = trow.strip("()")
    row_index, column_index = result.split(", ")
    row_index = int(row_index)
    column_index = int(column_index)

    players[0][2] += 1
    if not in_range(row_index, DARTBOARD_SIZE) or not in_range(column_index, DARTBOARD_SIZE):
        players = swap(players)
        trow = input()
        continue
    if datrboard[row_index][column_index] == "D":
        points = multiply_sector(row_index, column_index, datrboard, DARTBOARD_SIZE, DOUBLE_SECTOR)
        players[0] = reduce_player_points(players[0], points)
    elif datrboard[row_index][column_index] == "T":
        points = multiply_sector(row_index, column_index, datrboard, DARTBOARD_SIZE, TRIPLE_SECTOR)
        reduce_player_points(players[0], points)
    elif datrboard[row_index][column_index] == "B":
        is_player_win = True
        break
    else:
        points = int(datrboard[row_index][column_index])
        reduce_player_points(players[0], points)
    if players[0][1] <= 0:
        is_player_win = True
        break
    players = swap(players)
    trow = input()

if is_player_win:
    name = players[0][0]
    count_turns = players[0][2]
    print(f"{name} won the game with {count_turns} throws!")


"""A script to validate the reference images"""
from os.path import dirname, join
from os import listdir
from pyclashbot.utils.image_handler import open_image

def validate_references():
    """Method to validate the reference images"""
    reference_folder = join(dirname(__file__), "reference_images")
    valid = []
    invalid = []
    for folder in listdir(reference_folder):
        for image in listdir(join(reference_folder, folder)):
            try:
                print(f"Validating image {image}")
                open_image(join(reference_folder, folder, image))
                print(f"\tImage {image} is valid")
                valid.append(image)
            except Exception as err:  # pylint: disable=broad-except
                print(f"\tImage {image} is not valid")
                print(f"\t{err}")
                invalid.append(image)
    print(f"Validated {len(valid)} images")
    print(f"Failed to validate {len(invalid)} images")

if __name__ == "__main__":
    validate_references()


# may take a few seconds to load because the colors need to be extracted from the image
import turtle
from colors import rgb_colors
from turtle import Turtle, Screen
import random
turtle.colormode(255)

bob = Turtle()
bob.shape('turtle')
bob.color('green')
bob.resizemode('auto')
bob.speed('fastest')
bob.penup()

bob.setpos(-250, -250)

def paint_row():
    for x in range(10):
        random_color = random.choice(rgb_colors)
        bob.dot(20, random_color)
        bob.forward(50)

n = -200
for k in range(10):
    paint_row()
    bob.setpos(-250, n)
    n += 50

screen = Screen()
screen.screensize(1000, 1000)
screen.exitonclick()


genre_list_params = [
    (None, {"status": 200, "length": 50}),
    ({"page[size]": 10}, {"status": 200, "length": 10}),
    ({"page[size]": 60}, {"status": 200, "length": 60}),
]

cache_genre_list_params = [
    (
        None,
        {
            "status": 200,
            "key": "fastapi-cache:api.v1.genres:genre_list:('',):{'request': None, 'response': None, 'args': (), 'kwargs': \"{'self': <>, 'params': GenreListParams(page_size=50, page_number=0, name=None, sort=None)}\"}"
        },
    ),
]


# -*- coding: utf-8 -*-
arq = open ("texto.txt","r")
w = open ("file2.txt", "a")
a = "arumeida boladão escrevendo em arquivo com python\n"
w.write(a)
w.close()
print (arq)
linhas = arq.readlines()
texto_completo = arq.read()
print (texto_completo)

print (linhas)


import cv2 as cv
import numpy as np
import random
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'E:\\TESSERACT OCR\\tesseract.exe'
circles = []
counter1 = counter2 = 0
point1 = point2 = myPoint = myColor = []

def click_event(event, x, y, flags, param):
    global circles, counter1, counter2, point1, point2, myColor
    if event == cv.EVENT_LBUTTONDOWN:
        if counter1 == 0:
            point1 = int(x), int(y);
            counter1 += 1
            myColor = (random.randint(0, 2)*200, random.randint(0, 2)*200, random.randint(0, 2)*200)
        elif counter1 == 1:
            point2 = int(x), int(y);
            name = input('Enter Name: ')
            myPoint.append([point1, point2, name])
            counter1 = 0
        circles.append([x, y, myColor])
        counter2 += 1

img = cv.imread("Resources/text.png")
imgCopy = img.copy()
imgMask = np.zeros_like(imgCopy)

while True:
    for x, y, color in circles:
        cv.circle(img, (x, y), 2, color, cv.FILLED)
    cv.imshow("Image", img)
    cv.setMouseCallback('Image', click_event)
    if cv.waitKey(1) & 0xFF == ord('s'):
        print(myPoint)
        break

for i, r in enumerate(myPoint):
    imgCrop = img[r[0][1]:r[1][1], r[0][0]:r[1][0]]
    cv.imshow(str(i), imgCrop)
    img_text = pytesseract.image_to_string(imgCrop)
    print(img_text)
    #cv.rectangle(imgCopy, (r[0][0], r[0][1]), (r[1][0], r[1][1]), (0, 255, 0), cv.FILLED)

cv.imshow('I', imgCopy)
cv.waitKey(0)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Oct  1 06:24:33 2020

@author: lwoo0005
"""

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 17:01:51 2020

@author: lwoo0005
"""
import numpy as np
import pandas as pd

"""
pop='426F4_all_minD0_for_image'
inp_path='/Users/lwoo0005/Documents/An_H_pylori/Clr_Crtl_Fitness_assay/All_selection_coefs_426F4.xlsx'
sheet='426F4_all_minD0_for_image'
op_path='/Users/lwoo0005/Documents/An_H_pylori/Clr_Crtl_Fitness_assay/'

"""
inp_path='/Users/lwoo0005/Documents/An_H_pylori/Shami_stuff/partMCE3_allvars_selection_coefs.xlsx'
for pop in ['partAb-']:
    #pop='MCE3_allvars_Clr_rm1tp_sig'
    sheet='MCE3_'+pop+'_allvars_rm1tp_sig'
    op_path='/Users/lwoo0005/Documents/An_H_pylori/Shami_stuff/'

    data=pd.read_excel(open(inp_path,'rb'), sheet_name=sheet)
    #data=data[:600]
    data=data.sort_values('Position')

    #Should also have DNp5, HGT, ancestral, other as metadata--add to selcoef sheet
    pos_list=data['Position'].tolist()
    selcoef_list=data['Coefficient'].tolist()
    lowers_list=data['Lower_CI_bound'].tolist()
    uppers_list=data['Upper_CI_bound'].tolist()
    gene_list=data['Gene'].tolist()
    description_list=data['Description'].tolist()
    mutation_list=data['S/NS'].tolist()
    annotation_list=data['Mutation_annotation'].tolist()
    type_list=data['Type'].tolist()
    pval_list=data['p-value'].tolist()

    """
    pos_list=[10,12,14,23,25]
    selcoef_list=[-0.2,-0.22,-0.18,0.1,0.14]
    lowers_list=[-0.23,-0.25,-0.2,0,0.02]
    uppers_list=[-0.17,-0.19,-0.16,0.2,0.26]
    """

    i=0
    block_dic={}
    block_number=1
    old_lower=0
    old_upper=0
    block_positions=[]
    block_selcoefs=[]
    block_genes=[]
    block_descriptions=[]
    block_mutations=[]
    block_annotations=[]
    block_types=[]
    block_pvals=[]

    for p, s, lower, upper, g, d, m, a, t, pv in zip(pos_list, selcoef_list, lowers_list,
                                             uppers_list, gene_list, description_list,
                                             mutation_list, annotation_list, type_list,
                                             pval_list):
       #print s
       #print old_lower
       #print old_upper
       i+=1
       if i==1:
           block_positions.append(p)
           block_selcoefs.append(s)
           block_genes.append(g)
           block_descriptions.append(d)
           block_mutations.append(m)
           block_annotations.append(a)
           block_types.append(t)
           block_pvals.append(pv)
           block_dic[block_number]=[block_positions,block_selcoefs,block_genes,
                    block_descriptions,block_mutations, block_annotations,
                    block_types, block_pvals]
           old_lower=lower
           old_upper=upper
       else:
           if s >= old_lower and s <= old_upper:
               #print "Within bounds"
               block_positions.append(p)
               block_selcoefs.append(s)
               block_genes.append(g)
               block_descriptions.append(d)
               block_mutations.append(m)
               block_annotations.append(a)
               block_types.append(t)
               block_pvals.append(pv)
               block_dic[block_number]=[block_positions,block_selcoefs,block_genes,
                    block_descriptions,block_mutations, block_annotations,
                    block_types, block_pvals]
               old_lower=lower
               old_upper=upper
           else:
               #print "outside bounds"
               block_positions=[]
               block_selcoefs=[]
               block_genes=[]
               block_descriptions=[]
               block_mutations=[]
               block_annotations=[]
               block_types=[]
               block_pvals=[]
               block_number+=1
               block_positions.append(p)
               block_selcoefs.append(s)
               block_genes.append(g)
               block_descriptions.append(d)
               block_mutations.append(m)
               block_annotations.append(a)
               block_types.append(t)
               block_pvals.append(pv)
               block_dic[block_number]=[block_positions,block_selcoefs,block_genes,
                    block_descriptions,block_mutations, block_annotations,
                    block_types, block_pvals]
               old_lower=lower
               old_upper=upper

    block_positions={}
    for k,v in block_dic.items():
       pos=v[0]
       selcoefs=v[1]
       genes=v[2]
       descriptions=v[3]
       mutations=v[4]
       annotations=v[5]
       types=v[6]
       vals=v[7]
       num_vars=len(types)
       num_HGT=types.count('HGT')
       freq_HGT=float(num_HGT)/float(len(types))
       num_syn=mutations.count("S")
       freq_syn=float(num_syn)/float(len(mutations))
       if 'Coding' in mutations:
           coding_flag='Yes'
           coding_indices = [a for a, x in enumerate(mutations) if x == "Coding"]
           coding_selcoef=', '.join([str(selcoefs[b]) for b in coding_indices])
           coding_pval=', '.join([str(vals[b]) for b in coding_indices])
       else:
           coding_flag='No'
           coding_selcoef=', '.join(['NA'])
           coding_pval=', '.join(['NA'])
       if 'Nonsense' in mutations:
           nonsense_flag='Yes'
           nonsense_indices = [a for a, x in enumerate(mutations) if x == "Nonsense"]
           nonsense_selcoef=', '.join([str(selcoefs[b]) for b in nonsense_indices])
           nonsense_pval=', '.join([str(vals[b]) for b in nonsense_indices])
       else:
           nonsense_flag='No'
           nonsense_selcoef=', '.join(['NA'])
           nonsense_pval=', '.join(['NA'])
       if 'Nonstop' in mutations:
           nonstop_flag='Yes'
           nonstop_indices = [a for a, x in enumerate(mutations) if x == "Nonstop"]
           nonstop_selcoef=', '.join([str(selcoefs[b]) for b in nonstop_indices])
           nonstop_pval=', '.join([str(vals[b]) for b in nonstop_indices])
       else:
           nonstop_flag='No'
           nonstop_selcoef=', '.join(['NA'])
           nonstop_pval=', '.join(['NA'])
       if 'NS' in mutations:
           missense_flag='Yes'
           missense_indices = [a for a, x in enumerate(mutations) if x == "NS"]
           missense_selcoef=', '.join([str(selcoefs[b]) for b in missense_indices])
           missense_pval=', '.join([str(vals[b]) for b in missense_indices])
       else:
           missense_flag='No'
           missense_selcoef=', '.join(['NA'])
           missense_pval=', '.join(['NA'])
       min_pos=min(pos)
       max_pos=max(pos)
       min_gene=genes[pos.index(min_pos)].encode('ascii', 'ignore').decode('ascii')
       max_gene=genes[pos.index(max_pos)].encode('ascii', 'ignore').decode('ascii')
       avg_sc=np.average(selcoefs)
       min_sc=min(selcoefs)
       max_sc=max(selcoefs)
       driver_index=np.argmax(np.abs(selcoefs))
       extreme_sc=selcoefs[driver_index]
       driver=pos[driver_index]
       driver_gene=genes[driver_index].encode('ascii', 'ignore').decode('ascii')
       driver_description=descriptions[driver_index].encode('ascii', 'ignore').decode('ascii')
       driver_mutation=mutations[driver_index].encode('ascii', 'ignore').decode('ascii')
       driver_annotation=annotations[driver_index].encode('ascii', 'ignore').decode('ascii')
       driver_type=types[driver_index].encode('ascii', 'ignore').decode('ascii')
       driver_pval=vals[driver_index]
       block_positions[k]=[str(min_pos)+'-'+str(max_pos),
                           str(abs(max_pos-min_pos)+1),
                           min_gene, max_gene,
                           str(num_vars), str(freq_HGT),
                           str(freq_syn),
                           str(avg_sc), str(min_sc), str(max_sc),
                           str(driver), str(extreme_sc),
                           driver_gene, driver_description,
                           driver_mutation, driver_annotation,
                           driver_type, driver_pval,
                           coding_flag, coding_selcoef, coding_pval,
                           nonsense_flag, nonsense_selcoef, nonsense_pval,
                           nonstop_flag, nonstop_selcoef, nonstop_pval,
                           missense_flag, missense_selcoef, missense_pval
                           ]
    pandas_blocks=pd.DataFrame(block_positions).T
    csv_columns=['Position_range','Block_length',
                 'Start_gene', 'End_gene',
                 'Number_of_vars', 'Frequency_HGT',
                 'Frequency_synonymous',
              'Average_SC', 'Min_SC', 'Max_SC',
              'Putative_driver_pos','Putative_driver_SC',
              'Putative_driver_gene','Putative_driver_description',
              'Putative_driver_mutation','Putative_driver_annotation',
              'Putative_driver_type', 'Putative_driver_p_value',
              'Coding_in_block?', 'Coding_selcef(s)', 'Coding_p_value(s)',
              'Nonsense_in_block?', 'Nonsense_selcoef(s)', 'Nonsense_p_value(s)',
              'Nonstop_in_block?', 'Nonstop_selcoef(s)', 'Nonstop_p_value(s)',
              'Missense_in_block?', 'Missense_selcoef(s)', 'Missense_p_values']
    pandas_blocks.columns=csv_columns
    pandas_blocks.to_csv(op_path+str('/')+sheet+"_selcoef_blocker_more_info.csv",encoding='utf-8')
"""
with open(op_path+str('/')+pop+"_selcoef_blocker_var_type_info.csv",'w') as op:
   writer=csv.writer(op)
   writer.writerow(csv_columns)
   for k,v in block_positions.items():
       writer.writerow([k,v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10]])
"""


from django.db import models

from backend.core.models import TimeStampedModel

class Expense(TimeStampedModel):
    description = models.CharField('descrição', max_length=50)
    payment_date = models.DateField('data de pagamento', null=True, blank=True)
    value = models.DecimalField('valor', max_digits=7, decimal_places=2)
    paid = models.BooleanField('pago', default=False)

    class Meta:
        ordering = ('id',)
        verbose_name = 'despesa'
        verbose_name_plural = 'despesas'

    def __str__(self):
        return self.description


from flask import Flask, request, jsonify, render_template, redirect, current_app
import flask
import json
from slacker import Slacker
import datetime
import os

slack = Slacker(os.getenv('SLACK_KEY'))
app = Flask(__name__)
filters = set()
weightage = {}
messages = []
TYPES_MAPPING = {
        'everything': 0,
        'not important': 1,
        'worth checking': 5,
        'important': 7,
        'urgent': 9
    }
TYPES_MAPPING_REV = {
        0 :'everything',
        1 :'not important',
        5 :'worth checking',
        7 :'important',
        9 :'urgent'
    }

# @app.route('/')
# def hello_world():
    # return 'Hello World!'
    # return redirect('/show/0')

# @app.before_request
# def before_request():
#     flask.g.level = 0

@app.route('/busy',methods=['POST'])
def test_conn():
    return 'Test'

@app.route('/testEvents',methods=['POST'])
def test_event():
    print(request)
    print(request.data)
    in_req = json.loads(request.data.decode('utf-8'))
    # print(request.data)
    # slack.chat.post_message('#general', in_req['event']['text'])
    try:
        message = in_req['event']['text']
        user_id = in_req['event']['user']
        user_details = slack.users.profile.get(user_id).body
        user_profile = user_details['profile']['real_name']
        user_pic_url = user_details['profile']['image_72']
        timestamp = in_req['event_time']
        time = datetime.datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')
        channel_id = in_req['event']['channel']
        if channel_id.startswith('C'):
            channel = slack.channels.info(channel_id).body['channel']['name']
        else:
            channel = 'Direct Message'
        level = compute_levels(message)
        if level >= 7 and current_app.level < level:
            slack.chat.post_message(channel=channel_id, text='Sorry I am pretty busy right now. I will get back to you shortly.')

        messages.append({'message':message,'user':user_profile,'pic':user_pic_url, 'time':time,'level':level, 'channel':channel})
        # messages[message] = compute_levels(message)
        print(messages)#,user_profile,user_pic_url,timestamp)
    except Exception as e:
        print(repr(e))
    return 'Ok'
    # return in_req['event']['text']
    # return jsonify({'challenge':in_req['challenge']})
    # return 'Test'

@app.route('/set/<topic>/<int:level>', methods=['GET'])
# @require_post_data
def set_topic(topic,level):
    filters.add(topic)
    weightage[topic] = level
    print(filters, weightage)
    # print(request.args)#, repr(level), topic)
    return 'Ok'

@app.route('/tell/<int:level>')
def tell_level(level):
    filtered = filter_messages(level)
    res = []
    for fm in filtered:
        res_item = {}
        res_item['from'] = 'User '+ fm['user']
        res_item['message'] = fm['message']
        res_item['channel'] = fm['channel']
        # res_item['time'] = datetime.timenow().replace(microsecond=0) - time.strptime('%Y-%m-%d %H:%M:%S')
        res.append(res_item)
    return jsonify(res)

@app.route('/describe')
def describe_rules():
    return jsonify(weightage)

def filter_messages(level):
    filtered = []
    for message in messages:
        key = message['message']
        value = message['level']
        print(key,value)
        if value >= level:
            filtered.append(message)
    return filtered

@app.route('/')
def show_messages():
    # level = flask.g.get('level', 0)
    try:
        level = current_app.level
        # level = flask.g.get('level',0)
    except Exception as e:
        print(repr(e))
        current_app.level = 0
        level = 0
    filtered = filter_messages(level)
    return render_template('dashboard.html', response=filtered, heading=TYPES_MAPPING_REV[level])

@app.route('/show/<int:level>')
def showAlexa(level):
    # flask.g.level=level
    current_app.level = level
    return 'Ok'
    # return redirect('/showAlexa/{0}'.format(level))

def compute_levels(message):
    weight = 0
    count = 0
    for word in filters:
        if word in message:
            weight += weightage[word]
            count += 1
    if count !=0:
        return weight/count
    else:
        return 0

if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)