# -*- coding: utf-8 -*-
"""
Created on Thu Sep  1 12:08:24 2022

@author: Owner
"""
import GearballModel
import numpy as np
import math
import pandas as pd
import time

class solver:
    def __init__(self, num_scramble):
        self.heap = [] #can use the list.sort() method to make a heap / priority queue
        #might do tuples ini the heap. (F_value, Pointer_To_State_Instance)
        self.q = []
        self.start_state = GearballModel.gearball()
        self.start_state.scramble(num_scramble)
        self.translate = {0.0 : 0.0, 60.0 : 1.0, 120.0 : 2.0, 180.0 : 3.0, 240.0 : 2, 300.0 : 1}

    def find_children(self, state):
        #needs to take a state and generate a new child (6 total) for Blue,Red,Yellow rotation cw and ccw
        #make the cw(), ccw() functions return a copy of the gearball, or make a function that allows you to declare
        #a new gearball object provided the color states
        children = []
        children_depth = state.depth + 1
        '''
        for side in state.all_sides:#pointers to the states blue,red,yellow sides
            state.cw(side)
            state.cw(side.Opp_Side)

            children.append(GearballModel.gearball(children_depth, [state.G_side.gear_colors.copy(),
                                                                    state.R_side.gear_colors.copy(),
                                                                    state.B_side.gear_colors.copy(),
                                                                    state.O_side.gear_colors.copy(),
                                                                    state.Y_side.gear_colors.copy(),
                                                                    state.V_side.gear_colors.copy()],
                                                                    np.array( [state.G_side.gear_orientations.copy(),
                                                                               state.R_side.gear_orientations.copy(),
                                                                               state.B_side.gear_orientations.copy(),
                                                                               state.O_side.gear_orientations.copy(),
                                                                               state.Y_side.gear_orientations.copy(),
                                                                               state.V_side.gear_orientations.copy()]),
                                                                    parent = state, previous = str(side.color+' cw')))

            #declare a new gearball state and set its state to be the result of the move just executed
            #should undo the previous move so that subsequent results are accurate:
            state.ccw(side)
         '''

        for side in state.all_sides:#pointers to the states blue,red,yellow sides
            state.ccw(side) #should undo the previous move so that subsequent results are accurate

            children.append(GearballModel.gearball(children_depth, [state.G_side.gear_colors.copy(),
                                                                    state.R_side.gear_colors.copy(),
                                                                    state.B_side.gear_colors.copy(),
                                                                    state.O_side.gear_colors.copy(),
                                                                    state.Y_side.gear_colors.copy(),
                                                                    state.V_side.gear_colors.copy()],
                                                                    np.array( [state.G_side.gear_orientations.copy(),
                                                                               state.R_side.gear_orientations.copy(),
                                                                               state.B_side.gear_orientations.copy(),
                                                                               state.O_side.gear_orientations.copy(),
                                                                               state.Y_side.gear_orientations.copy(),
                                                                               state.V_side.gear_orientations.copy()]),
                                                                    parent = state, previous = str(side.color+' ccw')))
            #declare a new gearball state and set its state to be the result of the move just executed
            state.cw(side)
            state.cw(side.Opp_Side) #should undo the previous move so that subsequent results are accurate

        return children
    def gear_distance(self, state):
        #will get the total number of turns to return the gear orientations to 0-degrees. Can be at most 3 turns
        #for each (3) groups of 4 gears.
        group_angles = {0.0} # because there are 3 groups of 4 gears each, and each group all has the same orientations
        #i just add all of the data from gear rotations to have a set to extract the unique entries

        for side in state.all_sides:
            #I only check 3 sides to exploit symmetry of the gear ball
            #opposite sides will have the same exact gear orientations always
            group_angles = group_angles.union(set(x for x in side.gear_orientations.flatten()))
        #Next, calculate the minimum distance home for each entry:
        sum = 0
        for entry in group_angles:
            sum += self.translate[entry]
        return sum

    def num_colors(self, state):
        #second component of the heuristic value-- get the number of colors on each face
        #I only check 3 sides to exploit symmetry of the gear ball
        #opposite sides will have the same exact number of colors, always
        ''' I want to double check if i should the floor or cieling of the result here'''
        num_colors = []
        for side in state.all_sides:
            #I only check 3 sides to exploit symmetry of the gear ball
            #opposite sides will have the same exact gear orientations always
            num_colors.append(2 * (len(set(x[0] if len(x) > 1 else x for x in side.gear_colors.flatten() )) - 1))
        # This counts the number of colors on a side (excluding expected color) and adds to a list
        # multiply by 2 because we are including each sides opposite in the tally, which has the same number of colors

        '''NEXT: sum the results, divide by something and take the FLOOR or CIELING'''

        return math.ceil(sum(num_colors) / 8)

    def heuristic_value(self, state):
        #should return an integer
        #check the number of colors on a side
        #check minimum number of turns for gears to be correct
        #return the max of these two values
        return max(self.num_colors(state), self.gear_distance(state))

    def f_value(self, state):
        #self.f_value(self.start_state) = h(start_state)+ start_state.depth)
        #need to create a pointer which tethers a puzzle state to its f_value
        return self.heuristic_value(state) + state.depth

    def enheap(self, state):
        pointer = state
        tup = (self.f_value(state), pointer)

        self.heap.append(tup)
        self.heap.sort(key = lambda x: x[0]) #sort by the first entry of the tuple, which is the f_value
    def print_path(self, state):
        pointer = state
        move = 0
        while pointer != None:
            #pointer.print_Puzzle_State()
            print(str(move)+ ': '+ pointer.previous_move)
            pointer = pointer.parent
            move = move + 1

    def a_star(self):
        #probably want to delete gearball objects using the del obj command for memory
        #probably want to add parameters for pointer to parent and child in GearBall Model, also depth
        print('Begin A* solver: ')
        start_time = time.time()
        self.q.append(self.start_state)
        self.enheap(self.start_state)
        nodes_expanded = 0
        while len(self.q) != 0:
            #pop from the heap, find corresponding puzzle state
            p = self.heap.pop(0) # get the first entry in the heap
            #p[1]. print_Puzzle_State()
            #check if p = solved (heuristic = 0)
            if self.heuristic_value(p[1]) == 0.0:
                end_time = time.time() - start_time
                print('Time to find solution: '+ str(end_time))
                print('Nodes expanded to find solution: '  + str(nodes_expanded))
                p[1].print_Puzzle_State()
                self.print_path(p[1])
                break
            else:
                node_expanded = nodes_expanded + 1
                children = self.find_children(p[1])
                for child in children:
                    self.enheap(child)
                    self.q.append(child)
def main():
    puzzle_solver = solver(8)
    children = puzzle_solver.find_children(puzzle_solver.start_state)
    '''
    for child in children:
        child.print_Puzzle_State()
        print('Number of Colors Heuristic: '+str(puzzle_solver.num_colors(child)))
        print('Gear Distance Heuristic: '+str(puzzle_solver.gear_distance(child)))
        print('F-Value (Heuristic + depth): '+str(puzzle_solver.f_value(child)))
    '''
    puzzle_solver.a_star()
if __name__ == "__main__":
    main()


#Projeto 2 - Construindo um dashboard
#'Previsão do preço de ações (NASDAQ)'

# Bibliotecas
import time
import pandas as pd
import numpy as np

import cufflinks as cf
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

from pandas_datareader.data import DataReader
from pandas_datareader.nasdaq_trader import get_nasdaq_symbols

import datetime as dt
import streamlit as st

from fbprophet import Prophet
from fbprophet.plot import plot_plotly

import warnings

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
#init_notebook_mode(connected=True)
cf.go_offline()

# Parametrizações ##################################################
#sns.set_style('whitegrid')
#plt.style.use("fivethirtyeight")
st.set_option('deprecation.showPyplotGlobalUse', False)
#plt.rcParams['axes.facecolor'] = 'white'

# Funções #########################################################
#@st.cache
def plot_candlestick(df, acao):
    load_state.text('Loading graphic candlestick...')
    fig = go.Figure(data=
        [go.Candlestick(x=df.index,
                        open=df["Open"],
                        high=df["High"],
                        low=df["Low"],
                        close=df["Close"])]
    )
    fig.update_layout(
        title=f"Value of {acao}",
        yaxis_title="Price ($)"
    )
    st.plotly_chart(fig)
    return

def plot_line(df, company_name):
    load_state.text('Loading graphic line...')
    year_min = df.Year.min()
    year_max = df.Year.max()
    fig = px.line(df,
                  x=df.index,
                  y="Adj Close",
                  title= f'{company_name} - Stock price ({year_min} - {year_max})',
                  labels={'x':'Year','y':'Price'}
                 )
    st.plotly_chart(fig)
    return

def plot_bar(df, company_name):
    load_state.text('Loading graphic bar...')
    dfbar=df.groupby('Year')['Adj Close'].mean()
    fig = px.bar(dfbar,
                 x=dfbar.index,
                 y=dfbar.values,
                 title = f'{company_name} - Average Value',
                 labels={'x':'Year','y':'Price'}
                )
    st.plotly_chart(fig)
    return

def plot_bubble(acao, company_name):
    load_state.text('Loading graphic bubble...')
    dfbb = df_dict[acao].reset_index()
    dfbb = dfbb.loc[dfbb['Year']==dfbb.Year.max(),['Date','Adj Close','Volume','Year','Month']]
    fig = px.scatter(dfbb,
                     x="Date",
                     y="Adj Close",
                     labels={'x':'Year','y':'Price'},
                     size='Volume',
                     color='Month',
                     title = f'{company_name} - Stock price'
                    )
    st.plotly_chart(fig)
    return

def plot_box(df, company_name):
    load_state.text('Loading graphic boxplot...')
    fig = px.box(df,
                 x="Year",
                 y="Adj Close",
                 title = f'{company_name} - Boxplot Stock price',
                 labels={'x':'Year','y':'Price'}
                )
    st.plotly_chart(fig)
    return

def plot_hist(df, company_name):
    load_state.text('Loading graphic histogram...')
    year_min = df.Year.min()
    year_max = df.Year.max()
    fig = px.histogram(df, x="Adj Close",
                      title= f'{company_name} - Stock price ({year_min} - {year_max})',
                      labels={'x':'Year','y':'Price'})
    st.plotly_chart(fig)
    return

def plot_area(df, company_name):
    load_state.text('Loading graphic area...')
    year_min = df.Year.min()
    year_max = df.Year.max()
    fig = px.area(y=df["Adj Close"],
                  x=df.index,
                  title= f'{company_name} - Stock price ({year_min} - {year_max})',
                  labels={'x':'Year','y':'Price'})
    fig.update_layout(showlegend = False)
    st.plotly_chart(fig)
    return

def plot_cufflinks(df, company_name):
    load_state.text('Loading graphic "cufflinks"...')
    columns = ["High", "Low", "Open", "Close", "Volume"]
    year_min = df.Year.min()
    year_max = df.Year.max()
    fig = df[columns].iplot(
                asFigure=True,
                xTitle="Date",
                yTitle="Price",
                title=f'{company_name} - ({year_min} - {year_max})')
    st.plotly_chart(fig)
    return

def make_forecast(acao, period):
    load_state.text(f'{acao} - Processing ML prophet (forecast calculations)...')
    df = df_dict[acao].reset_index()
    df_train = df[["Date", "Close"]]
    df_train = df_train.rename(columns={'Date': 'ds', 'Close': 'y'})
    m = Prophet()
    m.fit(df_train)
    future = m.make_future_dataframe(periods=period)
    forecast = m.predict(future)
    return m, forecast

# Side Bar #######################################################
project_title = st.sidebar.text_input(label="Project title",
                                      value="Forecast stock calculations")

dt_end = dt.datetime.now().date()
dt_start = st.sidebar.date_input('Start date', dt.date(dt_end.year - 4, 1, 1))
dt_end = st.sidebar.date_input('End date')

n_years = st.sidebar.slider('Years of forecast', 1, 4, 1)
period = n_years * 365

# Criando a lista de ações da Nasdaq para multipla seleção
symbols = get_nasdaq_symbols()
acoes = symbols["NASDAQ Symbol"]

# Selecionando várias ações selecionadas
acoes_selected = st.sidebar.multiselect('Select stocks', acoes)
mask_acoes = symbols["NASDAQ Symbol"].isin(acoes_selected)
filtro_acoes = mask_acoes > 0
acao_list = mask_acoes[filtro_acoes].index.values.tolist()

run_button = st.sidebar.button(label='Execute')

# BODY ################################################################################################################
st.title(project_title)

if run_button:
    if len(acao_list) == 0:
        data_load_state = st.text('Please select stocks...')
    else:
        # Define a data final para o periodo de download das ações
        dt_end = dt.datetime.now().date()

        # Verifica se a data inicial da previsão é compatível, deve ter pelo menos 1 ano para efetuar a previsão
        # Se a data final for menor ou igual a data inicial a data inicial será decrescida em 1 ano
        if dt_end <= dt_start:
            dt_start = dt.datetime(dt_end.year - 4, dt_end.month, dt_end.day).strftime('%Y-%m-%d')

        data_load_state = st.text('Downloading information...')
        load_state = st.text('')

        my_bar = st.progress(0)
        percent_complete = 0

        company_list = list()

        #Efetuando o download dos dados financeiros yahoo e criando os dataframes
        df_dict = dict()
        for acao in acao_list:
            load_state.text(f'Download: {acao}')
            try:
                df_dict[acao] = DataReader(acao, 'yahoo', dt_start, dt_end)
                df_dict[acao]["Year"] = pd.DatetimeIndex(df_dict[acao].index).year
                df_dict[acao]["Month"] = pd.DatetimeIndex(df_dict[acao].index).month

                filtro = symbols["NASDAQ Symbol"]==acao
                acao_company = symbols.loc[filtro, "Security Name"].values[0]
                acao_company = acao_company.split('Common Stock', 1)[0]
                acao_company = acao_company.split('-', 1)[0]
                company_list.append(acao_company)
                load_state.text(f'Information {acao} successfully updated!')

                percent_complete += (0.2/len(acao_list))
                my_bar.progress(percent_complete)

            except:
                load_state.text (f'Information {acao} not found!')
                percent_complete += (0.2/len(acao_list))
                my_bar.progress(percent_complete)

        data_load_state.text('Creating graphics')
        load_state.text('')

        for i, acao in enumerate(acao_list, 1):
            try:
                company_name = company_list[i - 1]
                new_title = f'
{acao} - {company_name}
'
                st.markdown(new_title, unsafe_allow_html=True)
                st.write()

                plot_cufflinks(df_dict[acao], company_name)
                percent_complete += (0.1/len(acao_list))
                my_bar.progress(percent_complete)

                plot_bubble(acao, company_name)
                percent_complete += (0.1/len(acao_list))
                my_bar.progress(percent_complete)

                #plot_hist(df_dict[acao], company_name)

                plot_area(df_dict[acao], company_name)
                percent_complete += (0.1/len(acao_list))
                my_bar.progress(percent_complete)

                plot_bar(df_dict[acao], company_name)
                percent_complete += (0.1/len(acao_list))
                my_bar.progress(percent_complete)

                plot_box(df_dict[acao], company_name)
                percent_complete += (0.1/len(acao_list))
                my_bar.progress(percent_complete)

                #plot_line(df_dict[acao], company_name)
                #plot_candlestick(df_dict[acao], acao)

                m, forecast = make_forecast(acao, period)
                st.subheader(f'FB Prophet forecast to {acao} from {period} days')
                fig_forecast = plot_plotly(m, forecast)
                st.plotly_chart(fig_forecast)
                percent_complete += (0.3/len(acao_list))
                my_bar.progress(round(percent_complete,2))

                #st.subheader(f'Explaining the characteristics of the forecast model')
                #fig_components = m.plot_components(forecast)
                #st.write(fig_components)
            except:
                new_title = f'
{acao}
'
                st.markdown(new_title, unsafe_allow_html=True)
                st.write()

                load_state.text (f'Information {acao} not found!')
                percent_complete += (0.8/len(acao_list))
                my_bar.progress(round(percent_complete,2))

                except_title = f"
Sorry, we can't find the download information.
"
                st.markdown(except_title, unsafe_allow_html=True)
                st.write()

        data_load_state.text('Prediction created!')
        #data_load_state.text('')
        load_state.text('')


import datetime

class BicECPriceGapAnalysisSetting(object):
    OUTPUT_DIR = './data/OUTPUT/' + 'BicEC_PriceGapAnalysis' + '/'
    TGT_FLOOR_DATE = datetime.date(2018,6,1)
    TGT_UPPER_DATE = datetime.date(2018,8,31)

class PreprocessSetting(object):
    RAW_DATA_DIR = './data/Input/raw_data/'
    # DATA_FILES_TO_FETCH = ['売上データ詳細_' + TGT_STORE + '_20180401-0630.csv', ]
    # DATA_FILES_TO_FETCH = ['定楽屋 金山店2018-04-01-2018-06-30_before_grouping.csv', ]
    # PROCESSED_DATA_DIR = './data/Input/processed_data/'+ TGT_STORE +'/'


import sys

input = sys.stdin.readline

# 2056 작업
# 작업에 걸리는 시간과 필요한 선행작업 관계가 주어졌을 때
# 모든 작업을 마치는데 걸리는 최소시간을 구하는 문제
# 위상정렬을 사용해서 간단하게 해결 가능하다.
def sol2056():
    n = int(input())
    g = [[] for _ in range(n+1)]
    time = [0] * (n+1)
    degree = [0] * (n+1)
    q = []
    for i in range(1, n+1):
        info = list(map(int, input().split()))
        time[i] = info[0]
        degree[i] = info[1]
        for j in range(2, len(info)):
            g[info[j]].append(i)
        if not degree[i]:
            q.append(i)

    dp = [0] * (n+1)
    while q:
        nq = []
        for w in q:
            dp[w] += time[w]
            for nxt in g[w]:
                degree[nxt] -= 1
                dp[nxt] = max(dp[nxt], dp[w])
                if not degree[nxt]:
                    nq.append(nxt)
        q = nq

    return max(dp)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-03-03 23:48
# @Author  : zhou
# @File    : 1006 换个格式输出整数
# @Software: PyCharm
# @Description:

n = int(input())
tag = ['B', 'S']
L = []
while n > 0:
    L.append(n % 10)
    n //= 10

if len(L) == 2:
    L.append(0)

elif len(L) == 1:
    L.append(0)
    L.append(0)

L.reverse()

for i in range(len(L)):
    for j in range(L[i]):
        if i == 2:
            print(j + 1, end="")
        else:
            print(tag[i], end="")

print()

1006 换个格式输出整数.py


"""
Name: Logan Segal
Homework 10.py

Problem: In this homework we are working with creating our own classes and functions.
    We created everything from a blank coding page, and coded everything ourselves
    from start to finish. This homework utilizes everything we have learned so far, with
    the new topics we have learned about creating our own classes.

Certification of Authenticity:
I certify that this assignment is entirely my own work.
"""
from graphics import Circle, Line,Polygon

class Face:
    def __init__(self, window, center, size):
        eye_size = 0.15 * size
        eye_off = size / 3.0
        mouth_size = 0.8 * size
        mouth_off = size / 2.0
        self.window = window
        self.head = Circle(center, size)
        self.head.draw(window)
        self.left_eye = Circle(center, eye_size)
        self.left_eye.move(-eye_off, -eye_off)
        self.right_eye = Circle(center, eye_size)
        self.right_eye.move(eye_off, -eye_off)
        self.left_eye.draw(window)
        self.right_eye.draw(window)
        point_1 = center.clone()
        point_1.move(-mouth_size / 2, mouth_off)
        point_2 = center.clone()
        point_2.move(mouth_size / 2, mouth_off)
        self.mouth = Line(point_1, point_2)
        self.mouth.draw(window)

    def smile(self):
        middle = self.head.getCenter()
        radius = self.head.getRadius()
        size = 0.8 * radius
        mouth = radius / 2.0
        point_3 = middle.clone()
        point_3.move(0, mouth * 1.0)
        point_1 = middle.clone()
        point_1.move(-size / 2, mouth)
        point_2 = middle.clone()
        point_2.move(size / 2, mouth)
        self.mouth.undraw()
        self.mouth = Polygon(point_1, point_2, point_3)
        self.mouth.draw(self.window)

    def shock(self):
        radius = self.head.getRadius()
        size = 0.20 * radius
        center = self.mouth.getCenter()
        shock_expression = Circle(center, size)
        self.mouth.undraw()
        self.mouth = shock_expression
        self.mouth.draw(self.window)

    def wink(self):
        middle = self.head.getCenter()
        radius = self.head.getRadius()
        eye_close = radius / 3.0
        point_1 = middle.clone()
        point_1.move(-eye_close / 1.6, - eye_close)
        point_2 = middle.clone()
        point_2.move(eye_close / 2, - eye_close)
        eye_wink = Line(point_1, point_2)
        eye_wink.move(-eye_close, 0)
        self.left_eye.undraw()
        self.left_eye = eye_wink
        eye_wink.draw(self.window)
        self.smile()


import tkinter as Tk
from tkinter import  Tk, Button , Frame , Entry , Label

def generar():
    aux = generar(nombre.get(),apellidoP.get(),apellidoM.get(),añoN.get(),añoC.get())

ventana = Tk()
ventana.title("MATRICULA")
ventana.geometry("400x400")

seccion1 = Frame(ventana,bg="brown")
seccion1.pack(expand=True,fill='both')

#cabecera
txt1 = Label(seccion1,text="Usuario",bg="black",fg="white")
txt1.place(x=0, y=0)

#nombre
txt2 = Label(seccion1,text="Ingrese nombre",bg="black",fg="white")
txt2.place(x=0, y=40)

nombre = Tk
nombre = Entry(width="20")
nombre.place(x=0,y=0)

txt1 = Label(seccion1,text="Ingrese apellido paterno",bg="black",fg="white")
txt1.place(x=0, y=80)

apellidoP = Tk
apellidoP = Entry
apellidoP.place(x=0,y=0)

txt1 = Label(seccion1,text="Ingrese apellido materno",bg="black",fg="white")
txt1.place(x=0, y=120)

apellidoM = Tk
apellidoM = Entry(width="20")
apellidoM.place(x=0,y=0)

txt1 = Label(seccion1,text="Ingrese año de nacimiento",bg="black",fg="white")
txt1.place(x=0, y=160)

añoN = Tk
añoN = Entry(width="20")
añoN.place(x=0,y=0)

txt1 = Label(seccion1,text="Ingrese año de carrera",bg="black",fg="white")
txt1.place(x=0, y=200)

añoC = Tk
añoC = Entry(width="20")
añoC.place(x=0,y=0)

botoningresar= Button(seccion1,text="GENERAR",fg="black", command=generar)
botoningresar.place(x=300,y=350,width=80,height=30)

ventana.mainloop()


from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.core.files.storage import default_storage
from . import util
from .forms import newPageForm
import re
import random

def index(request):
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries(),
    })

def randomPage(request):
    entry_list = util.list_entries()
    entry_len = len(entry_list)
    entry_rand = random.randint(1,entry_len)
    rand_entry = entry_list[entry_rand-1]

    return redirect("/wiki/" + rand_entry)

def entry(request, title):
    if request.method == "POST":
        form=newPageForm(request.POST)

        if form.is_valid():
            pageTitle=form.cleaned_data["title"]
            pageContent=form.cleaned_data["content"]
            util.save_entry(pageTitle, pageContent)
            return redirect("/wiki/"+ pageTitle)
    else:
        page_content=util.get_entry(title)
        if page_content:
            final_content=processContent(page_content)
            return render(request, "encyclopedia/entry.html", {
                "content":final_content,
                "title":title
            })
        else:
            return render(request, "encyclopedia/error.html", {
                "title" : title,
                "entries": util.list_entries()
            })

def newpage(request):
    form = newPageForm(initial={
        "title": "New Page",
        "content": ""
        })
    return render(request, "encyclopedia/newpage.html",{
        "form":form,
        "title":"New Page",
        "content":" "
    })

def edit(request):
    title=request.GET['edit']
    content=util.get_entry(title)

    form = newPageForm({"title": title, "content":content})

    return render(request, "encyclopedia/edit.html", {
        "form":form,
        "title":title,
        "content":content
        })

def search(request):
    title=request.GET['search']

    try:
        content = util.get_entry(title)
        content = processContent(content)
        return render(request, "encyclopedia/entry.html", {
            "content":content,
            "title":title
        })

    except:
        results = util.list_entries()
        match_list = []
        l_title = title.lower()
        for r in results:
            rl = r.lower()
            if rl.startswith(l_title):
                match_list.append(r)

        return render(request, "encyclopedia/searchresults.html", {
            "title" : title,
            "match_list" : match_list
        })

def searchresults(request, title, match_list):
    return render(request, "encyclopedia/searchresults.html", {
        "title":title,
        "match_list":match_list
    })

# I don't know how well this approach would scale for large files...
def processContent(content):

    #paragraphs
    content = re.sub('(^[A-Za-z].+$)', r'
\1
', content, flags=re.MULTILINE)
    #headings
    content = re.sub('(##)(.+)',r'
\2
', content)
    content = re.sub('(#[^#])(.+)', r'
\2
', content)
    #strong
    content = re.sub('(\*\*)([^*]+)(\*\*)', r'\2', content)
    #href
    content = re.sub('(\[)([^]]+)(\])(\()([^)]*)(\))', r'\2', content)
    #ul
    spl=content.splitlines()
    srange = len(spl)

    for line in range(srange):
        spl[line] = spl[line].strip()
        if spl[line].startswith("* "):
            spl[line] = "
" + spl[line].replace("* ", "") + "
"

    for line in range(srange):

        if spl[line].startswith("
"):
            if not(spl[line-1].startswith ("
")):
                if not(spl[line-1].startswith("
")):
                    spl[line] = "
" + spl[line]
            # If last line of file is list element, add closing

            if line == srange-1:
                spl[line] += "
"
            elif not(spl[line+1].endswith("
")):
                if not(spl[line+1].endswith("
")):
                    spl[line] = spl[line] + "
"

    content = ("")
    for line in spl:
        content+=line

    return(content)


import math
import sys
# สังเกตว่า
# n-polygon มีได้ n-2 sub-triangle
# 6 เหลี่ยม มีได้ 3 เส้น -> 9 แบบ
# 5 เหลี่ยม มีได้ 2 เส้น -> 5 แบบ
# 4 เหลี่ยม มีได้ 1 เส้น -> 2 แบบ
# 3 เหลี่ยม มีได้ 0 เส้น
# Number of Diagonals= n(n−3)/2
def dist(coor1:list, coor2:list) -> float:
    x1,y1 = coor1
    x2,y2 = coor2
    return (((abs(x1-x2))**2 + (abs(y1-y2))**2))**0.5

def cost(coor1:list, coor2:list, coor3:list)-> float:
    return dist(coor1, coor2) + dist(coor2, coor3) + dist(coor3, coor1)

def polar_angle(coor1: list, coor2: list) -> float:
    x1, y1 = coor1
    x2, y2 = coor2
    return math.atan2(y2 - y1, x2 - x1)

def min_cost_triangulation(vertices : list) -> float:
    num_vertices = len(vertices)
    dp = [[0] * num_vertices for _ in range(num_vertices)]
    ref_vertex = min(vertices, key=lambda vertex: (vertex[1], vertex[0]))

    vertices.sort(key=lambda vertex: (polar_angle(ref_vertex, vertex), vertex))
    print(vertices)

    dp = [[0] * num_vertices for _ in range(num_vertices)]
    for diagonal in range(num_vertices):
        i = 0
        for j in range(diagonal, num_vertices):
            if j - i >= 2:
                dp[i][j] = sys.maxsize
                for k in range(i + 1, j):
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + cost(vertices[i], vertices[k], vertices[j]))
                    # print(dp)
            i += 1

    return dp[0][-1]
vertices = []
with open('./lab5/test.txt', 'r') as f:
    num_vertices = int(f.readline().strip())
    for _ in range(num_vertices):
        vertices.append(list(map(float, f.readline().strip().split()) ))
print("num_vertices : " ,num_vertices)
print(min_cost_triangulation(vertices))
f.close()


import inspect

from discord import Embed

from chitanda.config import config
from chitanda.decorators import args, register
from chitanda.listeners import DiscordListener

@register("help")
@args(r"$")
async def call(message):
    """Sends a private message detailing the available commands."""
    if isinstance(message.listener, DiscordListener):
        embed = Embed(title="Help!")
        for trigger, command in sorted(message.bot.commands.items()):
            if _applicable_listener(message.listener, command.call):
                embed.add_field(
                    name=f'{config["trigger_character"]}{trigger}',
                    value=_generate_help_text(command.call),
                    inline=False,
                )

        yield {
            "target": message.author,
            "message": embed,
            "private": True,
            "embed": True,
        }
    else:
        longest = max(len(t) for t in message.bot.commands)
        yield {"target": message.author, "message": "Help:"}
        for trigger, command in sorted(message.bot.commands.items()):
            if _applicable_listener(message.listener, command.call):
                yield {
                    "target": message.author,
                    "message": (
                        f'{config["trigger_character"]}'
                        f"{trigger.ljust(longest)} | "
                        f"{_generate_help_text(command.call)}"
                    ),
                }

def _applicable_listener(listener, call):
    return not hasattr(call, "listeners") or type(listener) in call.listeners

def _generate_help_text(call):
    doc = inspect.getdoc(call)
    if hasattr(call, "admin_only"):
        doc += " (admin only)"
    if hasattr(call, "auth_only"):
        doc += " (requires authentication)"
    if hasattr(call, "channel_only"):
        doc += " (channel only)"
    if hasattr(call, "private_message_only"):
        doc += " (PM only)"
    return doc


import numpy as np
import  matplotlib.pyplot as plt #类似 MATLAB 中绘图函数的相关函数
import tensorflow.compat.v1 as tf
import tensorflow.compat.v1 as tf #导入tensorflow，并且使用低版本
tf.compat.v1.disable_eager_execution() #确保Session中的run()函数可以正常运行

count=100
data=[]

for i in range(count):
    x1=np.random.normal(0.00,0.55)
    y1=x1*0.1+0.3+np.random.normal(0.00,0.03)
    data.append([x1,y1])

x_data=[v[0] for v in data]
y_data=[v[1] for v in data]

plt.scatter(x_data,y_data,c='r')
plt.show()

w=tf.Variable(tf.random_uniform([1],-1.0,1.0),name='w')
b=tf.Variable(tf.zeros([1]),name='b')

y=w*x_data+b

loss=tf.reduce_mean(tf.square(y-y_data),name='loss')

#way=tf.train.GradientDescentOptimizer(0.5)

train=tf.train.GradientDescentOptimizer(0.1).minimize(loss,name='train')

sess=tf.Session()

init=tf.global_variables_initializer()
sess.run(init)

for step in range(100):
    sess.run(train)

temp_1=sess.run(w)
temp_2=sess.run(b)

print("y=",temp_1[0],"x+",temp_2[0],",loss=",sess.run(loss))

plt.scatter(x_data,y_data,c='r')
plt.plot(x_data,sess.run(w)*x_data+sess.run(b))
plt.show()


# File: Main.py
# Description: Main programme
# Author: F. Eduard Decu
# Date: Mar 2019
# Updated: May 2019

# Imports
from GatherAllData import GatherAllData

# Consts
# Globals
# Functions

# Program entrance function
def main():

    #the CSV data file path
    filePath = "dataLog/data.csv"

    file = GatherAllData(filePath)

    #Prints all the data logs from the file
    file.Print_dataLog()

# Invoke main() program entrance
if __name__ == '__main__':
    main()


from .conftest import TestTimeouts
from ftplib import FTP
from socket import timeout

class TestFtplib(TestTimeouts):
    def test_connect(self):
        with self.raises(timeout):
            with FTP(self.connect_host(), timeout=1) as ftp:
                ftp.login()

    def test_read(self):
        with self.raises(timeout):
            with FTP(timeout=1) as ftp:
                ftp.connect(self.read_host(), self.read_port())
                ftp.login()


import cv2
from collections import Counter
from module import findnameoflandmark,findpostion,speak
import math

cap = cv2.VideoCapture(0)
tip=[8,12,16,20]
tipname=[8,12,16,20]
fingers=[]
finger=[]

while True:
         ret, frame = cap.read()
         frame1 = cv2.resize(frame, (640, 480))

         a=findpostion(frame1)
         b=findnameoflandmark(frame1)
         #print(b)

         if len(b and a)!=0:
            finger=[]
            fingers_up = []
            if a[2][1:] < a[4][1:]:
               finger.append(1)
               fingers_up.append(b[4])
               #print (b[4])

            else:
               finger.append(0)

            fingers=[]

            for id in range(0,4):
                if a[tip[id]][2:] < a[tip[id]-2][2:]:
                   #print(b[tipname[id]])
                   fingers_up.append(b[tipname[id]])

                   fingers.append(1)

                else:
                   fingers.append(0)
            if(len(fingers_up) == 0):
                print("STOP")
            elif(len(fingers_up) == 1):
                if('THUMB TIP' in fingers_up):
                    print("MOVE UP")
            elif(len(fingers_up) == 2):
                if(all(i in fingers_up for i in ['THUMB TIP','INDEX FINGER TIP'])):
                    print("MOVE LEFT")
                elif(all(i in fingers_up for i in ['THUMB TIP','PINKY TIP'])):
                    print("MOVE RIGHT")
            elif(len(fingers_up) == 3):
                if(all(i in fingers_up for i in ['MIDDLE FINGER TIP','RING FINGER TIP','PINKY TIP'])):
                    print("MOVE DOWN")
         x=fingers + finger
         c=Counter(x)
         up=c[1]
         down=c[0]
    #     print('This many fingers are up - ', up)
    #     print('This many fingers are down - ', down)

         cv2.imshow("Frame", frame1);
         key = cv2.waitKey(1) & 0xFF

         if key == ord("q"):
            speak("you have"+str(up)+"fingers up  and"+str(down)+"fingers down")

         if key == ord("s"):
           break
cv2.destroyAllWindows()


"""empty message

Revision ID: 07d1a2807aca
Revises: 1ab971d5de27
Create Date: 2017-12-12 13:27:01.834759

"""

# revision identifiers, used by Alembic.
revision = '07d1a2807aca'
down_revision = '1ab971d5de27'

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('risk_types',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('type', sa.String(length=128), nullable=True),
    sa.Column('user', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

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


# write python code Simplex stop-and-wait protocol with positive acknowledgement and
# retransmission.

import time

def SimpleStopAndWait():
    #sender
    data = "Hello World"
    while True:
        #send data
        print("Sending data: {}".format(data))
        time.sleep(1)
        #wait for acknowledgement
        print("Waiting for acknowledgement...")
        time.sleep(1)
        #check for acknowledgement
        if checkForAcknowledgement():
            print("Acknowledgement received, data sent successfully")
            break
        else:
            print("No acknowledgement received, retransmitting data...")
            time.sleep(1)

def checkForAcknowledgement():
    return True #simulate acknowledgement received

SimpleStopAndWait()


from itertools import groupby

greatest_pan = 0

for i in range (1, 10000):
    pan = ''
    n=1
    while len(pan) < 9:
        pan = pan + str(i*n)
        n += 1

    if len(pan) == 9:
        lst = list()
        for n in pan:
            if n == '0':
                lst = list()
                break
            lst.append(n)
        lst.sort()
        new_lst = [el for el, _ in groupby(lst)]

        if len(new_lst) == 9:
            if int(pan) > greatest_pan:
                greatest_pan = int(pan)

print(greatest_pan)


from django.core.urlresolvers import reverse
from django.utils.translation import ugettext

from soc.logic import dicts
from soc.logic.exceptions import AccessViolation
from soc.logic.exceptions import BadRequest
from soc.logic.exceptions import NotFound
from soc.logic.exceptions import RedirectRequest
from soc.models.org_app_record import OrgAppRecord
from soc.views.helper import access_checker
from soc.views.helper import request_data

from soc.modules.gci.models.profile import GCIProfile
from soc.modules.gci.models.task import GCITask
from soc.modules.gci.models.task import UNPUBLISHED

DEF_ALREADY_PARTICIPATING_AS_NON_STUDENT = ugettext(
    'You cannot register as a student since you are already a '
    'mentor or organization administrator in %s.')

DEF_ALL_WORK_STOPPED = ugettext(
    'All work on tasks has stopped. You can no longer place comments, '
    'submit work or make any changes to existing tasks.')

DEF_COMMENTING_NOT_ALLOWED = ugettext(
    "No more comments can be placed at this time.")

DEF_NO_TASK_CREATE_PRIV = ugettext(
    'You do not have sufficient privileges to create a new task for %s.' )

DEF_NO_TASK_EDIT_PRIV = ugettext(
    'You do not have sufficient privileges to edit a new task for %s.' )

DEF_NO_PREV_ORG_MEMBER = ugettext(
    'To apply as an organization for GCI you must have been a member of an '
    'organization in Google Summer of Code or Google Code In.')

DEF_TASK_UNEDITABLE_STATUS = ugettext(
    'This task is already published and published tasks cannot be edited.')

DEF_TASK_MUST_BE_IN_STATES = ugettext(
    'The task must be in one of the followings states %s')

DEF_TASK_MAY_NOT_BE_IN_STATES = ugettext(
    'The task may not be in one of the followings states %s')

DEF_ORG_APP_REJECTED = ugettext(
    'This org application has been rejected')

class Mutator(access_checker.Mutator):
  """Helper class for access checking.

  Mutates the data object as requested.
  """

  def unsetAll(self):
    self.data.task = access_checker.unset
    self.data.comments = access_checker.unset
    self.data.work_submissions = access_checker.unset
    self.data.is_visible = access_checker.unset
    self.data.full_edit = access_checker.unset
    super(Mutator, self).unsetAll()

  def profileFromKwargs(self):
    """Retrieves profile from the kwargs for GCI.
    """
    super(Mutator, self).profileFromKwargs(GCIProfile)

  def taskFromKwargs(self, comments=False, work_submissions=True):
    """Sets the GCITask entity in RequestData object.

    The entity that is set will always be in a valid state and for the program
    that is set in the RequestData.

    Args:
      comments: If true the comments on this task are added to RequestData
      work_submissions: If true the work submissions on this task are added to
                        RequestData
    """
    id = long(self.data.kwargs['id'])
    task = GCITask.get_by_id(id)

    if not task or (task.program.key() != self.data.program.key()) or \
        task.status == 'invalid':
      error_msg = access_checker.DEF_ID_BASED_ENTITY_NOT_EXISTS % {
          'model': 'GCITask',
          'id': id,
          }
      raise NotFound(error_msg)

    self.data.task = task

    if comments:
      self.data.comments = task.comments()

    if work_submissions:
      self.data.work_submissions = task.workSubmissions()

  def taskFromKwargsIfId(self):
    """Sets the GCITask entity in RequestData object if ID exists or None.
    """
    if not 'id' in self.data.kwargs:
      self.data.task = None
      return

    self.taskFromKwargs()

  def orgAppFromOrgId(self):
    org_id = self.data.GET.get('org_id')

    if not org_id:
      raise BadRequest('Missing org_id')

    q = OrgAppRecord.all()
    q.filter('survey', self.data.org_app)
    q.filter('org_id', org_id)

    self.data.org_app_record = q.get()

    if not self.data.org_app_record:
      raise NotFound("There is no org_app for the org_id %s" % org_id)

    if self.data.org_app_record.status != 'accepted':
      raise AccessViolation(DEF_ORG_APP_REJECTED)

  def fullEdit(self, full_edit=False):
    """Sets full_edit to True/False depending on the status of the task.
    """
    self.data.full_edit = full_edit

class DeveloperMutator(access_checker.DeveloperMutator,
                       Mutator):
  pass

class AccessChecker(access_checker.AccessChecker):
  """Access checker for GCI specific methods.
  """

  def isTaskVisible(self):
    """Checks if the task is visible to the public.

    Returns: True if the task is visible, if the task is not visible
        but the user can edit the task, False.
    """
    assert access_checker.isSet(self.data.task)

    can_edit = False
    try:
      self.checkCanUserEditTask()
      self.checkHasTaskEditableStatus()
      self.checkTimelineAllowsTaskEditing()
      can_edit = True
    except AccessViolation:
      pass

    if not self.data.timeline.tasksPubliclyVisible():
      if can_edit:
        return False
      period = self.data.timeline.tasksPubliclyVisibleOn()
      raise AccessViolation(
          access_checker.DEF_PAGE_INACTIVE_BEFORE % period)

    if not self.data.task.isPublished():
      if can_edit:
        return False
      error_msg = access_checker.DEF_PAGE_INACTIVE
      raise AccessViolation(error_msg)

    return True

  def isTaskInState(self, states):
    """Checks if the task is in any of the given states.

    Args:
      states: List of states in which a task may be for this check to pass.
    """
    assert access_checker.isSet(self.data.task)

    if self.data.task.status not in states:
      raise AccessViolation(DEF_TASK_MUST_BE_IN_STATES %states)

  def isTaskNotInStates(self, states):
    """Checks if the task is not in any of the given states.

    Args:
      states: List of states in which a task may not be for this check to pass.
    """
    assert access_checker.isSet(self.data.task)

    if self.data.task.status in states:
      raise AccessViolation(DEF_TASK_MAY_NOT_BE_IN_STATES %states)

  def canApplyStudent(self, edit_url):
    """Checks if a user may apply as a student to the program.
    """
    if self.data.profile:
      if self.data.profile.student_info:
        raise RedirectRequest(edit_url)
      else:
        raise AccessViolation(
            DEF_ALREADY_PARTICIPATING_AS_NON_STUDENT %
            self.data.program.name)

    self.studentSignupActive()

    # custom pre-registration age check for GCI students
    age_check = self.data.request.COOKIES.get('age_check', None)
    if not age_check or age_check == '0':
      # no age check done or it failed
      kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program'])
      age_check_url = reverse('gci_age_check', kwargs=kwargs)
      raise RedirectRequest(age_check_url)
    else:
      self.isLoggedIn()

  def canTakeOrgApp(self):
    """A user can take the GCI org app if he/she participated in GSoC or GCI
    as a non-student.
    """
    from soc.modules.gsoc.models.profile import GSoCProfile

    self.isUser()

    q = GSoCProfile.all()
    q.filter('is_student', False)
    q.filter('status', 'active')
    q.filter('user', self.data.user)
    gsoc_profile = q.get()

    q = GCIProfile.all()
    q.filter('is_student', False)
    q.filter('status', 'active')
    q.filter('user', self.data.user)
    gci_profile = q.get()

    if not (gsoc_profile or gci_profile):
      raise AccessViolation(DEF_NO_PREV_ORG_MEMBER)

  def canCreateNewOrg(self):
    """A user can create a new org if they have an accepted org app.
    """
    assert self.data.org_app

    if not self.data.profile:
      org_id = self.data.GET['org_id']
      profile_url = self.data.redirect.createProfile('org_admin').urlOf(
          'create_gci_profile')
      raise RedirectRequest(profile_url + '?new_org=' + org_id)

  def isBeforeAllWorkStopped(self):
    """Raises AccessViolation if all work on tasks has stopped.
    """
    if not self.data.timeline.allWorkStopped():
      return

    raise AccessViolation(DEF_ALL_WORK_STOPPED)

  def isCommentingAllowed(self):
    """Raises AccessViolation if commenting is not allowed.
    """
    if not self.data.timeline.allWorkStopped() or (
        not self.data.timeline.allReviewsStopped() and
        self.data.mentorFor(self.data.task.org)):
      return

    raise AccessViolation(DEF_COMMENTING_NOT_ALLOWED)

  def canCreateTask(self):
    """Checks whether the currently logged in user can edit the task.
    """
    assert access_checker.isSet(self.data.organization)
    assert access_checker.isSet(self.data.mentor_for)

    valid_org_keys = [o.key() for o in self.data.mentor_for]
    if self.data.organization.key() not in valid_org_keys:
      raise AccessViolation(DEF_NO_TASK_CREATE_PRIV % (
          self.data.organization.name))

    if (request_data.isBefore(self.data.timeline.orgsAnnouncedOn()) \
        or self.data.timeline.tasksClaimEnded()):
      raise AccessViolation(access_checker.DEF_PAGE_INACTIVE)

  def canUserEditTask(self):
    """Returns True/False depending on whether the currently logged in user
    can edit the task.
    """
    assert access_checker.isSet(self.data.task)
    assert access_checker.isSet(self.data.mentor_for)

    task = self.data.task

    valid_org_keys = [o.key() for o in self.data.mentor_for]
    if task.org.key() not in valid_org_keys:
      return False

    return True

  def checkCanUserEditTask(self):
    """Checks whether the currently logged in user can edit the task.
    """
    assert access_checker.isSet(self.data.task)

    if not self.canUserEditTask():
      raise AccessViolation(DEF_NO_TASK_EDIT_PRIV % (self.data.task.org.name))

  def hasTaskEditableStatus(self):
    """Returns True/False depending on whether the task is in one of the
    editable states.
    """
    assert access_checker.isSet(self.data.task)

    task = self.data.task

    if task.status not in (UNPUBLISHED + ['Open']):
      return False

    return True

  def checkHasTaskEditableStatus(self):
    """Checks whether the task is in one of the editable states.

    We specifically do not allow editing of tasks which are already claimed.
    """
    if not self.hasTaskEditableStatus():
      raise AccessViolation(DEF_TASK_UNEDITABLE_STATUS)

  def timelineAllowsTaskEditing(self):
    """Returns True/False depending on whether orgs can edit task depending
    on where in the program timeline we are currently in.
    """
    if (request_data.isBefore(self.data.timeline.orgsAnnouncedOn()) \
        or self.data.timeline.tasksClaimEnded()):
      return False

    return True

  def checkTimelineAllowsTaskEditing(self):
    """Checks if organizations can edit tasks at the current time in
    the program.
    """
    if not self.timelineAllowsTaskEditing():
      raise AccessViolation(access_checker.DEF_PAGE_INACTIVE)

class DeveloperAccessChecker(access_checker.DeveloperAccessChecker):
  """Developer access checker for GCI specific methods.
  """
  def isTaskVisible(self):
    return True


#!/usr/bin/env python
#-*- coding: UTF-8 -*-
"""
    Created by zhoupan on 8/5/16.
"""
import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@runoob.com'
receivers = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

# 三个参数：第一个为文本内容，第二个 plain 设置文本格式，第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")


import argparse
import glob
import os

from PIL import Image

def make_gifs(results_folder, type):
    results = results_folder  # "data_linear_upsampling_colorspace_stolen_discriminator_results"
    type = type  # "generated"

    # filepaths
    fp_in = f"{results}/{type}/gen.*.png"
    fp_out = f"{results}/gif/{type}/epochs.gif"

    os.makedirs(f"{results}/gif/{type}", exist_ok=True)

    # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
    imgs = (Image.open(f) for f in sorted(glob.glob(fp_in)))
    img = next(imgs)  # extract first image from iterator
    img.save(fp=fp_out, format='GIF', append_images=imgs,
             save_all=True, duration=200, loop=0)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Gif maker parameters')
    parser.add_argument('--results', type=str, required=True)
    parser.add_argument('--type', type=str, required=True)

    args = parser.parse_args()

    make_gifs(args.results, args.type)


from kafka import KafkaProducer, KafkaConsumer
import time
import requests
import keras.backend as K
from keras.layers import Layer as Layer
from keras import initializers, regularizers, constraints
import json
import numpy as np
from keras.layers import Bidirectional, GRU
from keras.models import Model
from keras.layers import Input, Embedding, Dropout, TimeDistributed, Dense
import tensorflow as tf
from nltk.tokenize import sent_tokenize, word_tokenize
import nltk

def dot_product(x, kernel):
    """
    https://github.com/richliao/textClassifier/issues/13#issuecomment-377323318
    Wrapper for dot product operation, in order to be compatible with both
    Theano and Tensorflow
    Args:
        x (): input
        kernel (): weights
    Returns:
    """
    if K.backend() == 'tensorflow':
        return K.squeeze(K.dot(x, K.expand_dims(kernel)), axis=-1)
    else:
        return K.dot(x, kernel)

class AttentionWithContext(Layer):
    """
    Follows the work of Yang et al. [https://www.cs.cmu.edu/~diyiy/docs/naacl16.pdf]
    "Hierarchical Attention Networks for Document Classification"
    by using a context vector to assist the attention
    # Input shape
        3D tensor with shape: `(samples, steps, features)`.
    # Output shape
        2D tensor with shape: `(samples, features)`.

    How to use:
    Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.
    The dimensions are inferred based on the output shape of the RNN.

    Example:
        model.add(LSTM(64, return_sequences=True))
        model.add(AttentionWithContext())
        # next add a Dense layer (for classification/regression) or whatever...
    """

    def __init__(self, return_coefficients=False,
                 W_regularizer=None, u_regularizer=None, b_regularizer=None,
                 W_constraint=None, u_constraint=None, b_constraint=None,
                 bias=True, **kwargs):
        self.supports_masking = True
        self.return_coefficients = return_coefficients
        self.init = initializers.get('glorot_uniform')

        self.W_regularizer = regularizers.get(W_regularizer)
        self.u_regularizer = regularizers.get(u_regularizer)
        self.b_regularizer = regularizers.get(b_regularizer)

        self.W_constraint = constraints.get(W_constraint)
        self.u_constraint = constraints.get(u_constraint)
        self.b_constraint = constraints.get(b_constraint)

        self.bias = bias
        super(AttentionWithContext, self).__init__(**kwargs)

    def build(self, input_shape):
        assert len(input_shape) == 3

        self.W = self.add_weight((input_shape[-1], input_shape[-1],),
                                  initializer=self.init,
                                  name='{}_W'.format(self.name),
                                  regularizer=self.W_regularizer,
                                  constraint=self.W_constraint)
        if self.bias:
            self.b = self.add_weight((input_shape[-1],),
                                      initializer='zero',
                                      name='{}_b'.format(self.name),
                                      regularizer=self.b_regularizer,
                                      constraint=self.b_constraint)

        self.u = self.add_weight((input_shape[-1],),
                                  initializer=self.init,
                                  name='{}_u'.format(self.name),
                                  regularizer=self.u_regularizer,
                                  constraint=self.u_constraint)

        super(AttentionWithContext, self).build(input_shape)

    def compute_mask(self, input, input_mask=None):
        # do not pass the mask to the next layers
        return None

    def call(self, x, mask=None):
        uit = dot_product(x, self.W)

        if self.bias:
            uit += self.b

        uit = K.tanh(uit)
        ait = dot_product(uit, self.u)

        a = K.exp(ait)

        # apply mask after the exp. will be re-normalized next
        if mask is not None:
            # Cast the mask to floatX to avoid float64 upcasting in theano
            a *= K.cast(mask, K.floatx())

        # in some cases especially in the early stages of training the sum may be almost zero
        # and this results in NaN's. A workaround is to add a very small positive number ε to the sum.
        # a /= K.cast(K.sum(a, axis=1, keepdims=True), K.floatx())
        a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())
        a = K.expand_dims(a)

        weighted_input = K.sum(a * x, axis=1, keepdims=True) ### fill the gap ### # compute the attentional vector

        if self.return_coefficients:
            return [weighted_input, a] ### fill the gap - [attentional vector, coefficients] ###
        else:
            return weighted_input ### fill the gap - attentional vector only ###

    def compute_output_shape(self, input_shape):
        if self.return_coefficients:
            return [(input_shape[0], input_shape[-1]), (input_shape[0], input_shape[-1], 1)]
        else:
            return input_shape[0], input_shape[-1]

def bidir_gru(my_seq, n_units):
    '''
    just a convenient wrapper for bidirectional RNN with GRU units
    '''
    return Bidirectional(GRU(n_units, return_sequences=True))(my_seq)

path_root = './'
path_to_data = path_root + 'data/'

d = 30 # dimensionality of word embeddings
n_units = 50 # RNN layer dimensionality
drop_rate = 0.5 # dropout
mfw_idx = 2 # index of the most frequent words in the dictionary
            # 0 is for the special padding token
            # 1 is for the special out-of-vocabulary token

padding_idx = 0
oov_idx = 1
batch_size = 32
nb_epochs = 2
my_optimizer = 'adam'
my_patience = 2 # for early stopping strategy

my_docs_array_train = np.load(path_to_data + 'docs_train.npy')
my_docs_array_test = np.load(path_to_data + 'docs_test.npy')

my_labels_array_train = np.load(path_to_data + 'labels_train.npy')
my_labels_array_test = np.load(path_to_data + 'labels_test.npy')

# load dictionary of word indexes (sorted by decreasing frequency across the corpus)
with open(path_to_data + 'word_to_index.json', 'r') as my_file:
    word_to_index = json.load(my_file)

# invert mapping
index_to_word = dict((v,k) for k,v in word_to_index.items()) ### fill the gap (use a dict comprehension) ###

sent_ints = Input(shape=(my_docs_array_train.shape[2],)) # vec of ints of variable size
sent_wv = Embedding(input_dim=len(index_to_word)+2, # vocab size
                    output_dim=d, # dimensionality of embedding space
                    input_length=my_docs_array_train.shape[2],
                    trainable=True
                    )(sent_ints)

sent_wv_dr = Dropout(drop_rate)(sent_wv)
sent_wa = bidir_gru(sent_wv_dr, n_units) ### fill the gap ### # get the annotations for each word in the sent
sent_att_vec, word_att_coeffs = AttentionWithContext(return_coefficients=True)(sent_wa)### fill the gap ### # get the attentional vector for the sentence
sent_att_vec_dr = Dropout(drop_rate)(sent_att_vec)
sent_encoder = Model(sent_ints, sent_att_vec_dr)

doc_ints = Input(shape=(my_docs_array_train.shape[1],my_docs_array_train.shape[2],))
sent_att_vecs_dr = TimeDistributed(sent_encoder)(doc_ints)### fill the gap ### # apply the sentence encoder model to each sentence in the document. Search for 'TimeDistributed' in https://keras.io/layers/wrappers/
doc_sa = bidir_gru(sent_att_vecs_dr,n_units) ### fill the gap ### # get annotations for each sent in the doc
doc_att_vec, sent_att_coeffs = AttentionWithContext(return_coefficients=True)(doc_sa)### fill the gap ### # get attentional vector for the doc
doc_att_vec_dr = Dropout(drop_rate)(doc_att_vec)

preds = Dense(units=1,
              activation='sigmoid')(doc_att_vec_dr)

model = Model(doc_ints,preds)

model.compile(loss='binary_crossentropy',
              optimizer = my_optimizer,
              metrics = ['accuracy'])

print('model compiled')
model.summary()

model.load_weights('moviemodel')

nltk.download('punkt')

def pad_sent(sent):
    if len(sent)>= 30:
        return sent[:30]
    else:
        return sent + [0]*(30 - len(sent))

consumer = KafkaConsumer('imbd-review', bootstrap_servers='localhost:9092')
producer = KafkaProducer(bootstrap_servers='localhost:9092')

while True:
    for review_json in consumer:
        review = json.loads(review_json.value.decode('utf-8'))
        title = review['title']
        txt = review['content']
        content = review['content']
        txt = [word_tokenize(sent) for sent in sent_tokenize(txt)]
        if len(txt) >= 7 :
            txt = txt[:7]
        else:
            txt = txt + [[0]*30]*(7 - len(txt))
        f = open("reviews.txt", "a")
        txt_input = [[word_to_index[word] if word in word_to_index else 0 for word in sentence] for sentence in txt]
        txt_input = [pad_sent(sent) for sent in txt_input]
        print(f'Review: {content}')
        f.write(f'Review: {content}\n')
        print(f'Review for the movie: {title}\nFrom: {review["username"]}')
        f.write(f'Review for the movie: {title}\nFrom: {review["username"]}\n')
        grade = model.predict(np.array([txt_input]))[0][0]
        if model.predict(np.array([txt_input]))[0][0] > 0.5:
            print(f'Good review\nGrade from the model: {grade}')
            f.write(f'Good review\nGrade from the model: {grade}\n')
        else:
            print(f'Bad review\nGrade from the model: {grade}')
            f.write(f'Bad review\nGrade from the model: {grade}\n')
        f.close()
    time.sleep(5)


from dart.model.dataset import DataType

column_type_map = {
    DataType.STRING: lambda column: 'VARCHAR(%s)' % (column.length or 'MAX'),
    DataType.VARCHAR: lambda column: 'VARCHAR(%s)' % (column.length or 'MAX'),
    DataType.BIGINT: lambda column: 'BIGINT',
    DataType.INT: lambda column: 'INT',
    DataType.SMALLINT: lambda column: 'SMALLINT',
    DataType.DOUBLE: lambda column: 'DOUBLE',
    DataType.FLOAT: lambda column: 'FLOAT',
    DataType.NUMERIC: lambda column: 'DECIMAL(%s, %s)' % (column.precision, column.scale),
    DataType.BOOLEAN: lambda column: 'BOOLEAN',
    DataType.DATE: lambda column: 'DATE',
    DataType.DATETIME: lambda column: 'TIMESTAMP',
    DataType.TIMESTAMP: lambda column: 'TIMESTAMP'
}

def mapped_column_definition(column=None):
    """
    :type column: dart.model.dataset.Column
    :rtype: str
    """
    type_function = column_type_map[column.data_type.upper()]
    return '"{name}" {type}{not_null}'.format(
        name=column.name,
        type=type_function(column),
        not_null=' NOT NULL' if not column.is_nullable else '',
    )


import ctypes
STD_OUTPUT_HANDLE= -11

FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.

BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.

fc_dict = { "r": FOREGROUND_RED, "g": FOREGROUND_GREEN, "b": FOREGROUND_BLUE }
bc_dict = { "r": BACKGROUND_RED, "g": BACKGROUND_GREEN, "b": BACKGROUND_BLUE }

def get_color_flag(desc, is_foreground):
    """
    通过一串描述，获取字体颜色的flag值
    """
    flag = 0
    if len(desc) < 1:
        return flag

    d = None
    if is_foreground:
        d = fc_dict
        flag = FOREGROUND_INTENSITY
    else:
        d = bc_dict
        flag = BACKGROUND_INTENSITY

    for k in desc:
        flag |= d.get(k, 0)
    return flag

class Color:
    std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    default_color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE

    def set_cmd_color(self, color, handle=std_out_handle):
        """(color) -> bit
        Example: set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
        """
        ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

    def reset(self):
        self.set_cmd_color(Color.default_color)

    def print_text(self, msg, fdesc = "", bdesc = ""):
        fcolor = get_color_flag(fdesc, True)
        if 0 == fcolor:
            fcolor = Color.default_color
        self.set_cmd_color(fcolor | get_color_flag(bdesc, False))
        print (msg)
        self.reset()

clr = Color()
clr.print_text("红色文字！", "r")
clr.print_text("绿色文字！", "g")


import numpy as np
from .GetFitacf import GetFitacf
import DateTimeTools as TT
from .. import Globals

def GetCellData(Radar,Date,ut,Beam,Gate):
	'''
	Get the data from a single cell of radar data

	Inputs
	======
	Radar : str
		Radar code
	Date : int
		Date in format yyyymmdd (can be a 2-element range)
	ut : float
		UT range in hours since the start of the day.
	Beam : int
		Beam number.
	Gate : int
		Gate number

	Returns
	=======
	out : numpy.recarray
		Data

	'''

	#get the data first
	sc,data = GetFitacf(Radar,Date,ut=ut)
	scind = np.arange(sc.size)

	#select this beam
	use = np.where((data.Beam == Beam) & (data.Gate == Gate))[0]
	uses = np.where((sc.Beam == Beam))[0]

	if use.size == 0:
		return None

	data = data[use]
	sc = sc[uses]
	scind = scind[uses]

	#limit time
	utc = TT.ContUT(data.Date,data.ut)
	utcs = TT.ContUT(sc.Date,sc.ut)
	if np.size(Date) == 1:
		utcr = TT.ContUT(np.array([Date,Date]),ut)
	else:
		utcr = TT.ContUT(Date,ut)
	use = np.where((utc >= utcr[0]) & (utc <= utcr[1]))[0]
	uses = np.where((utcs >= utcr[0]) & (utcs <= utcr[1]))[0]

	if use.size == 0:
		return None

	data = data[use]
	sc = sc[uses]
	scind = scind[uses]

	#work out indices
	ind = np.zeros(data.size,dtype='int32')
	I = data.Index[0]
	p = 0
	for i in range(0,data.size):
		#I could do with replacing this with something faster
		ind[i] = np.where(scind == data.Index[i])[0][0]

	#output array
	out = np.recarray(sc.size,dtype=Globals.adtype)
	out.Date = sc.Date
	out.ut = sc.ut
	out.Beam = Beam
	out.ScanCode = sc.ScanCode
	out.smsep = sc.smsep
	out.lagfr = sc.lagfr
	out.rsep = sc.rsep
	out.frang = sc.frang
	out.V.fill(np.nan)
	out.W_l.fill(np.nan)
	out.P_l.fill(np.nan)
	out.Gnd.fill(np.nan)
	out.V[ind] = data.V
	out.P_l[ind] = data.P_l
	out.W_l[ind] = data.W_l
	out.Gnd[ind] = data.Gnd
	out.Index = scind

	return out


from full_name_func import full_name

print('Please enter q for quite from program')
while True:
    first = input('Enter your first name\n')
    if first == 'q':
        break

    last_name = input('Enter your last name\n')
    if last_name == 'q':
        break

    formed_name = full_name(first, last_name)
    print(formed_name)


# https://atcoder.jp/contests/abc171/tasks/abc171_f

# import sys
# input = sys.stdin.buffer.readline

MOD = 10**9+7
MAXN = 2*10**6+5
f = [1]
for i in range(MAXN):
    f.append(f[-1] * (i+1) % MOD)
def nCr(n, r, mod=MOD):
    return f[n] * pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod

K = int(input())
S = input()
R = len(S)
N = K + R
ans = 0
for r in range(R,N+1):
    power = pow(25, N-r, MOD)
    ans += nCr(N, r) * power % MOD
    ans %= MOD
print(ans)

# S = input()
# n = int(input())
# N, K = map(int, input().split())
# l = list(map(int, (input().split())))
# A = [[int(i) for i in input().split()] for _ in range(N)]


# ARCHIVO PRINCIPAL
# Autor: Ricardo CÃ¡rdenas Guevara
# Fecha de creaciÃ³n: 17/10/2022

import socket
from encryption_utils import *
from file_utils import *
from input_utils import *
from connection import Connection
from properties import DEFAULT_PORT, SHOW_ENCRYPTED_MESSAGES

encryption_key = generateKey()
listening_port = DEFAULT_PORT
username = socket.gethostname()
remote_username = ''

want_exit = False

# MenÃº principal
# Se sigue mostrando hasta que se elija la opciÃ³n de salir
while not want_exit:
    print('\n====================================')
    print('>>    CHAT CIFRADO CON PYTHON     <<')
    print('====================================')
    print('Usuario: [' + username + ']')
    print('Puerto de escucha: [' + str(listening_port) + ']')
    print('Llave de cifrado: [' + encryption_key.replace('\n', '')[:13] + '...]')
    print('\nOpciones:')
    print('1.- Iniciar chat')
    print('2.- Cambiar nombre de usuario')
    print('3.- Cambiar puerto de escucha')
    print('4.- Generar llave de cifrado')
    print('5.- Importar llave de cifrado')
    print('6.- Exportar llave de cifrado')
    print('7.- Salir')
    option = select_option('\nSelecciona una opciÃ³n:', range(1, 8))
    if option == 1:
        print('\nINICIAR CHAT')
        connection = Connection(listening_port, username)
        try:
            address = readAddress('\nIngresa la direcciÃ³n del usuario remoto:\n')
            loading('Conectando')
            if connection.connect(address):
                remote_username = connection.remote_username
                loaded('Conectado con ' + remote_username)
                print('\nEspera tu turno para enviar un mensaje, escribe /salir para salir del chat')
                if (connection.first):
                    print('\nEnvÃa el primer mensaje')

                    message = input('\n> ')
                    # ValidaciÃ³n de salida del chat
                    if message == '/salir':
                        connection.send('/salir')
                        break
                    encrypted_message = encrypt(message, encryption_key)
                    connection.send(encrypted_message)
                    clear()
                    print('[' + username + ']: ' + message)
                    if SHOW_ENCRYPTED_MESSAGES:
                        print(' ðŸ”’â†“â†“â†“')
                        print('[' + username + ']: ' + encrypted_message)
                while True:
                    print('\nEsperando mensaje...', end='')
                    message = connection.listen()
                    # ValidaciÃ³n de salida del chat
                    if message == '/salir':
                        clear(inline=True)
                        print(remote_username + ' ha abandonado el chat')
                        break
                    decrypted_message = decrypt(message, encryption_key)
                    clear(inline=True)
                    if SHOW_ENCRYPTED_MESSAGES:
                        print('[' + remote_username + ']: ' + message)
                        print(' ðŸ”“â†“â†“â†“')
                    print('[' + remote_username + ']: ' + decrypted_message)

                    message = input('\n> ')
                    # ValidaciÃ³n de salida del chat
                    if message == '/salir':
                        connection.send('/salir')
                        break
                    encrypted_message = encrypt(message, encryption_key)
                    connection.send(encrypted_message)
                    clear()
                    print('[' + username + ']: ' + message)
                    if SHOW_ENCRYPTED_MESSAGES:
                        print(' ðŸ”’â†“â†“â†“')
                        print('[' + username + ']: ' + encrypted_message)

                connection.close()
                alert('Chat finalizado')
            else:
                warning('Error al establecer conexiÃ³n')
        except:
            connection.close()
            alert('Chat finalizado')
    elif option == 2:
        print('\nCAMBIAR NOMBRE DE USUARIO')
        if (confirm_option('\nÂ¿Deseas cambiar tu nombre de usuario? se sobreescribirÃ¡ el nombre actual (' + username + ')')):
            username = input('\nIngresa el nuevo nombre de usuario:\n')
            alert('Nombre cambiado')
        else:
            alert('AcciÃ³n cancelada')
    elif option == 3:
        print('\nCAMBIAR PUERTO DE ESCUCHA')
        if (confirm_option('\nÂ¿Deseas cambiar puerto de escucha? se sobreescribirÃ¡ el puerto actual (' + str(listening_port) + ')')):
            listening_port = readInt('\nIngresa el nuevo nÃºmero de puerto:\n')
            alert('Puerto cambiado')
        else:
            alert('AcciÃ³n cancelada')
    elif option == 4:
        print('\nGENERAR LLAVE DE CIFRADO')
        if (confirm_option('\nÂ¿Deseas generar una nueva llave de cifrado?, esta reemplazarÃ¡ a la llave actual')):
            # GeneraciÃ³n de nueva llave de cifrado
            encryption_key = generateKey()
            alert('Llave de cifrado generada')
        else:
            alert('AcciÃ³n cancelada')
    elif option == 5:
        print('\nIMPORTAR LLAVE DE CIFRADO')
        if (confirm_option('\nÂ¿Deseas importar una llave de cifrado?, esta reemplazarÃ¡ a la llave actual')):
            # ImportaciÃ³n de llave de cifrado desde archivo
            # Se evalÃºa antes de reemplazar la clave en caso de que haya fallado la lectura del archivo
            key = get_encryption_key(input('\nIngresa el nombre del archivo:\n'))
            if key:
                encryption_key = key
                alert('Llave de cifrado importada')
            else:
                warning('No se pudo obtener la llave de cifrado')
        else:
            alert('AcciÃ³n cancelada')
    elif option == 6:
        print('\nEXPORTAR LLAVE DE CIFRADO')
        # Guardado de llave de cifrado en archivo KEY
        filename = input('\nIngresa el nombre del archivo a guardar\n')
        if (save_encryption_key(filename, encryption_key)):
            alert('Llave de cifrado guardada en archivo ' + filename + '.key')
        else:
            warning('No se pudo guardar el archivo')
        print()
    elif option == 7:
        print('\nSALIR')
        if (confirm_option('\nÂ¿Deseas salir del sistema?')):
            want_exit = True
            print('\nBye :)')
        else:
            alert('AcciÃ³n cancelada')


# importing the Class
from btree import TreeNode

from lvt import levelOrderTraversal

import collections

# function to insert Node
def insertNode(root, value):
    if root is None:
        root = TreeNode(value)
        return root

    myqueue = collections.deque()
    myqueue.append(root)

    while myqueue:
        currNode = myqueue.popleft()
        if currNode is not None:
            if currNode.left is not None:
                myqueue.append(currNode.left)
            else:
                currNode.left = TreeNode(value)
                return root

        if currNode.right is not None:
            myqueue.append(currNode.right)
        else:
            currNode.right = TreeNode(value)
            return root

# def insertNode2(leftnode,rightnode,value):
#     # if root is None:
#     #     root = TreeNode(value)
#     #     return root
#     if leftnode.left is None:
#         leftnode.left = TreeNode(value)
#         return leftnode
#     elif rightnode.right is None:
#         rightnode.right = TreeNode(value)
#         return rightnode
#     else:
#         insertNode2(leftnode.left,rightnode.right,value)

def main():
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(6)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(9)
    # root = None
    print(levelOrderTraversal(root))
    print("Inserting node now")
    print(levelOrderTraversal(insertNode(root,10)))
    #print(insertNode(root,10))
    # levelOrderTraversal(root)

if __name__ == "__main__":
    main();


#!/usr/bin/env python3

from os import environ

from setuptools import setup

ptr_params = {
    "entry_point_module": "ansible_shed/main",
    "test_suite": "ansible_shed.tests.base",
    "test_suite_timeout": 300,
    "required_coverage": {
        "ansible_shed/main.py": 49,
        "ansible_shed/shed.py": 40,
    },
    "run_black": True,
    "run_flake8": True,
    "run_mypy": True,
    "run_usort": True,
}

ext_modules = []
if "MYPYC_BUILD" in environ:
    print("mypyc build time ...")
    from mypyc.build import mypycify

    ext_modules = mypycify(
        [
            "ansible_shed/__init__.py",
            "ansible_shed/main.py",
            "ansible_shed/shed.py",
        ],
        verbose=True,
    )

setup(
    name="ansible_shed",
    version="2023.3.15",
    description=(
        "asyncio ansible tower like shed to run playbooks and have prometheus "
        + "collector stats"
    ),
    packages=["ansible_shed", "ansible_shed.tests"],
    ext_modules=ext_modules,
    url="http://github.com/cooperlees/ansible_shed/",
    author="Cooper Lees",
    author_email="me@cooperlees.com",
    classifiers=[
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Development Status :: 3 - Alpha",
    ],
    entry_points={"console_scripts": ["ansible-shed = ansible_shed.main:main"]},
    install_requires=["aioprometheus[aiohttp]", "click", "GitPython"],
    extras_require={
        # If you'd like the ansible toolset dependency installed
        "ansible": ["ansible"],
    },
    test_require=["ptr"],
    python_requires=">=3.10",
    test_suite=ptr_params["test_suite"],
)


# Author: Caden Kroonenberg
# Date: 11-29-21

import csv
import data.info as info
import tweepy

# Init twitter user
CONSUMER_KEY = info.CONSUMER_KEY
CONSUMER_SECRET = info.CONSUMER_SECRET
ACCESS_KEY = info.ACCESS_KEY
ACCESS_SECRET = info.ACCESS_SECRET
BEARER_TOKEN = info.BEARER_TOKEN

# Your username
username = info.USERNAME

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
client = tweepy.Client(BEARER_TOKEN, CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)

user = client.get_user(username=username)[0]

id = user.id

my_tweets = client.get_users_tweets(id, max_results=25)[0]

for tweet in my_tweets:
    print(str(tweet.id) + '\t' + str(tweet.text))


from os import path
import pytest

def test_detect_single(monkeypatch):
    pathRoot = env_update(monkeypatch)
    from face_privacy_filter.transform_detect import FaceDetectTransform
    transform = FaceDetectTransform(include_image=False)
    inputDf = FaceDetectTransform.generate_in_df(path.join(pathRoot, 'testing', 'single-face_pexels.jpg'))
    outputDf = transform.predict(inputDf)
    assert len(outputDf) == 1                       # just one face, no image
    assert outputDf['w'][0] == outputDf['h'][0]     # make sure width/height is equal
    assert outputDf['w'][0] > 680                    # reasonable face size detection
    assert len(outputDf['image_binary'][0]) == 0     # there should be no binary data on detect regions
    print(outputDf)   # run `pytest -s` for more verbosity

def test_detect_multi(monkeypatch):
    pathRoot = env_update(monkeypatch)
    from face_privacy_filter.transform_detect import FaceDetectTransform
    transform = FaceDetectTransform(include_image=True)
    inputDf = FaceDetectTransform.generate_in_df(path.join(pathRoot, 'testing', 'multi-face_pexels.jpg'))
    outputDf = transform.predict(inputDf)
    assert len(outputDf) == 5       # note ONE face will be missed, but we get the original image, too
    imageDf = outputDf[outputDf['region']==-1]
    assert len(imageDf) == 1       # note ONE face will be missed, but we get the original image, too
    assert imageDf['w'][0] == 1280  # should be the original image size
    assert len(imageDf['image_binary'][0]) > 1  # should be the original image size
    assert len(outputDf[outputDf['image']==0]) == len(outputDf)  # all responses belong to image 0
    print(outputDf)

def env_update(monkeypatch):
    import sys

    pathRoot = path.dirname(path.dirname(path.dirname(path.abspath(__file__))))
    print("Adding '{:}' to sys path".format(pathRoot))
    if pathRoot not in sys.path:
        monkeypatch.syspath_prepend(pathRoot)
    return pathRoot


from flask import Response, request
from flask_restful import Resource
from models import Following, User, db
import json
from views import get_authorized_user_ids #added
import flask_jwt_extended

def get_path():
    return request.host_url + 'api/posts/'

class FollowingListEndpoint(Resource):
    def __init__(self, current_user):
        self.current_user = current_user

    @flask_jwt_extended.jwt_required()
    def get(self):
        # return all of the "following" records that the current user is following
        followings = Following.query.filter_by(user_id=self.current_user.id).all()

        body = [following.to_dict_following() for following in followings]

        return Response(json.dumps(body), mimetype="application/json", status=200)

    @flask_jwt_extended.jwt_required()
    def post(self):
        # create a new "following" record based on the data posted in the body
        args = request.get_json()

        if 'user_id' not in args:
            return Response(json.dumps("New following requires user."), mimetype="application/json", status=400)

        try:
            user_id = int(args.get('user_id'))
        except:
            return Response(json.dumps("New following requires user."), mimetype="application/json", status=400)

        requested_user = User.query.get(user_id)
        if not requested_user:
            return Response(json.dumps("No valid users."), mimetype="application/json", status=404)

        authorized_users = get_authorized_user_ids(self.current_user)
        if user_id in authorized_users:
            return Response(json.dumps("Already following user."), mimetype="application/json", status=400)

        new_following = Following(
            following_id = user_id,
            user_id = self.current_user.id
        )

        db.session.add(new_following)
        db.session.commit()

        # body = Following.query.get(new_following.id).to_dict_following()
        body = new_following.to_dict_following()

        return Response(json.dumps(body), mimetype="application/json", status=201)

class FollowingDetailEndpoint(Resource):
    def __init__(self, current_user):
        self.current_user = current_user

    @flask_jwt_extended.jwt_required()
    def delete(self, id):
        # delete "following" record where "id"=id

        following = Following.query.get(id)

        if not following or following.user_id != self.current_user.id:
            return Response(json.dumps("No valid following"), mimetype="application/json", status=404)

        Following.query.filter_by(id=id).delete()
        db.session.commit()

        return Response(json.dumps("Deleted following " + str(id)), mimetype="application/json", status=200)

def initialize_routes(api):
    api.add_resource(
        FollowingListEndpoint,
        '/api/following',
        '/api/following/',
        resource_class_kwargs={'current_user': flask_jwt_extended.current_user}
    )
    api.add_resource(
        FollowingDetailEndpoint,
        '/api/following/<int:id>',
        '/api/following/<int:id>/',
        resource_class_kwargs={'current_user': flask_jwt_extended.current_user}
    )


# -*- coding: utf-8 -*-
"""
School: Stevens Institute of Technology
Course: SSW 567 - A
Instructor: Prof. Andre Bondi
----- ----- ----- ----- -----
Topic: Homework # 05 / Test Cases
Requirement: Using static code analysis techniques and tools
----- ----- ----- ----- -----
@author: Yujun Kong
"""
import unittest
from hw_05_perfection_yujun_kong import Fraction, FractionsCalculator

class TestFraction(unittest.TestCase):
    """ test base class Fraction """
    def test_fraction_constructor(self):
        """ test constructor of target class """
        result = Fraction(0, 2).value
        self.assertEqual(result, "0")

        result = Fraction(10, -20).numerator
        self.assertEqual(result, -1)

        result = Fraction(-30, -30).value
        self.assertEqual(result, "1")

        result = Fraction(40, 20).value
        self.assertEqual(result, "2")

class TestFractionCalculator(unittest.TestCase):
    """ test calculation methods """

    def test_plus(self):
        """ test plus method """
        f_a = Fraction(39, -78)
        f_b = Fraction(10, 20)

        tfc = FractionsCalculator()
        tfc.plus(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "0")

    def test_minus(self):
        """ test minu method """
        f_a = Fraction(49, 70)
        f_b = Fraction(14, 20)

        tfc = FractionsCalculator()
        tfc.minus(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "0")

    def test_multiply_01(self):
        """ test multiply method 01 """
        f_a = Fraction(10, 50)
        f_b = Fraction(0, 60)

        tfc = FractionsCalculator()
        tfc.multiply(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "0")

    def test_multiply_02(self):
        """ test multiply method 02 """
        f_a = Fraction(25, 50)
        f_b = Fraction(30, 60)

        tfc = FractionsCalculator()
        tfc.multiply(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "1/4")

    def test_devide_01(self):
        """ test devide method 01 """
        f_a = Fraction(0, 70)
        f_b = Fraction(10, 80)

        tfc = FractionsCalculator()
        tfc.devide(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "0")

    def test_devide_02(self):
        """ test devide method 02 """
        f_a = Fraction(-35, 70)
        f_b = Fraction(40, 80)

        tfc = FractionsCalculator()
        tfc.multiply(f_a, f_b)
        result = tfc.result.value
        self.assertEqual(result, "-1/4")

if __name__ == '__main__':
    print('Running unit tests')
    unittest.main()


#!/usr/bin/env python
"""
# SuffolkCycleDjango : Implementation of blog_tags.py

Summary :

Use Case :
    As a <actor> I want <outcome> So that <justification>

Testable Statements :
    Can I <Boolean statement>
    ....
"""

__version__ = "0.1"
__author__ = 'Tony Flury : anthony.flury@btinternet.com'
__created__ = '07 Feb 2016'

from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html, mark_safe

register = template.Library()

@register.simple_tag(name='ellipsis')
def add_ellipsis(string, length=30, center=False):
    if not isinstance(string, basestring):
        return ""

    if len(string) <= length:
        return string

    # Make sure that we never exceed designated length and that our two 'halves' don't overlap
    if center:
        stride = min((len(string) - 3) / 2, (length - 3) / 2)
        return string[:stride] + '...' + string[-stride:]
    else:
        return string[:length - 3] + '...'

@register.simple_tag(name='year_visible', takes_context=True)
def year_visible(context):
    if int(context['archive']['display_year']) == int(context['year']['grouper']):
        return mark_safe("archive-visible")
    else:
        return mark_safe('')

@register.simple_tag(name='month_visible', takes_context=True)
def month_visible(context):
    if (int(context['archive']['display_year']) == int(context['year']['grouper'])) and (
                int(context['archive']['display_month']) == int(context['month']['grouper'])):
        return mark_safe("archive-visible")
    else:
        return mark_safe('')

@register.simple_tag(name='year_url', takes_context=True)
def year_url(context):
    year = "{:4d}".format(int(context['year']['grouper']))
    return reverse('blog:Archive', kwargs={'year': year})

@register.simple_tag(name='month_url', takes_context=True)
def month_url(context):
    year = "{:4d}".format(int(context['year']['grouper']))
    month = "{:02d}".format(int(context['month']['grouper']))
    return reverse('blog:Archive', kwargs={'year': year, 'month': month})

def build_url(text, page, context):

    tag = context['args'].get('tag_slug', None)
    year = context['args'].get('year', None)
    month = context['args'].get('month', None)

    if not tag and not year and not month:
        return format_html('{text}',
                            url = reverse('Blog:Home', kwargs={'page':page} ),
                            text = text)

    if tag:
        return format_html('{text}',
                            url = reverse('blog:Search', kwargs={'tag_slug':tag, 'page':page} ),
                            text = text)

    if year and not month:
        return format_html('{text}',
                            url = reverse('blog:Archive', kwargs={'year':year, 'page':page} ),
                            text = text)

    if year and month:
                return format_html('{text}',
                            url = reverse('blog:Archive', kwargs={'year':year, 'month':month, 'page':page} ),
                            text = text)

@register.simple_tag(name='prev_page_url', takes_context=True)
def prev_page_url(context):

    prev_page = context['args'].get('prev_page', None)
    if not prev_page : # Page count starts from one
        return ""

    return build_url('Previous', prev_page, context)

@register.simple_tag(name='next_page_url', takes_context=True)
def next_page_url(context):

    next_page = context['args'].get('next_page', None)
    if not next_page:
        return ""

    return build_url('Next', next_page, context)


#!/usr/bin/python3
"""Solves the N-queens puzzle."""
import sys

def init_board(n):
    """Initialize an `n`x`n` chessboard."""
    return [[' ' for _ in range(n)] for _ in range(n)]

def board_deepcopy(board):
    """Deep copy of a chessboard."""
    if isinstance(board, list):
        return list(map(board_deepcopy, board))
    return board

def get_solution(board):
    """Get queen positions from the board."""
    solution = []
    for r in range(len(board)):
        for c in range(len(board)):
            if board[r][c] == "Q":
                solution.append([r, c])
                break
    return solution

def xout(board, row, col):
    """Mark non-attacking positions as 'x'."""
    dirs = [(0, 1), (0, -1), (1, 0), (-1, 0),
            (1, 1), (-1, -1), (-1, 1), (1, -1)]

    for dr, dc in dirs:
        r, c = row + dr, col + dc
        while 0 <= r < len(board) and 0 <= c < len(board):
            if board[r][c] != 'Q':
                board[r][c] = 'x'
            r, c = r + dr, c + dc

def recursive_solve(board, row, queens, solutions):
    """Solve N-queens puzzle recursively."""
    if queens == len(board):
        solutions.append(get_solution(board))
        return solutions

    for c in range(len(board)):
        if board[row][c] == " ":
            tmp_board = board_deepcopy(board)
            tmp_board[row][c] = "Q"
            xout(tmp_board, row, c)
            solutions = recursive_solve(tmp_board, row + 1, queens + 1, solutions)

    return solutions

if __name__ == "__main__":
    if len(sys.argv) != 2 or not sys.argv[1].isdigit() or int(sys.argv[1]) < 4:
        print("Usage: nqueens N (N >= 4)")
        sys.exit(1)

    board = init_board(int(sys.argv[1]))
    solutions = recursive_solve(board, 0, 0, [])
    for sol in solutions:
        print(sol)


import fasttext
from tqdm import tqdm_notebook as tqdm
import pickle
from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score
from config import *

model = fasttext.train_supervised(input=newtrainpath,thread = thread_num,epoch=e_num,lr=lr_num) ##train model
model.save_model("fasttext{}epoch{}lr.bin".format(e_num,lr_num))  ## save model
model = fasttext.load_model("fasttext{}epoch{}lr.bin".format(e_num,lr_num))
nor2len = pickle.load(open(nor2len_path, 'rb'))
num2nor = pickle.load(open(num2labelpath, 'rb'))

def get_diff(h2m, m2l, real_result,predict_result):
    real_h= []
    real_m= []
    real_l= []
    predict_h = []
    predict_m = []
    predict_l = []
    for i in range(len(real_result)):
        t = num2nor[real_result[i]]
        if nor2len[t] < m2l:
            real_l.append(real_result[i])
            predict_l.append(predict_result[i])
        elif nor2len[t] <= h2m:
            real_m.append(real_result[i])
            predict_m.append(predict_result[i])
        else:
            real_h.append(real_result[i])
            predict_h.append(predict_result[i])
    return real_h,real_m,real_l,predict_h,predict_m,predict_l

def getscore(path):
    r_label=[]
    predict=[]
    with open(path,encoding = 'utf-8') as file:
        lines = file.readlines()
        for line in tqdm(lines):
            words = line.split('\t',1)
            result = model.predict(words[0])
            predict.append(int(result[0][0][9:]))
            words[1] = words[1].replace('\n','').replace('__label__','')
            r_label.append(int(words[1]))
    label_h,label_m,label_l,predict_h,predict_m,predict_l = get_diff(20,5,r_label,predict)
    return [accuracy_score(r_label, predict),accuracy_score(label_h, predict_h),accuracy_score(label_m, predict_m),accuracy_score(label_l, predict_l)],[precision_score(r_label, predict,average='macro'),precision_score(label_h, predict_h,average='macro'),precision_score(label_m, predict_m,average='macro'),precision_score(label_l, predict_l,average='macro')],[recall_score(r_label, predict,average='macro'),recall_score(label_h, predict_h,average='macro'),recall_score(label_m, predict_m,average='macro'),recall_score(label_l, predict_l,average='macro')],[f1_score(r_label, predict,average='macro'),f1_score(label_h, predict_h,average='macro'),f1_score(label_m, predict_m,average='macro'),f1_score(label_l, predict_l,average='macro')]

a1,p1,r1,f1 = getscore(newdevpath)
a2,p2,r2,f2 = getscore(newtestpath)

with open('fasttext{}epoch{}lr.txt'.format(e_num,lr_num),'w') as fi:
    fi.write('valid:\n')
    for a,p,r,f in zip(a1,p1,r1,f1):
        fi.write('accuary:'+str(a)+'\n')
        fi.write('precision:'+str(p)+'\n')
        fi.write('recall:'+str(r)+'\n')
        fi.write('f1:'+str(f)+'\n\n')

    fi.write('test:\n')
    for a,p,r,f in zip(a2,p2,r2,f2):
        fi.write('accuary:'+str(a)+'\n')
        fi.write('precision:'+str(p)+'\n')
        fi.write('recall:'+str(r)+'\n')
        fi.write('f1:'+str(f)+'\n\n')

# In[ ]:


favorite_languages = {
    'jony' : 'ruby',
    'seperina' : 'python',
    'sarah' : 'java',
    'lisa' : 'python'
}

print("Seperina's favorite language is " +
      favorite_languages['seperina'].title()
      +'\n')

for key, value in favorite_languages.items():
    print(key.title() +
          "'s favorite language is " +
          value.title())

python_user = ['seperina']
for name in favorite_languages.keys():
    if name in python_user:
        print("Congrats " +
              name.title() +
              "! Hope you keep studying " +
              favorite_languages[name].title())
    else:
        print("Do you want take Python?")

for name in sorted(favorite_languages.keys()):
    print(name.title() + ", please take your poll!")

print("\nThe following laguage has been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

#Exercise 6-1

user_information = {
    'first_name' : 'seperina',
    'last_name' : 'ji',
    'age' : 26,
    'city' : 'London'
}

print(user_information)

#Exercise 6-2
favorite_number = {
    'jony' : 4,
    'seperina' : 2,
    'lisa' : 1,
    'cassie' : 6,

}

for key, value in favorite_number.items():

    #number = favorite_number[friend]
    print(key + "'s favorite number is " + str(value))