from iexcloud.iexcloud import iexCloud
from parameters import engine_string
from db_ingestion.models import Tickers
import pandas as pd
#import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from dash.dependencies import Input
from dash.dependencies import Output
import plotly.express as px
import plotly.graph_objs as go
from django_plotly_dash import DjangoDash
from searchstocks.views import read_ticker_symbols
from searchstocks.views import get_symbols
from searchstocks.views import get_sectors
from searchstocks.views import dropdown_values
from searchstocks.views import colormap_value
from searchstocks.views import stock_information
from searchstocks.views import get_company_stats

##############################################################################################
#Parameters and instantiating classes
obj_iexcloud = iexCloud()
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = DjangoDash('searchstocks', external_stylesheets=external_stylesheets)

# def read_ticker_symbols():
#     try:
#         df_tickers = pd.read_sql('SELECT * FROM db_ingestion_tickers;', engine_string)
#         df_tickerstats = pd.read_sql('SELECT * FROM db_ingestion_tickerstats', engine_string)
#         df = pd.merge(df_tickers, df_tickerstats, how='inner', on='Symbol')
#         return df
#     except Exception as e:
#         print(str(e))

# def get_symbols():
#     dropdown_options = []
#     df = read_ticker_symbols()
#     for index, row in df.iterrows():
#         dropdown_options.append({'label': row['Name'], 'value': row['Symbol']})
#     return dropdown_options

# def get_sectors():
#     dropdown_options = []
#     df = read_ticker_symbols()
#     sector_lst = list(df['Sector'].unique())
#     for i in sector_lst:
#         dropdown_options.append({'label':i, 'value':i})
#     return dropdown_options

# def dropdown_values(column_name):
#     dropdown_options = []
#     df = read_ticker_symbols()
#     lst = list(df[column_name].unique())
#     for i in lst:
#         dropdown_options.append({'label':i, 'value':i})
#     return dropdown_options

# def colormap_value(table_name, range):
#     try:
#         df_colormaps = pd.read_sql(f'SELECT * FROM db_ingestion_{table_name}_colormaps;', engine_string)
#         df_colormaps = df_colormaps[df_colormaps['Metric'] == range]
#         print(df_colormaps)

#         color = df_colormaps['Color'].iloc[0]
#         return color
#     except Exception as e:
#         print(str(e))

# def stock_information(ticker, metric):
#     df_tickerstats = pd.read_sql(f'SELECT * FROM db_ingestion_tickerstats', engine_string)
#     df_tickerstats = df_tickerstats[df_tickerstats['Symbol'] == ticker]

#     if metric == 'marketcap':
#         updated_metric = 'Market Capitalization Ranges'
#     if metric == 'dividend':
#         updated_metric = 'Dividend Ranges'
#     if metric == 'ebitda':
#         updated_metric = 'EBITDA Ranges'
#     if metric == 'peratio':
#         updated_metric = 'PE Ratio Ranges'
#     if metric == 'revenue':
#         updated_metric = 'Revenue Ranges'

#     range = df_tickerstats[updated_metric].iloc[0]

#     return range

# def get_company_stats():
#     try:
#         df = pd.read_sql(f'SELECT * FROM db_ingestion_tickerstats', engine_string)
#     except Exception as e:
#         print(str(e))

#     return df

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

#App layout
app.layout = html.Div([
    dcc.Dropdown(id='stockselector',
                options=get_symbols(),
                multi=True,
                value = [],
                clearable = True,
                placeholder="Companies listed on S&P500",
                style={'backgroundColor': '#1E1E1E'}),

    dcc.Dropdown(id='sectorselector',
                options=get_sectors(),
                multi=True,
                clearable = True,
                value = [],
                placeholder="Sectors listed on S&P500",
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.RadioItems(
        id='colormap',
        options=[
            {'label': 'Market Capitalization Ranges', 'value': 'marketcap'},
            {'label': 'Dividend Ranges', 'value': 'dividend'},
            {'label': 'PE Ratio Ranges', 'value': 'peratio'},
            {'label': 'Revenue Ranges', 'value': 'revenue'},
            {'label': 'EBITDA Ranges', 'value': 'ebitda'},
            {'label': 'None', 'value': 'none'}
        ],
        inline=True,
        value='none',
        style={"color": "white"},
    ),

    dcc.Graph(id="time-series-chart", config={'displayModeBar': False}),

    html.Br(),

    html.Button('Update Graphh',
                n_clicks = 0,
                id='button',
                style = {
                'display':'flex',
                'justifyContent':'center',
                'align-items':'center',
                'margin': 'auto'
                }
    ),

    html.Br(),

    dcc.Dropdown(id='marketcap_selector',
                options=[
                    {'label': "0 - $250Millon", 'value': "0 - $250Million"},
                    {'label': "$250Million - $500Million", 'value': "$250Million - $500Million"},
                    {'label': "$500Million - $1Billion", 'value': "$500Million - $1Billion"},
                    {'label': '$1Billion - $10Billion', 'value': '$1Billion - $10Billion'},
                    {'label': '$10Billion - $50Billion', 'value': '$10Billion - $50Billion'},
                    {'label': '$50Billion - $100Billion', 'value': '$50Billion - $100Billion'},
                    {'label': '$100Billion - $500Billion', 'value': '$100Billion - $500Billion'},
                    {'label': 'Over $500Billion ', 'value': 'Over $500Billion'},
                ],
                multi=True,
                clearable = True,
                value = [],
                placeholder="Filter Sectors by Market Capitalization",
                searchable=True,
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.Dropdown(id='dividend_selector',
                options=[
                    {'label': '0% - 1%', 'value': '0% - 1%'},
                    {'label': '1% - 2.5%', 'value': '1% - 2.5%'},
                    {'label': '2.5% - 5%', 'value': '2.5% - 5%'},
                    {'label': '5% - 7.5%', 'value': '5% - 7.5%'},
                    {'label': '7.5% - 10%', 'value': '7.5% - 10%'},
                    {'label': '10% - 15%', 'value': '10% - 15%'},
                    {'label': '15% - 20%', 'value': '15% - 20%'},
                    {'label': 'Greater than 20%', 'value': 'Greater than 20%'},

                ],
                multi=True,
                clearable = True,
                value = [],
                placeholder="Filter Sectors by Dividend Yield",
                searchable=False,
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.Dropdown(id='pe_selector',
                options=[
                    {'label': 'Less than -10', 'value': 'Less than -10'},
                    {'label': '-10 - 0', 'value': '-10 - 0'},
                    {'label': '0 - 10', 'value': '0 - 10'},
                    {'label': '10 - 20', 'value': '10 - 20'},
                    {'label': '20 - 30', 'value': '20 - 30'},
                    {'label': '30 - 40', 'value': '30 - 40'},
                    {'label': '40 - 50', 'value': '40 - 50'},
                    {'label': '50 - 75', 'value': '50 - 75'},
                    {'label': '75 - 100', 'value': '75 - 100'},
                    {'label': 'Greater than 100', 'value': 'Greater than 100'},
                ],
                multi=True,
                clearable = True,
                value = [],
                placeholder="Filter Sectors by PE Ratio Scores",
                searchable=False,
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.Dropdown(id='revenue_selector',
                options=[
                    {'label': '$0 - $250Million', 'value': '$0 - $250Million'},
                    {'label': '$250Million - $500Million', 'value': '$250Million - $500Million'},
                    {'label': '$500Million - $1Billion', 'value': '$500Million - $1Billion'},
                    {'label': '$1Billion - $10Billion', 'value': '$1Billion - $10Billion'},
                    {'label': '$10BBillion - $50Billion', 'value': '$10Billion - $50Billion'},
                    {'label': '$50Billion - $100Billion', 'value': '$50Billion - $100Billion'},
                    {'label': 'Greater than $100Billion', 'value': 'Greater than $100Billion'},
                ],
                multi=True,
                clearable = True,
                value = [],
                placeholder="Filter Sectors by Revenue",
                searchable=False,
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.Dropdown(id='ebitda_selector',
                options=[
                    {'label': 'Less than -$100Million', 'value': 'Less than -$100Million'},
                    {'label': '-$100Million - -$50Million', 'value': '-$100Million - -$50Million'},
                    {'label': '-$50Million - $0', 'value': '-$50Million - $0'},
                    {'label': '$0 - $250Million', 'value': '$0 - $250Million'},
                    {'label': '$250Million - $500Million', 'value': '$250Million - $500Million'},
                    {'label': '$500Million - $1Billion', 'value': '$500Million - $1Billion'},
                    {'label': '$1Billion - $10Billion', 'value': '$1Billion - $10Billion'},
                    {'label': 'Greater than $10Billion', 'value': 'Greater than $10Billion'},
                ],
                multi=True,
                clearable = True,
                value = [],
                placeholder="Filter Sectors by Earnings (EBITDA)",
                searchable=False,
                style={'backgroundColor': '#1E1E1E'}),

    html.Br(),

    dcc.Graph(id="value-finder", config={'displayModeBar': False}),

])

#Callbacks
@app.callback(
    Output("time-series-chart", "figure"),
    [Input("stockselector", "value"),
    Input("sectorselector", "value"),
    Input("marketcap_selector", "value"),
    Input("dividend_selector", "value"),
    Input("pe_selector", "value"),
    Input("revenue_selector", "value"),
    Input("ebitda_selector", "value"),
    Input("colormap", "value")]
    )

def time_series_stock(ticker_dropdown, sector_dropdown, marketcap_selector,
                    dividend_selector, pe_selector, revenue_selector,
                    ebitda_selector, colormap):

    graphs = []

    #Flatten list
    if any(isinstance(i, list) for i in ticker_dropdown):
        ticker_dropdown = [item for elem in ticker_dropdown for item in elem]

    #graphs = []

    #Draw time series of a single stock
    for ticker in ticker_dropdown:
        stock_df = obj_iexcloud.get_max_time_series_df(ticker)
        graphs.append(go.Scatter(
            x = stock_df['Date'],
            y = stock_df[ticker],
            mode = 'lines',
            name = ticker,
            textposition = 'bottom center',
        ))

    parameters = {
        'Market Capitalization Ranges': marketcap_selector,
        'Dividend Ranges': dividend_selector,
        'PE Ratio Ranges': pe_selector,
        'Revenue Ranges': revenue_selector,
        'EBITDA Ranges': ebitda_selector
    }
    filled_parameters = {}
    for key, value in parameters.items():
        if value:
            filled_parameters[key] = value

    #Draw time series of sectors and filter
    sector_df = read_ticker_symbols()
    sector_df = sector_df[sector_df['Sector'].isin(sector_dropdown)]
    print(sector_df)
    #if marketcap_dropdown:
    for key in  filled_parameters:
        #sector_df = sector_df.loc[(sector_df['Market Capitalization Ranges'].isin(marketcap_dropdown))]
        sector_df = sector_df.loc[(sector_df[key].isin(filled_parameters[key]))]
    stock_list = list(sector_df['Symbol'])
    for stock in stock_list:
        stock_df = obj_iexcloud.get_max_time_series_df(stock)
        #Choose color based on metric
        if colormap == 'none':
            graphs.append(go.Scatter(
            x = stock_df['Date'],
            y = stock_df[stock],
            mode = 'lines',
            name = stock,
            textposition = 'bottom center',
            ))
        else:
            metric = colormap
            range = stock_information(stock, metric)
            color = colormap_value(metric, range)

            graphs.append(go.Scatter(
            x = stock_df['Date'],
            y = stock_df[stock],
            mode = 'lines',
            name = stock,
            textposition = 'bottom center',
            line=dict(color=f'#{color}'),
            ))

    if any(isinstance(i, list) for i in graphs):
        graphs = [item for elem in graphs for item in elem]

    fig = {
            'data': graphs,
            'layout': go.Layout(
            paper_bgcolor='rgba(30, 30, 30, 30)',
            plot_bgcolor='rgba(30, 30, 30, 30)',
            autosize=True,
            height = 550,
            xaxis = {'showgrid':True,
                'gridwidth':1,
                'gridcolor':'Grey',
                'color': 'White',
                'rangeselector': {
                    'buttons':list([
                            dict(count=1, label="1m", step="month", stepmode="backward"),
                            dict(count=6, label="6m", step="month", stepmode="backward"),
                            dict(count=1, label="YTD", step="year", stepmode="todate"),
                            dict(count=1, label="1y", step="year", stepmode="backward"),
                            dict(count=5, label="5y", step="year", stepmode="backward"),
                            dict(step="all")
                            ])
                        }
                    },
            yaxis = {'showgrid':True,
                'gridwidth':1,
                'gridcolor':'Grey',
                'color': 'White',
                    },
            legend=dict(
                font=dict(
                    color="white"
                    ),
                )
            )
        }

    return fig

@app.callback(
    Output("value-finder", "figure"),
    [Input("stockselector", "value"),
    Input("sectorselector", "value")]
    #Input("marketcap_selector", "value"),
    #Input("dividend_selector", "value"),
    #Input("pe_selector", "value"),
    #Input("revenue_selector", "value"),
    #Input("ebitda_selector", "value")]
    )

def value_finder(ticker_dropdown, sector_dropdown):

    #Flatten list
    if any(isinstance(i, list) for i in ticker_dropdown):
        ticker_dropdown = [item for elem in ticker_dropdown for item in elem]

    value_finder_df = read_ticker_symbols()
    value_finder_df['value'] = ((value_finder_df['Share Price'] -
                                value_finder_df['200 Day MA']) / value_finder_df['Share Price']) * 100

    value_finder_df = value_finder_df[value_finder_df['Symbol'].isin(ticker_dropdown)]

    fig = px.bar(value_finder_df, x="Symbol", y="value",
                color="Symbol")

    if sector_dropdown:
        if any(isinstance(i, list) for i in sector_dropdown):
            sector_dropdown = [item for elem in sector_dropdown for item in elem]

        value_finder_df = read_ticker_symbols()
        value_finder_df['value'] = ((value_finder_df['Share Price'] -
                                    value_finder_df['200 Day MA']) / value_finder_df['Share Price']) * 100

        value_finder_df = value_finder_df[value_finder_df['Sector'].isin(sector_dropdown)]

        #df_metrics = get_company_stats()

        #value_finder_df = pd.merge(value_finder_df, df_metrics[['Symbol', 'PE Ratio Ranges']], how='left', on='Symbol')

        fig = px.bar(value_finder_df,
                    x="Symbol",
                    y="value",
                    #color="PE Ratio Ranges",
                    color="Symbol",

                    )

    if not sector_dropdown and not ticker_dropdown:
        value_finder_df = read_ticker_symbols()
        value_finder_df['value'] = ((value_finder_df['Share Price'] -
                                    value_finder_df['200 Day MA']) / value_finder_df['Share Price']) * 100

        value_finder_df = value_finder_df.sort_values(by=['value'])
        value_finder_df = value_finder_df.head(15)

        fig = px.bar(value_finder_df,
                    x="Symbol",
                    y="value",
                    #color="PE Ratio Ranges",
                    color="Sector",
                    )

    fig.update_layout(autosize=True,
                    height=450,
                    paper_bgcolor='rgba(30, 30, 30, 30)',
                    plot_bgcolor='rgba(30, 30, 30, 30)',
                    xaxis = {'showgrid':True,
                            'gridwidth':1,
                            'gridcolor':'Grey',
                            'color': 'White'},
                    yaxis = {'showgrid':True,
                            'gridwidth':1,
                            'gridcolor':'Grey',
                            'color': 'White'},
                    legend=dict(
                    font=dict(
                        color="white"
                    ),
                )
            )

    return fig


import math

import numpy as np
from matplotlib import pyplot as plt
import random
alpha = 10E-2
def ex2_a():
    r1_List = []
    r2_List = []
    mean = [3, 3]
    cov = [[1, 0], [0, 1]]
    a = np.random.multivariate_normal(mean, cov, 500).T
    mean = [-3, -3]
    cov = [[2, 0], [0, 5]]
    b = np.random.multivariate_normal(mean, cov, 500).T
    c = np.concatenate((a, b), axis=1)
    c = c.T
    np.random.shuffle(c)
    c = c.T
    x = c[0]
    y = c[1]
    plt.plot(x, y, 'x',alpha=0.2)
    r1 = random.choice(c.T)
    r2 = random.choice(c.T)
    iterations = 10
    d1 = np.array([0,0])
    d2 = np.array([0, 0])
    for i in range(iterations):
        for point in c.T:
                r1Close: float = np.sqrt((r1[0] - point[0]) ** 2 + (r1[1] - point[1]) ** 2)
                r2Close: float = np.sqrt((r2[0] - point[0]) ** 2 + (r2[1] - point[1]) ** 2)
                if r1Close < r2Close:
                    d1 = d1 + (point - r1)
                else:
                    d2 = d2 + (point - r2)
        r1 = r1 + (alpha/1000)*d1
        r2 = r2 + (alpha / 1000) * d2
        r1_List.append((r1[0], r1[1]))
        r2_List.append((r2[0], r2[1]))
    r1_List_NPArray_T = np.asarray(r1_List).T
    r2_List_NPArray_T = np.asarray(r2_List).T

    plt.scatter(r1_List_NPArray_T[0], r1_List_NPArray_T[1],label = "r1_list")
    plt.scatter(r2_List_NPArray_T[0], r2_List_NPArray_T[1],label = "r2_list")
    plt.legend()
    plt.axis('equal')
    plt.show()

def ex2_b():
    r1_List = []
    r2_List = []
    mean = [3, 3]
    cov = [[1, 0], [0, 1]]
    a = np.random.multivariate_normal(mean, cov, 500).T
    mean = [-3, -3]
    cov = [[2, 0], [0, 5]]
    b = np.random.multivariate_normal(mean, cov, 500).T
    c = np.concatenate((a, b), axis=1)
    c = c.T
    np.random.shuffle(c)
    c = c.T
    x = c[0]
    y = c[1]
    #plt.plot(x, y, 'x',alpha=0.2)
    r1 = random.choice(c.T)
    r2 = random.choice(c.T)
    iterations = 10
    d1 = np.array([0,0])
    d2 = np.array([0, 0])

    closer_r1_cluster_a = []
    closer_r1_cluster_b = []
    closer_r2_cluster_a = []
    closer_r2_cluster_b = []
    a_transposed = a.T
    b_transposed = b.T

    for i in range(iterations):
        for point in c.T:
                r1Close: float = np.sqrt((r1[0] - point[0]) ** 2 + (r1[1] - point[1]) ** 2)
                r2Close: float = np.sqrt((r2[0] - point[0]) ** 2 + (r2[1] - point[1]) ** 2)
                if r1Close < r2Close:
                    d1 = d1 + (point - r1)
                else:
                    d2 = d2 + (point - r2)
                if r1Close < r2Close:
                    if point in a_transposed:
                        closer_r1_cluster_a.append(point)
                    elif point in b_transposed:
                        closer_r1_cluster_b.append(point)
                else:
                    if point in a_transposed:
                        closer_r2_cluster_a.append(point)
                    elif point in b_transposed:
                        closer_r2_cluster_b.append(point)
        r1 = r1 + (alpha/1000)*d1
        r2 = r2 + (alpha / 1000) * d2
        r1_List.append((r1[0], r1[1]))
        r2_List.append((r2[0], r2[1]))
    closer_r1_cluster_a_transposed= np.asarray(closer_r1_cluster_a).T
    closer_r1_cluster_b_transposed= np.asarray(closer_r1_cluster_b).T
    closer_r2_cluster_a_transposed= np.asarray(closer_r2_cluster_a).T
    closer_r2_cluster_b_transposed= np.asarray(closer_r2_cluster_b).T

    if closer_r1_cluster_a_transposed.size > 0:
        plt.scatter(closer_r1_cluster_a_transposed[0], closer_r1_cluster_a_transposed[1], label="closer-r1-cluster-a",alpha=0.1)
    if closer_r1_cluster_b_transposed.size>0:
        plt.scatter(closer_r1_cluster_b_transposed[0], closer_r1_cluster_b_transposed[1], label="closer-r1-cluster-b",alpha=0.1)
    if closer_r2_cluster_a_transposed.size>0:
        plt.scatter(closer_r2_cluster_a_transposed[0], closer_r2_cluster_a_transposed[1], label="closer-r2-cluster-a",alpha=0.1)
    if closer_r2_cluster_b_transposed.size>0:
        plt.scatter(closer_r2_cluster_b_transposed[0], closer_r2_cluster_b_transposed[1], label="closer-r2-cluster-b",alpha=0.1)

    plt.scatter(r1[0],r1[1],label="R1")
    plt.scatter(r2[0],r2[1],label="R2")

    plt.legend(loc=2, prop={'size': 6})
    plt.axis('equal')
    #plt.show()

def ex2_c():
    number_of_experiments = 9
    grid: int = int(math.sqrt(number_of_experiments))
    for i in range(number_of_experiments):
        plt.subplot(grid, grid, i + 1)
        ex2_b()
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    #ex2_a()
    #ex2_b()
    ex2_c()


"""
SCC0276 — Machine Learning

Project: Alzheimer disease detection

Authors:
- Alice Valença De Lorenci - 11200289
- Gabriel Soares Gama - 10716511
- Marcos Antonio Victor Arce - 10684621

The following code was reproduced from:
    https://github.com/KaueTND/Brain_Extraction_T1wMRI/blob/main/Workflow_jupyter.ipynb
"""

# libraries
from PIL import Image
from scipy import signal as sci
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.morphology import binary_fill_holes, binary_opening
import matplotlib.image as mpimg
from skimage import morphology as morph
from scipy import ndimage as nd
import sys, os
from skimage.filters import (
    threshold_otsu,
    threshold_isodata,
    threshold_li,
    threshold_local,
    threshold_minimum,
)
from skimage import feature
from skimage.filters import threshold_local as threshold_adaptative
import heapq
import matplotlib.patches as mpatches
from skimage.morphology import convex_hull_image
import pandas as pd
import seaborn as sns
from scipy.signal import convolve2d as sc_conv
from matplotlib.colors import colorConverter
import matplotlib as mpl
import time
import cv2 as cv

def save_without_spacing(nome, fig):
    import matplotlib.pyplot as plt
    from matplotlib.ticker import NullLocator

    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(NullLocator())
    plt.gca().yaxis.set_major_locator(NullLocator())
    plt.savefig(nome, bbox_inches="tight", pad_inches=0, dpi=fig.dpi)

# remove background noise
def remove_ruido_fundo(imagem, Ti=0):
    if Ti == 0:
        Ti = np.mean(imagem)
    imagem_filtrada = sci.medfilt(imagem, [3, 3])
    ti = imagem_filtrada > Ti
    mascara = binary_fill_holes(ti)

    return [Ti, imagem * mascara]

# adjust contrast
def ajuste_contraste(img):
    A = img
    L = np.max(A.ravel())
    B = (L - 1) - A
    SE1 = morph.ball(3)[3]
    C = morph.closing(B, SE1)
    L = np.max(C.ravel())
    D = (L - 1) - C
    Adiff = A - D
    return np.clip(A + Adiff, 0, 255)

# image binarization, used to find conex components
def binariza(imagem, Cerebro=True):
    if Cerebro:
        t = threshold_otsu(imagem)
    else:  # Crânio
        t = 0
    imagem_binaria = imagem.copy()
    imagem_binaria[imagem_binaria <= t] = 0
    imagem_binaria[imagem_binaria > t] = 1
    return imagem_binaria

# detect connected component border
def detecta_borda_conexa(imagem_binaria):
    cranio_convexo = convex_hull_image(binary_fill_holes(imagem_binaria))  # preenche a imagem
    borda_cranio = feature.canny(cranio_convexo)  # extrai a borda
    return borda_cranio

# detect connected component
def detecta_componente_conexa(imagem_binaria, mostrar_Passos=False):
    label_aux = morph.label(imagem_binaria)
    label_ret = morph.label(imagem_binaria)
    if mostrar_Passos == True:
        plt.figure()
        plt.subplot(121)
        plt.imshow(label_ret, "flag")
        # plt.title('Componentes Conexas(Labels)')
        # save_without_spacing("TrabalhoMeninge_7_"+str(0)+"comp.png")
    valor_disco = 0

    # Passo 1 - Detecção da Borda do Crânio via Canny
    contorno_cranio_binario = detecta_borda_conexa(imagem_binaria)
    if mostrar_Passos == True:
        plt.subplot(122)
        plt.imshow(contorno_cranio_binario, "gray")
        plt.title("Detecção Borda Canny")
        plt.figure()

    # Passo 2 - Detecção da Tonalidade do Fundo
    tonalidade_fundo = np.argmax(np.bincount(label_ret[0:20, 0:20].ravel()))
    for ab in range(10):
        # print(ab)
        contorno_cranio = label_ret[contorno_cranio_binario == True]
        [IMX, IMY] = imagem_binaria.shape

        # Passo 3 - Detecção da Parte Central do Cérebro (sem fundo)
        array_centro = label_ret[IMX // 2 - 25 : IMX // 2 + 25, IMY // 2 - 25 : IMY // 2 + 25]
        array_centro = array_centro[array_centro != tonalidade_fundo]
        max_centro = np.argmax(
            np.bincount(array_centro.ravel())
        )  # retorna o pixel mais frequente na imagem array_centro, correspondendo ao valor do cérebro

        # Passo 4 - Verificação da Presença da Intensidade da Borda no Centro
        if max_centro in contorno_cranio:
            valor_disco = valor_disco + 1
            label_ret = morph.opening(label_aux, morph.disk(valor_disco))
            label_ret = morph.label(label_ret)
            # plt.imshow(label_ret)
            # save_without_spacing("TrabalhoMeninge_7_"+str(valor_disco)+"comp.png")
        else:
            break

    # print(valor_disco)
    if valor_disco == 0:
        label_ret = label_aux
    return [label_ret, tonalidade_fundo, array_centro]

# extract connected component
def extrai_maior_componente(LC, tonalidade_fundo, array_centro=0, mostrar_Passos=False):
    # print(type(array_centro))
    c1 = LC.copy()

    if mostrar_Passos == True:
        plt.figure(figsize=(8, 8))
        plt.subplot(121)
        plt.imshow(c1, "gray")
        plt.axis("off")
        plt.title("Componentes Conexas")
    hist = np.bincount(LC.ravel())
    index = heapq.nlargest(1, range(len(hist)), key=hist.__getitem__)[-1]

    # Se a maior componente conexa for o fundo, pegue a segunda maior componente
    if index == tonalidade_fundo:
        index = heapq.nlargest(2, range(len(hist)), key=hist.__getitem__)[-1]

    # Rerotulação das componentes conexas baseado na ocorrencia de pixels no centro
    if type(array_centro) == np.ndarray:
        matriz_substituicao = np.isin(c1, np.unique(array_centro[array_centro != tonalidade_fundo]))
        c1_k = convex_hull_image(matriz_substituicao)
        if mostrar_Passos == True:
            plt.figure()
            plt.imshow(matriz_substituicao, "gray")
            plt.axis("off")
            # plt.title('Agrupamento Conexo')
            # save_without_spacing("TrabalhoMeninge_8_Agrupamento.png")
        return [matriz_substituicao, c1_k]
        # c1[matriz_substituicao] = index

    c1[c1 == index] = 1000
    c1[c1 < 1000] = 0
    c1[c1 == 1000] = 1
    c1_k = convex_hull_image(c1)
    return [c1, c1_k]

# apply skull stripping flow
def skullStripping(im1):
    """
    Arguments:
    - im1: original png image (array format)

    Return:
    - img: skull stripped image
    """
    # im1 = Image.open(fileName)
    img = np.array(im1)
    ruido = three_segments(220, 240, 50, 210)
    ruido = ruido[::-1]
    [media, img] = remove_ruido_fundo(img)
    Aenhanced = ajuste_contraste(img)
    Gbin = binariza(Aenhanced)
    [LC, tonalidade_fundo, array_centro] = detecta_componente_conexa(Gbin, False)
    [c1, c1_k] = extrai_maior_componente(LC, tonalidade_fundo, array_centro, False)

    img = img * c1_k

    return img


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

"""
__title__ = ""
__author__ = "Shuang"
__mtime__ = "2016/7/25"

"""
from collections import defaultdict

from Transaction import Transaction

def get_transactions(read_filename):
	"""
	从文件中获取事务，返回事务列表及词汇-事务列表字典
	"""
	trans_list = []
	word_tran_dict = {}		# 词-事务字典，key=词汇，value=包含该词汇的事务id列表, id起始值为0

	f = open(read_filename, 'r')
	f_info = f.readlines()
	for i in range(len(f_info)):
		line = f_info[i]
		item_dict = defaultdict(lambda: 0)
		for item in line.split():
			name = item.split(':')[0]
			num = item.split(':')[1]
			item_dict[name] = num
			if item in word_tran_dict:
				word_tran_dict[item].append(i)
			else:
				word_tran_dict[item] = [i]
		trans = Transaction(i, item_dict, 1, 0)
		trans_list.append(trans)
	return trans_list, word_tran_dict

def get_item_weight(read_filename):
	""" 获取词汇的外部效用值，返回词汇外部效用字典及词汇id字典"""
	word_weight_dict = defaultdict(lambda: 0)
	word_id_dict = defaultdict(lambda: 0)

	f = open(read_filename, 'r')
	line = f.readline()
	i = 0
	while line:
		info = line.split(' ')
		word_weight_dict[info[0]] = info[1]
		word_id_dict[info[0]] = i
		line = f.readline()
		i += 1
	return word_weight_dict, word_id_dict


__copyright__ = "Copyright © Stichting SciPost (SciPost Foundation)"
__license__ = "AGPL v3"

from django.contrib import admin

from .models import Webinar, WebinarRegistration

class WebinarRegistrationInline(admin.TabularInline):
    model = WebinarRegistration

class WebinarAdmin(admin.ModelAdmin):
    inlines = [
        WebinarRegistrationInline,
    ]

admin.site.register(Webinar, WebinarAdmin)


import numpy as np

import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use("seaborn-darkgrid")
plt.rcParams.update({
    "text.usetex": True,
    "font.size": 14}
)

from linear_model_polynomial import *

# Load the data
DATAPATH = "../../../DATA/olympic100m.txt"
data = np.loadtxt(DATAPATH, delimiter=",")

t_full = data[:,1] # Target
x_full = data[:,0]
# Data indices for validation and training data
idx_val = x_full > 1979
idx_train = x_full <= 1979
#
x_val = x_full[idx_val]
t_val = t_full[idx_val]
#
x = x_full[idx_train]
t = t_full[idx_train]

# Shift and rescale the data to avoid numerical problems with large numbers
x = x - x_full[0]
x = 0.25*x
# also do this for validation input
x_val = x_val - x_full[0]
x_val = 0.25*x_val

for Npoly in range(1,9):
    X, w = fit_polynomial(x, t, Npoly)
    t_val_pred = predict_polynomial(w, x_val)
    loss = np.sum( (t_val_pred - t_val)**2/len(t_val) )
    print("Npoly = %2d   loss = %10.5f" % (Npoly, loss))


import numpy as np
import matplotlib.pyplot as plt
plt.style.use('classic')
plt.rcParams['lines.linewidth'] = 1

x = 100000
X=np.arange(x)

for i in range(15):
    Yr=np.random.choice([-1,1],x)
    Y=[0]
    Y[0]=Yr[0]
    for el in range(1,x):
        Y.append(Y[el-1]+Yr[el])
    plt.plot(X, Y)

plt.savefig('flip.png', format="png")
plt.show()


from flask import Flask
from lcu_driver import Connector
import GetChamps as GetChamps
from threading import Thread
import json
import sys

app = Flask(__name__)
connector = Connector()
games_data = GetChamps.get_champs()
data = []
# fired when LCU API is ready to be used
@connector.ready
async def connect(connection):
    print('LCU API is ready to be used.')

# fired when League Client is closed (or disconnected from websocket)
@connector.close
async def disconnect(_):
    print('The client have been closed!')
    await connector.stop()

# subscribe to '/lol-summoner/v1/current-summoner' endpoint for the UPDATE event
# when an update to the user happen (e.g. name change, profile icon change, level, ...) the function will be called
@connector.ws.register('/lol-summoner/v1/current-summoner', event_types=('UPDATE',))
async def icon_changed(connection, event):
    print(f'The summoner {event.data["displayName"]} was updated.')

@connector.ws.register('/lol-champ-select/v1/session', event_types=('UPDATE',))
async def selection(connection, event):
    myTeam,enemyTeam = GetChamps.get_selected_champ(event.data)
    result = GetChamps.best_pick(myTeam ,enemyTeam,games_data)
    global data
    data  = result
    sys.stdout.flush()

@app.route("/members")
def members():
    return json.dumps(data)
    #return {"members":["Member1","Member2","Member3"]}

def startconnector():
    connector.start()
if __name__ == "__main__":
    # starts the connector
    Thread(target = startconnector).start()
    app.run(debug=True)


#!/usr/bin/env python3
import rospkg
import rospy
import numpy as np
import yaml
from local_map.map_logic import Mapper
from geometry_msgs.msg import PoseStamped, Point32
from sensor_msgs.msg import PointCloud
from std_msgs.msg import Header
from teraranger_array.msg import RangeArray

class Server:
    def __init__(self):
        rospack = rospkg.RosPack()
        with open(rospack.get_path("phx_launch") + "/../config/hardware_config.yaml") as f:
            mechanical_config = yaml.load(f, Loader=yaml.SafeLoader)
        dirOfRangeSensors = mechanical_config["direction_of_range_sensors"]
        distCenterDroneRangeSens = mechanical_config["dist_of_range_sensors_from_center"]
        with open(rospack.get_path("phx_launch") + "/../config/software_config.yaml") as f:
            software_config = yaml.load(f, Loader=yaml.SafeLoader)
        maxMapAge = software_config["max_age_map_point"]
        self.mapper = Mapper(np.array(dirOfRangeSensors), distCenterDroneRangeSens, maxMapAge)
        self.pub = rospy.Publisher("phx/local_map", PointCloud, queue_size=1)
        self.pos = None

    def ranges_callback(self, msg: RangeArray):
        if self.pos is None:
            # We have still not received the first pose from the FC
            return
        ranges = np.array(list(map(lambda x: x.range, msg.ranges)))
        worldmap = self.mapper.update(ranges, self.pos, self.rot)
        points = list(map(lambda x: Point32(x[0], x[1], x[2]), worldmap))
        header = Header()
        header.stamp = msg.header.stamp
        header.frame_id = "map"  # Needs to correspond to the settings in rviz.
        msg = PointCloud(header, points, [])
        self.pub.publish(msg)

    def pose_callback(self, msg: PoseStamped):
        self.pos = np.array((msg.pose.position.x, msg.pose.position.y, msg.pose.position.z,))
        self.rot = np.array(
            (msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z,))

if __name__ == '__main__':
    rospy.init_node('local_mapper')

    server = Server()

    rospy.Subscriber("/mavros/local_position/pose", PoseStamped, server.pose_callback)
    rospy.Subscriber('/multiflex_1/ranges_raw', RangeArray, server.ranges_callback)
    rospy.loginfo("Local mapper is initialized")

    rospy.spin()


import sys
from itertools import combinations
N, S = map(int, sys.stdin.readline().split())

sequence = list(map(int, sys.stdin.readline().split()))

# 연속된 부분수열이 아님!! -> 조합을 사용하여 모든 부분수열을 구함

count = 0       # 합이 S를 만족하는 부분수열의 개수

com = []
for i in range(1,N+1):
    com += list(combinations(sequence, i))      # 리스트 간 서로 더할 수 있음

for i in range(len(com)):
    if sum(com[i]) == S:
        count += 1

print(count)

백준/Silver/1182. 부분수열의 합/부분수열의 합.py


import re, json
from classes.chapter import Chapter
from classes.article import Article
from classes.recital import Recital
from classes.section import Section

def readFile(file):
    """
    Argument: 'file' path, type string. \n
    Reads data from file and returns a list
    with each line in in a seprate element.
    """
    f = open(file, 'r')
    print(f'Reading data from file {file}')
    lines = []
    for line in f:
        #Remove uncesseary div tags
        if re.search('
|<\/div>', line) == None:
            lines.append(line)
    f.close()
    return lines

def mapText(lines):
    """
    Arguments: 'lines' list of strings.\n
    Will loop over the html code and try to map each needed line.\n
    Creates a object for each Chapter, Section and Article.
    """
    chapters, sectinos ,articles, recitals = [], [], [], []
    lineCounter, recitleCounter, articleCounter = 0, 0, 0
    CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

    for line in lines:
        if re.search('CHAPTER (M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))', line):
            try:
                # Sets the end line for the previous object.
                chapterObj.endLine = lineCounter - 1
            except UnboundLocalError:
                #The first object will trigger this.
                pass
            chapterObj = Chapter(lineCounter, line)
            chapters.append(chapterObj)
            chapterObj.addTitle(lines[lineCounter + 3])

            tempTitleLineNr = lineCounter

        elif re.search('SECTION (M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))', line):
            try:
                sectionObj.endLine = lineCounter - 2
            except UnboundLocalError:
                #The first object will trigger this.
                pass

            sectionObj = Section(lineCounter - 1)

            # If the third next row have 'Article [0-9]', then it means
            # that the section does not have a section name.
            # So then i call the section 'Section I' or 'Section II'
            # Else the Section name is on the third next row.
            if re.search('Article [0-9]', lines[lineCounter + 3]):
                sectionObj.setTitle(line)
            else:
                sectionObj.setTitle(lines[lineCounter + 3])

            sectinos.append(sectionObj)
            chapterObj.hasSections = True
            chapterObj.addSection(sectionObj)

        elif re.search('( |)Article <\/span>[0-9].<|( |)Article [0-9](.|)(<| <)', line):
        # Need to do regex because the htmlcode does not follow a standard
            articleCounter += 1
            try:
                articleObj.endLine = lineCounter - 1
            except UnboundLocalError:
                #The first object will trigger this.
                pass

            articleObj = Article(lineCounter, articleCounter)
            chapterObj.addArticle(articleObj)

            # This is for Chapter titles that are on 2 rows.
            # tempTitleLineNr is the line where the current chapter started.
            # if lineCounter - tempTitleLineNr == 9 and that the previous third row does
            # not contain 'SECTION' then it means there is
            # a 2 rowed title.
            # The second row title is on the current - 3 row.
            if lineCounter - tempTitleLineNr == 9 and re.search('SECTION', lines[lineCounter - 3]) == None:
                chapterObj.addTitle(lines[lineCounter - 3])

            # Need to do this because of no standard in html code.
            # Often the Article title is in its own
 tag that is 3 row under
            # but sometimes its in the same
 tag then its 2 row under.
            if re.search('Titrearticle', lines[lineCounter + 2]):
                articleObj.setTitle(lines[lineCounter + 3])
            else:
                articleObj.setTitle(lines[lineCounter + 2])

            # Have a try/catch here because each chapter does not have sections.
            try:
                sectionObj.addArticle(articleObj)
            except UnboundLocalError:
                pass
            articles.append(articleObj)

        elif re.search('
', line):
        # This is for the recitals.
            try:
                recitalObj.endLine = lineCounter
            except UnboundLocalError:
                pass
            recitleCounter += 1
            recitalObj = Recital(lineCounter + 1, recitleCounter)
            recitals.append(recitalObj)

        lineCounter += 1
    # Manual sets the endlines for each type,
    # dont know if there is any better way.
    recitals[-1].endLine = 669
    chapters[-1].endLine = 3008
    articles[-1].endLine = 3008
    sectinos[-1].endLine = 3008

    articles = addContent(articles, lines)
    recitals = addContent(recitals, lines)

    createJson(articles, chapters, recitals)

def addContent(objects, content):
    """
    Arguments: 'objects', type list of objects. 'content' list of strings.\n
    Adds content to object.
    """
    for obj in objects:
        for lineNr in range(obj.startLine - 1, obj.endLine):
            obj.addContent(content[lineNr])
    return objects

def createJson(articles, chapters, recitals):
    # These are the lists that will be written to the json files.
    jsonArtList, jsonRecitalList, jsonChapterList = [], [], []

    for article in articles:
        text = article.content

        # Each first article in every chapter gets some ChapterTitle data,
        # that should not be in the article text. This is a fix to remove that data.
        if re.search('
', text):
            text = re.split('
', text)
        else:
            text = re.split('class="ChapterTitle">', text)
        text = re.split('class="SectionTitle">', text[0])
        articleData = {
            'id': article.id,
            'name': 'article-' + str(article.id),
            'text': text[0]
        }
        jsonArtList.append(articleData)

    for recital in recitals:
        recitalData = {
            'id': recital.id,
            'text': recital.content
        }
        jsonRecitalList.append(recitalData)

    for chapter in chapters:
        # This is a mess
        sections = []

        if chapter.hasSections == True:

            # Sections in a chapter
            for section in chapter.sections:
                sectionArticles = []

                # Articles in a section in a chapter
                for sectionArticle in section.articles:
                    articleData = {
                        'id': sectionArticle.id,
                        'name': sectionArticle.title
                    }
                    sectionArticles.append(articleData)

                sectionData = {
                    'title': section.title,
                    'articles': sectionArticles
                }
                sections.append(sectionData)
        else:
            # If chapter dont have section

            # Temp list just to get the same strutcure in the json
            dummySectionArticles = []

            # Articles in chapter
            for article in chapter.articles:
                articleData = {
                    'id': article.id,
                    'name': article.title
                }
                dummySectionArticles.append(articleData)

                # Leaving the title empty because this is not a section.
                sectionData = {
                    'title': '',
                    'articles': dummySectionArticles
                }

            sections.append(sectionData)
        chapterData = {
            'id': chapter.id,
            'title': chapter.title,
            'sections': sections
        }
        jsonChapterList.append(chapterData)

    writeToFile('articles.json', jsonArtList)
    writeToFile('recitals.json', jsonRecitalList)
    writeToFile('chapters.json', jsonChapterList)

def writeToFile(filename, content):
    path = 'eleventy/_data/' + filename

    f = open(path, 'w')
    jsonStr = json.dumps(content)
    f.write(jsonStr)
    print(f'Writing data to file {path}')
    f.close()

def main():
    htmlCode = 'python/htmlCode.html'
    content = readFile(htmlCode)
    mapText(content)

main()


import random
import matplotlib.pyplot as plt
import numpy as np

def generar_lista(n, m):
    l = random.sample(range(m), k = n)
    l.sort()
    return l

def generar_elemento(m):
    return random.randint(0, m-1)

def busqueda_secuencial_(lista, x):
    '''Si x está en la lista devuelve el índice de su primera aparición,
    de lo contrario devuelve -1. Además devuelve la cantidad de comparaciones
    que hace la función.
    '''
    comps = 0 # inicializo en cero la cantidad de comparaciones
    pos = -1
    for i,z in enumerate(lista):
        comps += 1 # sumo la comparación que estoy por hacer
        if z == x:
            pos = i
            break
    return pos, comps

def busqueda_binaria(lista, e):
    '''
        Devuelve la posicion de un elemento 'e' en una lista ordenada,
        Devuelve -1 si el elemento no esta en la lista.-
    '''
    comps = 0 # inicializo en cero la cantidad de comparaciones
    index = -1
    izq = 0
    der = len(lista) - 1
    while izq <= der and index == -1:
        middle_index = (izq + der) // 2
        middle_value = lista[middle_index]

        if middle_value == e:
            index = middle_index
        elif e < middle_value:
            der = middle_index - 1
            comps += 1
        elif e > middle_value:
            izq = middle_index + 1
            comps += 1

    return (index, comps)

def experimento_secuencial_promedio(lista, m, k):
    comps_tot = 0
    for i in range(k):
        x = generar_elemento(m)
        comps_tot += busqueda_secuencial_(lista,x)[1]

    comps_prom = comps_tot / k
    return comps_prom

def experimento_binario_promedio(lista, m, k):
    comps_tot = 0
    for i in range(k):
        x = generar_elemento(m)
        comps_tot += busqueda_binaria(lista,x)[1]

    comps_prom = comps_tot / k
    return comps_prom

def graficar_bbin_vs_bseq(m, k):
    largos = np.arange(256) + 1 # estos son los largos de listas que voy a usar
    # lista de largo i, para i entre 1 y 256
    comps_secuencial_promedio = np.zeros(256) # aca guardo el promedio de comparacion secuencial
    comps_binaria_promedio = np.zeros(256) # aca guardo el promedio de comparacion binaria

    for i, n in enumerate(largos):
        lista = generar_lista(n, m) # genero lista de largo n
        comps_secuencial_promedio[i] = experimento_secuencial_promedio(lista, m, k)
        comps_binaria_promedio[i] = experimento_binario_promedio(lista, m, k)

    # ahora grafico largos de listas contra operaciones promedio de búsqueda.
    plt.plot(largos,comps_secuencial_promedio,label = 'Búsqueda Secuencial')
    plt.plot(largos,comps_binaria_promedio,label = 'Busqueda Binaria')
    plt.xlabel("Largo de la lista")
    plt.ylabel("Cantidad de comparaciones")
    plt.title("Complejidad de Búsqueda secuencial vs Binaria")
    plt.ylim(1, 30)
    plt.legend()
    plt.show()


from collections import OrderedDict
from logger import log
from app.drivers.db.store import Store

class LRUCache(Store):

    def __init__(self, capacity: int):
        self.size = capacity
        self.cache = OrderedDict()
        log.debug("Init of LRU memory cache complete: set capacity: {capacity}")

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        val = self.cache[key]
        log.debug("Retrieved item {val} from the database using the key {key}")
        self.cache.move_to_end(key)
        return val

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            del self.cache[key]
        self.cache[key] = value
        log.debug("Inserted new value into the database with key: {key} and value: {value}")
        if len(self.cache) > self.size:
            log.info("Cache is at capacity, removing least recently used element")
            item = self.cache.popitem(last=False)
            log.info("Removed {item}, the least recent used element from the cache")

    def get_all(self):
        if not self.cache:
            return None
        else:
            mylist = self.cache.items()
            log.debug("Retrieved the following from the database: {mylist}")
            return mylist

    def remove(self, key):
        del self.cache[id]
        log.debug("Removed {key} entry from the database")

    def clear(self):
        self.cache = {}
        log.debug("Cleared all elements from the database")


import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(funcName)s,(%(lineno)d), %(message)s')

# create a file handler and add the handlers to the logger
handler = RotatingFileHandler('hello.log', mode='a', maxBytes=5*1024,
                                 backupCount=15, encoding=None, delay=0)

handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logger.addHandler(handler)#

# create a console handler and add the handlers to the logger
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)

def main():
    c = 0
    while(True):
        c += 1
        logger.info('Hello baby {0}'.format(c))

if __name__=='__main__':
    main()


import scrapy

class DxSpider(scrapy.Spider):
    name = 'dx'
    allowed_domains = ['www.go2.cn']
    start_urls = [f'http://www.go2.cn/search/all/?category_id=all&search_1=1&q=%E5%8D%95%E9%9E%8B&kl=hot&page={i}' for i in range(1, 5)]

    def parse(self, response):
        li = response.xpath('//div[@class="search-result-list"]/ul/li')
        for i in li:
            dict = {}
            name = i.xpath('.//div[@class="pro-name app-text-nowrap"]/text()').extract_first()
            info = i.xpath('.//div[@class="pro-info app-text-nowrap"]/text()').extract_first()
            price = i.xpath('.//div/span[@class="price"]/text()').extract_first()
            link = i.xpath('.//a/@href').extract_first()
            img = i.xpath('.//img/@src').extract_first()
            img1 = f'http://z.go2.cn{link}'
            link1 = f'http://www.go2.cn{img}'
            dict['name'] = name
            dict['info'] = info
            dict['price'] = price
            dict['img1'] = img1
            dict['link1'] = link1
            yield dict

        pass


import os

from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from rest_framework.decorators import api_view

from MewTeam import settings
from message.models import Room
from shared.chat_center import create_room
from shared.error import Error
from shared.res_temp import ResponseTemplate
from shared.token import check_token
from shared.validator import validate_image_name
from team.models import UserTeamShip, Team
from shared.permission import is_creator
from team.serializers import TeamSerializer

@api_view(['POST'])
def create_team(request):
    try:
        response, user_id = check_token(request)
        if user_id == -1:
            return response
        data = request.data
        name = data['name']
        with transaction.atomic():
            new_team = Team.objects.create(name=name)
            UserTeamShip.objects.create(user_id=user_id, team=new_team, identify=UserTeamShip.Identify.CREATOR)

            room = create_room(user_id=user_id, name=name, room_type=Room.RoomType.TEAM, team=new_team)
            room.avatar = new_team.avatar
            room.save()

            return ResponseTemplate(Error.SUCCESS, 'Team created successfully!', data={'team_id': new_team.id})
    except Exception as e:
        return ResponseTemplate(Error.DATABASE_INTERNAL_ERROR, str(e) + "user_id=" + str(user_id))

@api_view(['GET'])
def get_team_list(request):
    try:
        response, current_user_id = check_token(request)
        if current_user_id == -1:
            return response
        ships = UserTeamShip.objects.filter(user_id=current_user_id)
        team_list = []
        for ship in ships:
            team_list.append({
                'team': TeamSerializer(ship.team).data,
                'identity': ship.identify,
            })
        return ResponseTemplate(Error.SUCCESS, 'get current user team list successfully', data=team_list)
    except ObjectDoesNotExist as e:
        return ResponseTemplate(Error.DATABASE_INTERNAL_ERROR, str(e))
    except Exception as e:
        return ResponseTemplate(Error.FAILED, str(e))

@api_view(['DELETE'])
def disband_team(request, team_id):
    try:
        response, current_user_id = check_token(request)
        if current_user_id == -1:
            return response
        team = Team.objects.get(id=team_id)
        if not is_creator(current_user_id, team_id):
            return ResponseTemplate(Error.PERMISSION_DENIED, 'you are not the creator of the team')
        team.delete()
        return ResponseTemplate(Error.SUCCESS, 'Team disbanded successfully')
    except Exception as e:
        return ResponseTemplate(Error.FAILED, str(e))

@api_view(['POST'])
def update_team_avatar(request, team_id):
    try:
        response, current_user_id = check_token(request)
        if current_user_id == -1:
            return response
        file = request.FILES.get('file')
        if file is None:
            return ResponseTemplate(Error.FILE_MISSING, 'Missing image file')
        if not validate_image_name(file.name):
            return ResponseTemplate(Error.FILE_TYPE_INVALID, 'Invalid image file type')
        if file.size > settings.MAX_AVATAR_FILE_SIZE:
            return ResponseTemplate(Error.FILE_SIZE_ILLEGAL, 'Size of file is too large. It should be less than 4mb.')

        team = Team.objects.filter(id=team_id).filter().first()
        avatar = f"{settings.TEAM_AVATAR_URL}{team_id}.{file.name.split('.')[-1]}"
        os.makedirs(os.path.dirname(avatar), exist_ok=True)

        for dir_file in os.listdir(os.path.dirname(avatar)):
            if dir_file.startswith(str(team_id)):
                dir_file_path = os.path.join(os.path.dirname(avatar), dir_file)
                if os.path.isfile(dir_file_path):
                    os.remove(dir_file_path)

        with open(avatar, "wb+") as f:
            for chunk in file.chunks():
                f.write(chunk)
        team.avatar = avatar
        team.save()
        return ResponseTemplate(Error.SUCCESS, 'Edit team avatar successfully')
    except Exception as e:
        return ResponseTemplate(Error.FAILED, str(e))


from __future__ import annotations

from typing import cast

from pants.backend.python.subsystems.python_tool_base import PythonToolBase
from pants.backend.python.target_types import ConsoleScript
from pants.core.util_rules.config_files import ConfigFilesRequest
from pants.engine.addresses import UnparsedAddressInputs
from pants.option.custom_types import file_option, shell_str, target_option

class MyPy(PythonToolBase):
    options_scope = "mypy"
    help = "The MyPy Python type checker (http://mypy-lang.org/)."

    default_version = "mypy==0.812"
    default_main = ConsoleScript("mypy")
    # See `mypy/rules.py`. We only use these default constraints in some situations. Technically,
    # MyPy only requires 3.5+, but some popular plugins like `django-stubs` require 3.6+. Because
    # 3.5 is EOL, and users can tweak this back, this seems like a more sensible default.
    register_interpreter_constraints = True
    default_interpreter_constraints = ["CPython>=3.6"]

    @classmethod
    def register_options(cls, register):
        super().register_options(register)
        register(
            "--skip",
            type=bool,
            default=False,
            help=f"Don't use MyPy when running `{register.bootstrap.pants_bin_name} typecheck`.",
        )
        register(
            "--args",
            type=list,
            member_type=shell_str,
            help=(
                "Arguments to pass directly to mypy, e.g. "
                f'`--{cls.options_scope}-args="--python-version 3.7 --disallow-any-expr"`'
            ),
        )
        register(
            "--config",
            type=file_option,
            default=None,
            advanced=True,
            help=(
                "Path to a config file understood by MyPy "
                "(https://mypy.readthedocs.io/en/stable/config_file.html).\n\n"
                f"Setting this option will disable `[{cls.options_scope}].config_discovery`. Use "
                f"this option if the config is located in a non-standard location."
            ),
        )
        register(
            "--config-discovery",
            type=bool,
            default=True,
            advanced=True,
            help=(
                "If true, Pants will include any relevant config files during "
                "runs (`mypy.ini`, `.mypy.ini`, and `setup.cfg`)."
                f"\n\nUse `[{cls.options_scope}].config` instead if your config is in a "
                f"non-standard location."
            ),
        )
        register(
            "--source-plugins",
            type=list,
            member_type=target_option,
            advanced=True,
            help=(
                "An optional list of `python_library` target addresses to load first-party "
                "plugins.\n\nYou must also set `plugins = path.to.module` in your `mypy.ini`, and "
                "set the `[mypy].config` option in your `pants.toml`.\n\nTo instead load "
                "third-party plugins, set the option `[mypy].extra_requirements` and set the "
                "`plugins` option in `mypy.ini`."
            ),
        )

    @property
    def skip(self) -> bool:
        return cast(bool, self.options.skip)

    @property
    def args(self) -> tuple[str, ...]:
        return tuple(self.options.args)

    @property
    def config(self) -> str | None:
        return cast("str | None", self.options.config)

    @property
    def config_request(self) -> ConfigFilesRequest:
        # Refer to https://mypy.readthedocs.io/en/stable/config_file.html.
        return ConfigFilesRequest(
            specified=self.config,
            specified_option_name=f"{self.options_scope}.config",
            discovery=cast(bool, self.options.config_discovery),
            check_existence=["mypy.ini", ".mypy.ini"],
            check_content={"setup.cfg": b"[mypy"},
        )

    @property
    def source_plugins(self) -> UnparsedAddressInputs:
        return UnparsedAddressInputs(self.options.source_plugins, owning_address=None)


import tweepy
from pickle import dump, load
from config import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET

class TwitterScraper(object):

    def __init__(self, user):

        """
        Upon initialization, the class scrapes the twitter account of the user name entered as a parameter. It stores the tweets it finds in a long
        list and saves the file where the class was initialized

        user: twitter user name of account to scrape

        return: list of original tweets from the account holder
        """

        # created api environment with keys
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
        self.api = tweepy.API(auth)
        self.user = user

    def scrape(self):

        scraped_tweets = []

        try:
            # initialize page counter
            page = 1

            while True:
                tweets = self.api.user_timeline(screen_name=str(self.user), page=page, count=200, tweet_mode='extended', include_rts=False)
                if tweets:
                    for tweet in tweets:
                        # process status here
                        scraped_tweets.append(tweet)
                else:
                    # All done
                    break
                page += 1  # next page

            f = open(str(self.user) + 'Tweets.pickle', 'wb')
            dump(scraped_tweets, f)
            f.close()

        except tweepy.error.TweepError:
            return -1


from django import forms
from django.contrib.auth.models import User
from epr_app.models import mst_patient,mst_doctor,mst_specialization,exist_patient
# exist_patient

class PatientForm(forms.ModelForm):
    user_id = forms.CharField(required=False)
    # username = forms.CharField(required=False)
    # sp_name = forms.ChoiceField(required=False)
    # d_id1 =
    # d_name =
    # prob_des = forms.CharField( widget = forms.Textarea)

    class Meta():
        model = mst_patient
        # fields = '__all__'
        exclude = ['d_id1','user_id','pres']
        # exclude = '__all__'

class ExistPatientForm(forms.ModelForm):
    prob_des = forms.CharField( widget = forms.Textarea)

    class Meta():
        model = exist_patient
        exclude = ['pres',]

class PIDForm(forms.ModelForm):
    class Meta():
        model=exist_patient
        fields = ('p_id',)