from dash import dcc, html, dash_table
import config
import sites

import numpy as np
import pandas as pd

def call_layout(site_config):

    layout = html.Div([

        html.Div(id='dash-header',
                 children=[
                    html.H1(children=config.title),
                    html.H3(children=dcc.Markdown(
                            site_config['loc_msg_markdown'])),
                    # html.H3(children=site_config['dates_msg']),
                ]),

        html.Div(id='dash-controls',
                 children=[
                    html.Div(id='select-date-range',
                            children=[
                                html.Span(children='Select dates', style={'font-weight': 'bold'}),
                                dcc.DatePickerRange(id='my-date-picker-range',
                                                        min_date_allowed=site_config['date_range'][0],
                                                        max_date_allowed=site_config['date_range'][1],
                                                        start_date=site_config['date_range'][0],
                                                        end_date=site_config['date_range'][1],
                                                        first_day_of_week=1,  # start on Mondays
                                                        minimum_nights=0,
                                                        updatemode='singledate',
                                                        ),
                            ]),

                    html.Div(id='select-direction',
                            children=[
                                html.Span(children='Traffic direction', style={'font-weight': 'bold'}),
                                dcc.RadioItems(options={'bi_direction': 'Both',
                                                        'in': site_config['config_direction']['in'] + ' only',
                                                        'out': site_config['config_direction']['out'] + ' only'},
                                                value='bi_direction',
                                                inputStyle={"margin-left": "10px"},
                                                inline=True,
                                                id='data-dir-radio'),
                            ]),
                 ]),

        html.Div(id='bar-graph-div',
                 children=[
                 html.Div(id='select-resolution',
                            children=[
                                html.Span(children='Select time resolution', style={'font-weight': 'bold'}),
                                dcc.RadioItems(options={'1_month': 'monthly',
                                                        '1_week': 'weekly',
                                                        '1_day': 'daily',
                                                        '1_hour': 'hourly',
                                                        '30_min': '30 min',
                                                        '15_min': '15 min'},
                                                value=site_config['default_res'],
                                                inputStyle={"margin-left": "10px"},
                                                inline=True,
                                                id='data-agg-radio'),
                            ]),

            dcc.Graph(id='bar-graph',
                      config={'toImageButtonOptions': {
                              'format': 'png', 'filename': 'bar_chart', 'height': None, 'width': None, 'scale': 10}, 'displaylogo': False}
                      )]),

        html.Div(id='table-div',
            children=[
            html.H3(children='Traffic summary on the selected dates'),
            dash_table.DataTable(data=pd.DataFrame(np.zeros((3, 4))).to_dict('records'),
                                 columns=[
                dict(id='dir', name=''),
                dict(id='total_vol', name='Total traffic', type='numeric',
                     format=dash_table.Format.Format().group(True)),
                dict(id='daily_avg', name='Average daily traffic', type='numeric', format=dash_table.Format.Format(
                        precision=1, scheme=dash_table.Format.Scheme.fixed)),
                dict(id='perc', name='Percent', type='numeric',
                     format=dash_table.FormatTemplate.percentage(1))
            ],
                style_cell_conditional=[
                {'if': {'column_id': 'dir'},
                 'width': '25%'},
                {'if': {'column_id': 'total_vol'},
                 'width': '25%'},
                {'if': {'column_id': 'daily_avg'},
                 'width': '25%'},
                {'if': {'column_id': 'perc'},
                 'width': '20%'},
            ],
                style_cell={'font-family': 'Roboto',
                            'padding-right': '10px',
                            'padding-left': '10px'},
                id='avg-table'),
        ]),

        html.Div(id='time-of-day-div',
            children=[
            html.Div(id='select-dayofweek-1',
                children=[
                # html.Span(children='Select day of week', style={'font-weight': 'bold'}),
                dcc.Checklist(id='time-day-checklist',
                            options=config.weekday_list,
                            value=config.weekday_list,
                            inputStyle={"margin-left": "10px"},
                            inline=True,
                            )]),

            dcc.Graph(id='time-of-day',
                    config={'toImageButtonOptions': {'format': 'png', 'filename': 'time_of_day_chart', 'height': None, 'width': None, 'scale': 10}, 'displaylogo': False}
            )]),

        html.Div(children=[dcc.Graph(id='avg-hour-traffic',
                                     config={'toImageButtonOptions': {'format': 'png', 'filename': 'avg_hourly_traffic_chart', 'height': 350, 'width': 750, 'scale': 10}, 'displaylogo': False})]),

        html.Div(children=[dcc.Graph(id='day-of-week',
                                     config={'toImageButtonOptions': {'format': 'png', 'filename': 'day_of_week_chart', 'height': 350, 'width': 750, 'scale': 10}, 'displaylogo': False})]),

        html.Div(children=[dcc.Checklist(id='day-checklist',
                                         options=config.weekday_list,
                                         value=config.weekday_list,
                                         inputStyle={"margin-left": "10px"},
                                         inline=True,
                                         )]),

        html.Div(children=[dcc.RadioItems(id='rain-radio',
                                         options=['All days', 'Only days without rain'],
                                         value='All days',
                                         inputStyle={"margin-left": "10px"},
                                         style={"margin-top": "15px",
                                             "margin-bottom": "5px",},
                                         inline=True,
                                         )]),

        html.Div(children=[dcc.Graph(id='weather-plot',
                                     config={'toImageButtonOptions': {'format': 'png', 'filename': 'weather_chart', 'height': 350, 'width': 750, 'scale': 10}, 'displaylogo': False})]),

        html.Div(id='footer',
        children=[
                        html.H4(children=dcc.Markdown('This dashboard is open source and hosted on a [GitHub repository](https://github.com/fenggroup/bike-traffic-plotly-dash).')),
            html.H4(children=dcc.Markdown('Download the [bike counter data](https://github.com/fenggroup/bike-traffic-plotly-dash/tree/main/data/counter)')),
            # html.H4(children=dcc.Markdown('[Click here](https://fenggroup.org/bike-counter/) to learn more about our bike counting project.')),
            # html.H4(children=dcc.Markdown('[Feng Group](https://fenggroup.org/) 2022'))
        ]),

        # dcc.Store stores the values
        dcc.Store(id='intermediate-value'),
        dcc.Store(id='weather-value'),
        dcc.Store(id='daily-notes'),
        dcc.Store(id='site-config'),

    ])

    return layout

home_layout = html.Div(children=[
    html.H1(children='Bike counter dashboard'),

    html.H3(children='Select a bike counter below to see its dashboard.'),

    html.Div([html.Br(),
              dcc.Link(sites.site_01['site_title'], href=sites.site_01['site_url']),
              html.Br(),
              html.Br(),
              dcc.Link(sites.site_02['site_title'], href=sites.site_02['site_url']),
              html.Br(),
              html.Br(),
              dcc.Link(sites.site_03['site_title'], href=sites.site_03['site_url']),
              html.Br(),
              html.Br(),
    ]),

    html.Div(children=[
    html.H4(children=dcc.Markdown('The dashboards are open source and hosted on [our GitHub repository](https://github.com/fenggroup/bike-traffic-plotly-dash).')),
    html.H4(children=dcc.Markdown('[Feng Group](https://fenggroup.org/) 2022'))
    ]),

])


import streamlit as st
import pandas as pd
import random
from stqdm import stqdm

df_64 = pd.read_csv("juyok_DB.csv", encoding='UTF8')
df_est = pd.read_csv("juyok_DB_est.csv", encoding='UTF8')

# st.write(df_64)

st.markdown("## **당신의 이름은 무엇인가요?**")
name = st.text_input("이름: ")

st.markdown("## **당신의 성별은 무엇인가요?**")
sex = st.selectbox("성별: ",("여성","남성") )
st.write('성별:', sex)

st.markdown('## **당신이 궁금한 사항을 입력해 주세요.**')
question = st.text_input("질문: ")

df_64_count = pd.DataFrame(df_64["Name"])
df_64_count["Count"] = 0

# for _ in stqdm(range(50)):
#print(df_est.at[index2, "step2"])
#print(df_est.at[index2, "step3"])
#print(df_est.at[index2, "step4"])

if st.button("실행"):

    output_area = st.empty()

    for i in range(0,1):
      l1 = random.randrange(0,2)
      l2 = random.randrange(0,2)
      l3 = random.randrange(0,2)
      l4 = random.randrange(0,2)
      l5 = random.randrange(0,2)
      l6 = random.randrange(0,2)

      a = df_64["Name"].loc[(df_64.layer1 == l1)&(df_64.layer2 == l2)&(df_64.layer3 == l3)&(df_64.layer4 == l4)&(df_64.layer5 == l5)&(df_64.layer6 == l6)]
      index = df_64.index[df_64["Name"] == a.values[0]][0]

#      if i == 0:
#        first_row = df_64["Name"].loc[index]

      df_64_count.at[index, "Count"] += 1

    max_index = df_64_count["Count"].idxmax()
    max_row = df_64_count.loc[max_index]

 #   output_area.write(first_row)

    for j in stqdm(range(0,1000)):
      l1 = str(random.randrange(0,2))
      l2 = str(random.randrange(0,2))
      l3 = str(random.randrange(0,2))
      l4 = str(random.randrange(0,2))
      l5 = str(random.randrange(0,2))
      l6 = str(random.randrange(0,2))
#      a = df_64["Name"].loc[(df_64.layer1 == l1)&(df_64.layer2 == l2)&(df_64.layer3 == l3)&(df_64.layer4 == l4)&(df_64.layer5 == l5)&(df_64.layer6 == l6)]
#      index = df_64.index[df_64["Name"] == a.values[0]][0]
      a = l1+l2+l3+l4+l5+l6
      output_area.write(a)
      output_area.write(max_row["Name"])

    index = df_64.index[df_64["Name"] == max_row["Name"]][0]
    st.write('현재- ', max_row["Name"],":", df_64.at[index, "explain_short"])

    index2 = df_est.index[df_est["step1"] == max_row["Name"]][0]

    con = st.container()
    con.caption("Result")

    index1 = df_64.index[df_64["Name"] == df_est.at[index2, "step2"]][0]
    st.write( "3개월후","-",df_est.at[index2, "step2"],":", df_64.at[index1, "explain_short"])

    index1 = df_64.index[df_64["Name"] == df_est.at[index2, "step3"]][0]
    st.write( "6개월후","-",df_est.at[index2, "step3"],":", df_64.at[index1, "explain_short"])

    index1 = df_64.index[df_64["Name"] == df_est.at[index2, "step4"]][0]
    st.write( "9개월후","-",df_est.at[index2, "step4"],":", df_64.at[index1, "explain_short"])

#    total_q = [max_row["Name"],df_est.at[index2, "step2"],df_est.at[index2, "step3"],df_est.at[index2, "step4"]]

#    st.write(total_q)

#    if first_row in total_q:
#      st.write(first_row)
#    else:
#      print("다시")


import rodMassParam as P
import matplotlib.pyplot as plt
from control import TransferFunction as tf
import control as cnt
import numpy as np
import rodMassParam as P

# ----------- noise specification --------
# attenuate noise above omega_n by gamma_n
def add_spec_noise(gamma, omega, flag):
    w = np.logspace(np.log10(omega), np.log10(omega) + 4)
    if flag==True:
        plt.subplot(211)
        plt.plot(w,
                 (20 * np.log10(gamma)) * np.ones(len(w)),
                 color='g',
                 label='noise spec')

#----------- input disturbance specification --------
# reject disturbance above omega by gamma
def add_spec_disturbance(gamma, omega, flag):
    w = np.logspace(np.log10(omega)-4, np.log10(omega))
    if flag==True:
        plt.subplot(211)
        plt.plot(w,
                 20*np.log10(1.0/gamma)*np.ones(len(w)),
                 color='g',
                 label='disturbance spec')

#----------- general tracking specification --------
# track references below omega by gamma
def add_spec_tracking(gamma, omega, flag):
    w = np.logspace(np.log10(omega) - 2, np.log10(omega))
    if flag==True:
        plt.subplot(211)
        plt.plot(w,
                 20*np.log10(1/gamma)*np.ones(len(w)),
                 color='g',
                 label='tracking spec')

#----------- steady state tracking of step --------
# track step by gamma
def add_spec_tracking_step(gamma, flag):
    omega = 0.01
    w = np.logspace(np.log10(omega)-4, np.log10(omega))
    if flag==True:
        plt.subplot(211)
        plt.plot(w,
                 20*np.log10(1.0/gamma),
                 color='g',
                 label='tracking spec')

#----------- steady state tracking of ramp --------
# track ramp by gamma
def add_spec_tracking_ramp(gamma, flag):
    omega = 0.01
    w = np.logspace(np.log10(omega)-4, np.log10(omega))
    if flag==True:
        plt.subplot(211)
        plt.plot(w,
                 20*np.log10(1.0/gamma)-20*np.log10(w),
                 color='g',
                 label='tracking spec')

# proportional control: change cross over frequency
def add_control_proportional(C, kp):
    proportional = tf([kp], [1])
    return C * proportional

# integral control: increase steady state tracking and dist rejection
# ki: frequency at which integral action ends
def add_control_integral(C, ki):
    integrator = tf([1, ki], [1, 0])
    return C * integrator

# phase lag: add gain at low frequency
# z: frequency at which gain ends
# M: separation between pole and zero
def add_control_lag(C, z, M):
    Lag = tf([1, z], [1, z/M])
    return C * Lag

# low pass filter: decrease gain at high frequency (noise)
# p: lpf cutoff frequency
def add_control_lpf(C, p):
    LPF = tf(p, [1, p])
    return C * LPF

# phase lead: increase PM (stability)
# w_L: location of maximum frequency bump
# M: separation between zero and pole
def add_control_lead(C, w_L, M):
    gain = (1.0+np.sqrt(M))/(1.0+1.0/np.sqrt(M))
    Lead = tf([gain * 1.0, gain * w_L / np.sqrt(M)],
              [1.0, w_L * np.sqrt(M)])
    return C * Lead

# Compute plant transfer functions
Plant = cnt.tf([1.0 / (P.m * P.ell**2)], [1, P.b/(P.m*P.ell**2), P.k1/(P.m*P.ell**2)])
C_pid = cnt.tf([(P.kd+P.kp*P.sigma), (P.kp+P.ki*P.sigma), P.ki], [P.sigma, 1, 0])

PLOT = True
# PLOT = False

# calculate bode plot and gain and phase margin
mag, phase, omega = cnt.bode(Plant, dB=True, omega=np.logspace(-3, 5), Plot=False)
gm, pm, Wcg, Wcp = cnt.margin(Plant*C_pid)
print(" pm: ", pm, " Wcp: ", Wcp, "gm: ", gm, " Wcg: ", Wcg)

if PLOT:
    plt.figure(3), plt.clf()
    plt.subplot(211), plt.grid(True)
    plantMagPlot, = plt.semilogx(omega, 20*np.log10(mag), label='Plant')
    plt.subplot(212), plt.grid(True)
    plantPhasePlot, = plt.semilogx(omega, phase, label='Plant')

#########################################
#   Define Design Specifications
add_spec_noise(gamma=10, omega=2000, flag=PLOT)
#add_spec_disturbance(gamma=0.1, omega=0.1, flag=PLOT)
add_spec_tracking(gamma=10, omega=0.02, flag=PLOT)
#add_spec_tracking_ramp(gamma=0.03, flag=PLOT)

#########################################
#   Control Design
C = C_pid
C = add_control_lag(C, z=0.02, M=10)
C = add_control_lpf(C, p=10)
#C = add_control_lead(C, w_L=, M=)
#C = add_control_integral(C, ki=)
#C = add_control_proportional(C, kp=)

mag, phase, omega = cnt.bode(Plant*C, dB=True, omega=np.logspace(-5, 5), Plot=False)
gm, pm, Wcg, Wcp = cnt.margin(Plant*C)
print(" pm: ", pm, " Wcp: ", Wcp, "gm: ", gm, " Wcg: ", Wcg)
if PLOT:
    plt.subplot(211),
    plantMagPlot, = plt.semilogx(omega, 20*np.log10(mag), label='PC')
    plt.subplot(212),
    plantPhasePlot, = plt.semilogx(omega, phase, label='PC')

###########################################################
# add a prefilter to eliminate the overshoot
F = tf(1, 1)
F = add_control_lpf(F, p=1)

############################################
#  Create Plots
############################################
# Closed loop transfer function from R to Y - no prefilter
CLOSED_R_to_Y = (Plant*C/(1.0+Plant*C))
# Closed loop transfer function from R to Y - with prefilter
CLOSED_R_to_Y_with_F = (F*Plant*C/(1.0+Plant*C))
# Closed loop transfer function from R to U
CLOSED_R_to_U = (C/(1.0+Plant*C))

if PLOT:
    plt.figure(4), plt.clf()

    plt.subplot(311),  plt.grid(True)
    mag, phase, omega = cnt.bode(CLOSED_R_to_Y, dB=True, Plot=False)
    plt.semilogx(omega, mag, color='b')
    mag, phase, omega = cnt.bode(CLOSED_R_to_Y_with_F, dB=True, Plot=False)
    plt.semilogx(omega, mag, color='g')
    plt.title('Close Loop Bode Plot')

    plt.subplot(312), plt.grid(True)
    T = np.linspace(0, 2, 100)
    T, yout = cnt.step_response(CLOSED_R_to_Y, T)
    plt.plot(T, yout, color='b')
    plt.ylabel('Step Response')

    plt.subplot(313), plt.grid(True)
    T = np.linspace(0, 2, 100)
    T, yout = cnt.step_response(CLOSED_R_to_U, T)
    plt.plot(T, yout, color='b')
    plt.ylabel('Control Effort')

    # Keeps the program from closing until the user presses a button.
    plt.pause(0.0001)  # not sure why this is needed for both figures to display
    print('Press key to close')
    plt.waitforbuttonpress()
    plt.close()

##############################################
#  Convert Controller to State Space Equations
##############################################
C_num = np.asarray(C.num[0])
C_den = np.asarray(C.den[0])
F_num = np.asarray(F.num[0])
F_den = np.asarray(F.den[0])

Css=cnt.tf2ss(C)
Fss=cnt.tf2ss(F)


zvirata = ["pes", "kočka", "králík", "had"]
zvirata.append("andulka")

# Slovník ze seznamu, klíč je druhý znak ve slově a hodnota je slovo
zvirata_dict = {}
for zvire in zvirata:
    zvirata_dict[zvire[1]] = zvire

# Seřazení klíčů
keys = zvirata_dict.keys()
sort_letters = sorted(keys)

# Vytvoření nového seznamu dle seřazených klíčů
sort_value = []
for key in sort_letters:
    sort_value.append(zvirata_dict[key])

print(sort_value)

# Vytvoření nového slovníku dle seřazených klíčů
# sort_value = {}
# for key in sort_letters:
 #    sort_value[key] = zvirata_dict[key]

# Vypsání pouze hodnot slovníku jako seznam
# seznam_zvirat = list(sort_value.values())
# print(seznam_zvirat)

# Než jsem si přečetla pořádně zadání, že to má být přes slovníky, tak jsem
# vytvořila toto a také fungovalo, ale pak jsem předělala podle zadání:

#for zvire in zvirata:
#    zvirata.sort(key=lambda zvire: zvire[1])
#print(f"Zvířata seřazena dle druhého písmene: {zvirata}")

# lambda se používá, když parametr klíče má být funkce (nebo jiná volatelná),
# která převezme jeden argument a vrátí klíč k použití pro účely řazení


'''
Hacer un programa que lea el nombre y precio de un producto,
el programa repetira esta accion hasta que el usuario lo desee,
al finalisar mostrara el total de productos, la sumatoria de los precios, el porcentaje de IVA respecto al total y el total a pagar

'''
cantidadProductos = 0
precioTotal = 0.0
totalPagar = 0.0
iva = 0.0
confirmacion = 0
print('Bienvenido a la calculadora de precios de IBM: \nA continuacion Ingresa los nombres y precios de los productos:\n')

while(confirmacion == 0):

    nombre = input('Ingresa el nombre del producto: \n')
    precioProducto = float(input('Ingresa el precio del producto: \n'))
    precioTotal += precioProducto
    cantidadProductos += 1
    confirmacion = int(input('Deseas agregar mas productos? 0 = SI 1 = NO\n'))

iva = precioTotal * 0.16
totalPagar = precioTotal + iva

print(f'Cantidad de productos ingresados: {cantidadProductos} \n Precio Total: {precioTotal} \n Total Iva: {iva} \n Total a pagar: {totalPagar}')


#!/usr/bin/env python3

from __future__ import print_function

import ase.io
import sys
import numpy as np

if len(sys.argv) != 3:
    sys.stderr.write("Usage: %s model.so model_params < input.xyz\n" % sys.argv[0])
    sys.exit(1)

at = ase.io.read(sys.stdin, format="extxyz")

import fortranMCMDpy
FORTRAN_model = sys.argv[1]
FORTRAN_model_params = sys.argv[2]
f_MC_MD = fortranMCMDpy.fortran_MC_MD(FORTRAN_model)
params = np.array([ float(x) for x in FORTRAN_model_params.split() ])
f_MC_MD.init_model(params)

f0 = np.zeros((len(at),3))
e0 = f_MC_MD.eval_forces(at, f0)
print("e0 ", e0)
print("f0 ", f0)
print("")
pos_0 = at.get_positions()
for i_at in range(len(at)):
    for i_cart in range(3):

        pos_pert = pos_0.copy()
        for i_dx in range(8):
            dx = 10.0**(-i_dx)

            pos_pert[i_at, i_cart] = pos_0[i_at, i_cart] + dx
            at.set_positions(pos_pert)
            ep = f_MC_MD.eval_energy(at)

            pos_pert[i_at, i_cart] = pos_0[i_at, i_cart] - dx
            at.set_positions(pos_pert)
            em = f_MC_MD.eval_energy(at)
            print(i_at, i_cart, dx, (ep-em)/(2.0*dx), f0[i_at,i_cart], (ep-em)/(2.0*dx)+ f0[i_at,i_cart])
        print("")


####
# Each team's file must define four tokens:
#     team_name: a string
#     strategy_name: a string
#     strategy_description: a string
#     move: A function that returns 'c' or 'b'
####

#Idea: run your own historical simulation before you play against anyone. This will allow you to determine how your opponent will play and give the percentage chances. Then I will play according to what the best play is against my opponent, based on the data from the simulation.

team_name = 'maggin'

strategy_name = 'Pattern Recognition'
strategy_description = 'Identify pattern that each player engages in.'

    # This player always adapts then either colludes or betrays based on opponent's   historical pattern.

def move(my_history, their_history, my_score, their_score):

      if len(my_history)==0:
          return 'b'
      else:
          # View last round
          recent_round_them = their_history[-1]
          recent_round_me = my_history[-1]

          # Examine rounds before that one
          for round in range(len(my_history)-1):
              prior_round_them = their_history[round]
              prior_round_me = my_history[round]
              # If one matches
              if (prior_round_me == recent_round_me) and \
                      (prior_round_them == recent_round_them):
                  return their_history[round]
          # No match found
          if my_history[-1]=='c' and their_history[-1]=='b':
              return 'b'


import numpy as np
from constants.constants import UNI, EXTENDED
from utils.progress_bar import progress_bar

def create(img:np.array, UNICODE=EXTENDED) -> str:
    res = ""
    for i,line in enumerate(img):
        progress_bar(i/img.shape[0])
        for pixel in line:
            res += UNICODE[int(sum(pixel)/768*len(UNI))]
        res += "\n"
    return res


#

num = int(input())
if num % 2 != 0 and num >= 1 and num <= 100:
    foo = (num / 2)+1
    count = [int(i) for i in range(num) if i % 2 != 0][::-1]
    rnum = num
    #print(count)
    for i in range(num):
        print(" "*int(i),end='')
        print(i+1,end="")
        if int(foo) == i+1:
            print("")
            break
        else:
            print(" "*int(count[i]),end="")
            print(int(rnum))
        rnum -= 1


'''
binary search (이진탐색) : 반드시 정렬된 상태에서 시작해야한다. 로그실행시간을 보장한다.
용어 설명
target : 찾고자하는 값
data: 오름차순으로 정렬된 list
start: data의 처음 값 인덱스
end: data의 마지막 값 인덱스
mid: start,end의 중간 인덱스
바이너리 서치
data중 target을 검색하여 index 값을 return 한다.
없으면 None을 return
'''
# target = 찾고자하는값, data: list값
def binary_search(target,data):
    data.sort() # 먼저 정렬부터한다 (오름차순)
    start = 0
    end = len(data) - 1
    while start <= end: # 반복문은 인덱스 끝까지돌린다.
        mid = (start+end) // 2 # 중간 인덱스
        if data[mid] == target:
            return mid # 함수를 끝낸다.
        elif data[mid] < target: #중간값 보다 타겟값이 크면 시작인덱스를 mid보다 뒤로
            start = mid + 1
        else:
            end = mid - 1
    return None

li = [i ** 2 for i in range(11)]
print(li)
target = 9
idx = binary_search(target,li)

if idx:
    print(li[idx])
else:
    print('찾는게없다.')


from lxml import etree
import requests
import pymysql
def getdel():
        url = 'https://book.douban.com/top250'
        data = requests.get(url).text
        s=etree.HTML(data)

        file=s.xpath('//*[@id="content"]/div/div[1]/div/table/tr/td[2]/div[1]/a/@title')
        print(file)
        return file
l1=getdel()
db = pymysql.connect("localhost", "root", "admin", "test", charset="utf8")
cs = db.cursor()
for i in range(len(l1)):

    sql = "insert into py(jing) values('{0}')".format(l1[i])

    cs.execute(sql)
    db.commit()
print('数据插入完成')
db.close()


#class without chaining
##*********************************
##class MyHashMap:
##    def __init__(self):
##        self.size = 10
##        self.arr = [None for i in range(self.size)]
##        #print(self.arr)
##
##    def put(self,key,val):
##        hsh = self.gethash(key)
##        self.arr[hsh] = val
##
##    def get(self,key):
##        print("Get value at {}:{}".format(key,self.arr[self.gethash(key)]))
##        return self.arr[self.gethash(key)]
##
##    def remove(self,key):
##        self.arr[self.gethash(key)] = None
##
##    def gethash(self,key):
##        #print("\thash of {} is {}".format(key,key%self.size))
##        return key%self.size

#class with chainging
class MyHashMap:
    def __init__(self):
        self.size = 100
        self.arr = [[] for i in range(self.size)]

    def gethash(self,key):
        print("hash of {} is {}".format(key,key%self.size))
        return key%self.size

    def put(self,key,val):
        print("\nPUT ",val)
        hsh = self.gethash(key)
        found = False
        for i,v in enumerate(self.arr[hsh]):
            print("i:{},v:{}".format(i,v))
            if v:
                if v[0] == key:
                    print(v)
                    arr[hsh][i] = (key,val)
                    found = True
                    break
        if found == False:
            self.arr[hsh].append((key,val))
            print("\tCurrent Arr:",self.arr)

    def get(self,key):
        print("\nGET ",key)
        hsh = self.gethash(key)
        for v in self.arr[hsh]:
            if v[0] == hsh:
                print("value of {} is {}".format(v[0],v[1]))
                return v[1]
        return -1

    def remove(self,key):
        hsh = self.gethash(key)
        for i,v in enumerate(self.arr):
            if v[0] == key:
                print("{} to be deleted".format(self.arr[hsh][i]))
                self.arr[hsh][i] = None

M = MyHashMap()
M.put(1,1)
M.put(2,2)
M.put(11,3)
M.get(1)
M.get(3)
print(M.arr)


import requests
from bs4 import BeautifulSoup
import os

def get_book(url):
    response = requests.get(url)
    response.encoding = "utf-8"
    text = response.text
    soup = BeautifulSoup(text)
    div_show = soup.select("div.dirShow")[0]
    # print(div_show)
    dirs = div_show.select("li a")
    count = len(dirs)

    for num in range(1, count + 1):
        url = url.replace('0.html', '%s.html').replace('bookDir', 'book')
        url_after = url % (num)
        print(url_after)
        response = requests.get(url_after)
        response.encoding = 'utf-8'
        text = response.text
        soup = BeautifulSoup(text)
        titles = soup.select("table td")
        print(titles[3].text)
        articles = soup.select("div#Content")
        print(articles[0].text)

        # 保存文件
        is_exist = os.path.exists(r"D:\flaskDemo\static\books")
        if not is_exist:
            os.mkdir(r"D:\flaskDemo\static\books")
        title = titles[3].text + ".txt"
        with open(r"D:\flaskDemo\static\books\\" + title, "a", encoding="utf-8") as f:
            f.write(articles[0].text)

if __name__== "__main__":
    # 沉默的大多数
    # url="http://t.icesmall.cn/bookDir/2/335/0.html"
    # 麦田守望者
    # http://t.icesmall.cn/bookDir/1/33/0.html
    # 挪威的森林
    # http://t.icesmall.cn/bookDir/3/423/0.html
    # 输入世界名著网书籍目录地址
    get_book("http://t.icesmall.cn/bookDir/3/423/0.html")


#!/usr/bin/env python3
import argparse
import sys
from typing import List, Union
import uuid

import capstone_gt
import gtirb
from gtirb_capstone.instructions import GtirbInstructionDecoder

def lookup_sym(node: gtirb.Block) -> Union[str, None]:
    """
    Find a symbol name that describes the node.
    """
    for sym in node.module.symbols:
        if sym._payload == node:
            return sym.name

def node_str(node: gtirb.Block) -> str:
    """
    Generate a string that uniquely identifies the node
    """
    if isinstance(node, gtirb.ProxyBlock):
        return lookup_sym(node) or node.uuid
    else:
        return hex(node.address)

def has_undefined_branch(branches: List[gtirb.Edge]) -> bool:
    """
    Determine if any of the branches are not resolved to a target.
    """
    for branch in branches:
        if isinstance(branch.target, gtirb.ProxyBlock) and not lookup_sym(
            branch.target
        ):
            return True
    return False

def has_symbolic_branch(branches: List[gtirb.Edge]) -> bool:
    """
    Determine if any of the branches are to a defined symbol.
    """
    for branch in branches:
        if lookup_sym(branch.target):
            return True
    return False

def is_skipped_section(node: gtirb.CodeBlock) -> bool:
    """
    Determine if the node is part of an uninteresting section.
    """
    skipped_sections = [
        ".plt",
        ".init",
        ".fini",
        ".MIPS.stubs",
    ]

    for section in node.module.sections:
        if section.name not in skipped_sections:
            continue

        for interval in section.byte_intervals:
            start = interval.address
            end = interval.address + interval.size

            if start <= node.address and node.address < end:
                return True
    return False

def get_func_entry_name(node: gtirb.CodeBlock) -> Union[str, None]:
    """
    If the node is the entry point to a function, return the function name.

    Otherwise returns None
    """
    for key, value in node.module.aux_data["functionNames"].data.items():
        if node in node.module.aux_data["functionEntries"].data[key]:
            return value.name

def belongs_to_skipped_func(node: gtirb.CodeBlock) -> bool:
    """
    Determine if a CFG node is
    """
    skipped_funcs = [
        "__do_global_ctors_aux",
        "__do_global_dtors_aux",
        "__libc_csu_fini",
        "__libc_csu_init",
        "_dl_relocate_static_pie",
        "_start",
        "deregister_tm_clones",
        "frame_dummy",
        "register_tm_clones",
    ]

    for name in skipped_funcs:
        for key, value in node.module.aux_data["functionNames"].data.items():
            if value.name == name:
                if node in node.module.aux_data["functionBlocks"].data[key]:
                    return True

    return is_skipped_section(node)

def is_padding(node: gtirb.CodeBlock) -> bool:
    """
    Determine if a CFG node is padding
    """
    for key, padding_size in node.module.aux_data["padding"].data.items():
        padding_addr = key.element_id.address + key.displacement

        if padding_addr == node.address:
            return True

    return False

def check_unreachable(module: gtirb.Module) -> int:
    """
    Check a GTIRB module for unexpected unreachable code
    """
    error_count = 0

    for node in module.cfg_nodes:
        if (
            not isinstance(node, gtirb.CodeBlock)
            or belongs_to_skipped_func(node)
            or is_padding(node)
        ):
            continue

        func = get_func_entry_name(node)
        if len(list(node.incoming_edges)) == 0 and func != "main":

            if func:
                # In some cases in our examples, function call sites are
                # optimized away, but the function is left in the binary.
                # We warn for these - if this code isn't being run, we're not
                # testing whether ddisasm disassembled it well, and we may want
                # to consider reworking those examples.
                print(
                    'WARNING: unreachable function "{}" at {}'.format(
                        func, node_str(node)
                    )
                )
            else:
                # Unreachable code that is not a function entry is likely to
                # be an error, such as jump table where not all possible
                # targets were discovered.
                print("ERROR: unreachable code at", node_str(node))
                error_count += 1

    return error_count

def check_unresolved_branch(module: gtirb.Module) -> int:
    """
    Check a GTIRB module for unresolved branches
    """
    error_count = 0

    for node in module.cfg_nodes:
        if (
            not isinstance(node, gtirb.CodeBlock)
            or belongs_to_skipped_func(node)
            or is_padding(node)
        ):
            continue

        branches = []

        for edge in node.outgoing_edges:
            if edge.label.type not in (
                gtirb.Edge.Type.Return,
                gtirb.Edge.Type.Fallthrough,
            ):
                branches.append(edge)

        # Calls to PLT functions seem to have a branch to a ProxyBlock for
        # that symbol and a branch to the original PLT function.
        if has_undefined_branch(branches) and not has_symbolic_branch(
            branches
        ):
            print("ERROR: unresolved jump in", node_str(node))
            error_count += 1

    return error_count

def check_cfg_empty(module: gtirb.Module) -> int:
    """
    Check if a GTIRB module has an empty CFG
    """
    if len(list(module.cfg_nodes)) == 0:
        print("ERROR: CFG has no nodes")
        return 1

    return 0

def check_main_is_code(module: gtirb.Module) -> int:
    """
    Check a GTIRB module for a `main` symbol that is not a CodeBlock.

    Returns the number of errors found.
    """
    error_count = 0

    for sym in module.symbols:
        if sym.name == "main":
            if not isinstance(sym.referent, gtirb.CodeBlock):
                print("ERROR: main is not code")
                error_count += 1

    return error_count

def check_decode_mode_matches_arch(module: gtirb.Module) -> int:
    """
    Ensure a GTIRB only uses DecodeMode values that match the architecture

    Returns the number of errors found.
    """
    error_count = 0

    # if a new mode is added, we will raise a KeyError unless it is added
    # to this dictionary.
    mode_to_arch = {
        gtirb.CodeBlock.DecodeMode.Thumb: gtirb.module.Module.ISA.ARM
    }

    for block in module.code_blocks:
        if block.decode_mode == gtirb.CodeBlock.DecodeMode.Default:
            # "Default" is correct on every arch
            continue

        if module.isa != mode_to_arch[block.decode_mode]:
            print(f"ERROR: {module.isa} does not support {block.decode_mode}")
            error_count += 1

    return error_count

def check_outgoing_edges(module: gtirb.Module) -> int:
    """
    Check outgoing edges for invalid configurations
    """
    error_count = 0

    for node in module.cfg_nodes:
        fallthrough_count = 0
        direct_call_count = 0
        direct_jump_count = 0

        for edge in node.outgoing_edges:

            if edge.label.direct and edge.label.type == gtirb.Edge.Type.Call:
                direct_call_count += 1
            elif (
                edge.label.direct and edge.label.type == gtirb.Edge.Type.Branch
            ):
                direct_jump_count += 1
            elif edge.label.type == gtirb.Edge.Type.Fallthrough:
                fallthrough_count += 1

        if fallthrough_count > 1:
            print("ERROR: multiple fallthrough from ", node_str(node))
            error_count += 1
        if direct_call_count > 1:
            print("ERROR: multiple direct call from ", node_str(node))
            error_count += 1
        if direct_jump_count > 1:
            print("ERROR: multiple direct jump from ", node_str(node))
            error_count += 1

    return error_count

def is_rep_loop(inst: capstone_gt.CsInsn) -> bool:
    """
    Check if an instruction is a rep/repe/repne loop
    """
    return inst.prefix[0] in [
        capstone_gt.x86.X86_PREFIX_REP,
        capstone_gt.x86.X86_PREFIX_REPE,
        capstone_gt.x86.X86_PREFIX_REPNE,
    ]

def is_direct(inst: capstone_gt.CsInsn) -> bool:
    """
    Check if a call or jump instruction is direct
    """
    assert any(
        inst.group(grp)
        for grp in (
            capstone_gt.x86.X86_GRP_CALL,
            capstone_gt.x86.X86_GRP_JUMP,
            capstone_gt.x86.X86_GRP_BRANCH_RELATIVE,
        )
    )
    target = inst.operands[0]
    return target.type == capstone_gt.CS_OP_IMM

def is_pc_relative(inst: capstone_gt.CsInsn) -> bool:
    """
    Check if a call or jump instruction is pc-relative
    """
    assert any(
        inst.group(grp)
        for grp in (
            capstone_gt.x86.X86_GRP_CALL,
            capstone_gt.x86.X86_GRP_JUMP,
            capstone_gt.x86.X86_GRP_BRANCH_RELATIVE,
        )
    )
    target = inst.operands[0]
    return (
        target.type == capstone_gt.CS_OP_MEM
        and inst.reg_name(target.mem.base) == "rip"
    )

def check_edge_instruction_group(module: gtirb.Module) -> int:
    """
    Check edges for valid instruction groups
    """
    # TODO: support non-x86 checks
    if module.isa not in [gtirb.Module.ISA.X64, gtirb.Module.ISA.IA32]:
        return 0

    err_count = 0
    decoder = GtirbInstructionDecoder(module.isa)

    # TODO: there is one more generic capstone group, X86_GRP_PRIVILEGE.
    # does it belong in Syscall?
    edge_type_groups = {
        gtirb.Edge.Type.Branch: set(
            (
                capstone_gt.x86.X86_GRP_JUMP,
                capstone_gt.x86.X86_GRP_BRANCH_RELATIVE,
            )
        ),
        gtirb.Edge.Type.Call: set((capstone_gt.x86.X86_GRP_CALL,)),
        gtirb.Edge.Type.Return: set((capstone_gt.x86.X86_GRP_RET,)),
        gtirb.Edge.Type.Syscall: set((capstone_gt.x86.X86_GRP_INT,)),
        gtirb.Edge.Type.Sysret: set((capstone_gt.x86.X86_GRP_IRET,)),
    }

    for edge in module.ir.cfg:
        if edge.label.type == gtirb.Edge.Type.Fallthrough:
            # fallthrough edges do not map to a specified instruction group
            continue

        block = edge.source

        # get the last instruction
        for instruction in decoder.get_instructions(block):
            last_inst = instruction

        # ensure instruction can be an edge

        # Instructions with rep prefix can have self-edge
        if (
            edge.label.type == gtirb.Edge.Type.Branch
            and is_rep_loop(last_inst)
            and edge.target == block
        ):
            continue

        valid_groups = edge_type_groups[edge.label.type]
        if not any(last_inst.group(grp) for grp in valid_groups):
            print(
                "ERROR: invalid edge instruction group at 0x{:08x}: {}".format(
                    last_inst.address, last_inst.groups
                )
            )
            err_count += 1

    return err_count

def check_cfg_completeness(module: gtirb.Module) -> int:
    """
    Check we have 1 call/branch edge from all direct or
    pc-relative calls/jumps.
    """
    # TODO: support non-x86 checks
    if module.isa not in [gtirb.Module.ISA.X64, gtirb.Module.ISA.IA32]:
        return 0

    err_count = 0
    decoder = GtirbInstructionDecoder(module.isa)

    for block in module.code_blocks:
        # get the last instruction
        for instruction in decoder.get_instructions(block):
            last_inst = instruction
        if last_inst.group(capstone_gt.x86.X86_GRP_CALL):
            call_edges = [
                edge
                for edge in block.outgoing_edges
                if edge.label.type == gtirb.EdgeType.Call
            ]
            if is_direct(last_inst) or is_pc_relative(last_inst):

                # do not count if we are using the 'call next; next: pop'
                # trick to get the PC value.
                if (
                    is_direct(last_inst)
                    and module.isa == gtirb.Module.ISA.IA32
                    and last_inst.operands[0].imm
                    == last_inst.address + last_inst.size
                ):
                    continue

                if len(call_edges) != 1:
                    print(
                        "ERROR: expected 1 call edge at "
                        f"0x{last_inst.address:08x} and got {len(call_edges)}"
                    )
                    err_count += 1
        elif last_inst.group(capstone_gt.x86.X86_GRP_JUMP):

            # The first block of plt sections looks like:
            #    pushq .got.plt+8(%rip)
            #    jmpq *.got.plt+16(%rip)  <----
            # And the first 3 entries of .got.plt (or .got) are:
            #    .quad link-time address of _DYNAMIC  # set by linker
            #    .quad Obj_Entry  # set by ld.so
            #    .quad _rtld_bind_start  # set by ld.so
            # Currently we don't generate an edge for that
            # jump because .got.plt+16 has a 0 and no relocations.
            if (
                block.section.address == block.address
                and block.section.name in [".plt", ".plt.sec", ".plt.got"]
            ):
                continue

            branch_edges = [
                edge
                for edge in block.outgoing_edges
                if edge.label.type == gtirb.EdgeType.Branch
            ]
            if is_direct(last_inst) or is_pc_relative(last_inst):
                if len(branch_edges) != 1:
                    print(
                        "ERROR: expected 1 branch edge at "
                        f"0x{last_inst.address:08x} and got"
                        f" {len(branch_edges)}"
                    )
                    err_count += 1

    return err_count

def check_dangling_auxdata(module: gtirb.Module) -> int:
    """
    Check for dangling UUIDs in elfSymbolTabIdxInfo auxdata
    """
    err_count = 0

    for k, v in module.aux_data["elfSymbolTabIdxInfo"].data.items():
        if not isinstance(k, gtirb.Symbol):
            if isinstance(k, uuid.UUID):
                print(
                    "ERROR: expected elfSymbolTabInfo key to be Symbol, but "
                    f"it is a dangling UUID: {k}, {v}"
                )
            else:
                print(
                    "ERROR: expected elfSymbolTabInfo key to be Symbol, but "
                    f"it is {type(k)}: {k}, {v}"
                )
            err_count += 1

    return err_count

CHECKS = {
    "unreachable": check_unreachable,
    "unresolved_branch": check_unresolved_branch,
    "cfg_empty": check_cfg_empty,
    "main_is_code": check_main_is_code,
    "decode_mode_matches_arch": check_decode_mode_matches_arch,
    "outgoing_edges": check_outgoing_edges,
    "edge_instruction_group": check_edge_instruction_group,
    "cfg_completeness": check_cfg_completeness,
    "dangling_auxdata": check_dangling_auxdata,
}

class NoSuchCheckError(Exception):
    """Indicates an invalid GTIRB check was specified"""

    pass

def run_checks(module: gtirb.Module, selected_checks: List[str]):
    """
    Run specified checks

    Raises NoSuchCheckError for unexpected names in selected_checks
    """
    error_count = 0
    for selected_check in selected_checks:
        if selected_check not in CHECKS:
            raise NoSuchCheckError(f"No such check: {selected_check}")

        error_count += CHECKS[selected_check](module)

    return error_count

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("path")

    check_names = list(CHECKS.keys())
    check_names.append("all")

    parser.add_argument(
        "--check",
        choices=check_names,
        default="all",
        help="The name of the check to run",
    )
    args = parser.parse_args()

    module = gtirb.IR.load_protobuf(args.path).modules[0]
    checks = list(CHECKS.keys()) if args.check == "all" else [args.check]
    error_count = run_checks(module, checks)
    sys.exit(error_count)

if __name__ == "__main__":
    main()


# https://www.geeksforgeeks.org/find-sum-modulo-k-first-n-natural-number/

def find_sum(N,K):

    ans = 0

    # Counting the number of times
    # 1, 2, .., K-1, 0 sequence occurs.
    y = N / K

    # Finding the number of elements
    # left which are incomplete of
    # sequence Leads to Case 1 type.
    x = N % K

    # adding multiplication of number
    # of times 1, 2, .., K-1, 0
    # sequence occurs and sum of
    # first k natural number and
    # sequence from case 1.
    ans = ((K * (K - 1) / 2) * y +
                (x * (x + 1)) / 2)

    return int(ans)

if __name__ == "__main__":
    N = 10
    K = 2
    print(find_sum(N, K))


class myclass:   #aclass
    def inherit(self):
      self.A=int(input("enter the A value:"))
      self.B=int(input("enter the B value:"))

class Addtion(myclass):
    def add(self):
      self.inherit()
      c=self.A+self.B
      print("Addition value are",c)

class multiplication(myclass):
    def mul(self):
     self.inherit()
     c=self.A*self.B
     print("multiplication is :",c)

class subraction(myclass):
    def sub(self):
      self.inherit()
      c=self.A-self.B
      print("subraction",c)

obj1=Addtion()
obj1.add()
obj=multiplication()
obj.mul()
obj=subraction()
obj.sub()


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RangeSlider
import pims

def gui(input_img):
# read in an image, usually np.array kind. This one will be a stack of images
# Initialize the frame number to be zero, since array indexing
    frame = 0
    img = input_img

    fig, axs = plt.subplots(1, 2, figsize=(10, 5))
    plt.subplots_adjust(bottom=0.25)

    im = axs[0].imshow(img[frame])
    axs[1].hist(img.flatten(), bins='auto')
    axs[1].set_title('Histogram of pixel intensities')

    # Create the RangeSlider
    slider_ax = plt.axes([0.20, 0.1, 0.60, 0.03])
    slider = RangeSlider(slider_ax, "Threshold", img[frame].min(), img[frame].max())

    # Create the Vertical lines on the histogram
    lower_limit_line = axs[1].axvline(slider.val[0], color='k')
    upper_limit_line = axs[1].axvline(slider.val[1], color='k')

    def update(val):
        # The val passed to a callback by the RangeSlider will
        # be a tuple of (min, max)

        # Update the image's colormap
        im.norm.vmin = val[0]
        im.norm.vmax = val[1]

        # Update the position of the vertical lines
        lower_limit_line.set_xdata([val[0], val[0]])
        upper_limit_line.set_xdata([val[1], val[1]])

        # Redraw the figure to ensure it updates
        fig.canvas.draw_idle()

    slider.on_changed(update)
    plt.show()

# Test case
gui(np.array(pims.open("./example/Single_molecule_moving.tif")))


import itertools
from collections import OrderedDict
import nltk
from spellchecker import SpellChecker
from nltk.corpus import wordnet as wn
from ranker import Ranker
#import utils
"""
search engine for spell checker
"""

# DO NOT MODIFY CLASS NAME
class Searcher:
    # DO NOT MODIFY THIS SIGNATURE
    # You can change the internal implementation as you see fit. The model
    # parameter allows you to pass in a precomputed model that is already in
    # memory for the searcher to use such as LSI, LDA, Word2vec models.
    # MAKE SURE YOU DON'T LOAD A MODEL INTO MEMORY HERE AS THIS IS RUN AT QUERY TIME.
    def __init__(self, parser, indexer, model=None):
        self._parser = parser
        self._indexer = indexer
        self._ranker = Ranker()
        self._model = model

    # DO NOT MODIFY THIS SIGNATURE
    # You can change the internal implementation as you see fit.
    def search(self, query, k=None):
        """
        Executes a query over an existing index and returns the number of
        relevant docs and an ordered list of search results (tweet ids).
        Input:
            query - string.
            k - number of top results to return, default to everything.
        Output:
            A tuple containing the number of relevant search results, and
            a list of tweet_ids where the first element is the most relavant
            and the last is the least relevant result.
        """
        query_list = query.split(" ")
        query_as_list = self._parser.text_operation(query_list)
        # extension  by spell checker
        queary_list_after_word_net = self.q_spell_check(query_as_list)
        #remove stop words
        query_as_list = self._parser.parse_sentence(queary_list_after_word_net)
        # find the docs
        relevant_docs = self._relevant_docs_from_posting(query_as_list) # return all the rel doc for the quiry
        #ranked_doc_ids = Ranker.rank_relevant_docs(relevant_docs)

        relevant_docs = OrderedDict(sorted(relevant_docs.items(), key=lambda item: item[1], reverse=True))
        relevant_docs = dict(itertools.islice(relevant_docs.items(), 2000))   #max is 2000 docs
        relevant_docs_sort = self._ranker.dot_prodact_and_cos(relevant_docs, self._indexer, len(query_as_list))
        n_relevant = len(relevant_docs)
        if k is not None:
            relevant_docs_sort = self.ranker.retrieve_top_k(relevant_docs_sort, self.k)
        return n_relevant, relevant_docs_sort

    # feel free to change the signature and/or implementation of this function
    # or drop altogether.
    def _relevant_docs_from_posting(self, query_as_list):
        """
        This function loads the posting list and count the amount of relevant documents per term.
        :param query_as_list: parsed query tokens
        :return: dictionary of relevant documents mapping doc_id to document frequency.
        """
        relevant_docs = {}
        for word in query_as_list:
            posting_list = self._indexer.get_term_posting_list(word)  # get all the twite with this word
            for doc in posting_list:
                tf = self._indexer.get_term_inverted_idx(word)[2]
                id = doc[0]
                if id not in relevant_docs.keys():
                    relevant_docs[id] = [1, []]
                    # self._indexer.get_term_inverted_idx[word]
                    tfidf = doc[4] * tf
                    relevant_docs[id][1].append(tfidf)
                else:
                    tfidf = doc[4] * tf
                    relevant_docs[id][1].append(tfidf)
                    relevant_docs[id][0] += 1

        return relevant_docs
    """
    this function expand the query by using spell checker
    get query as list and add words by checker
    """
    def q_spell_check(self, query):
      spell = SpellChecker()
      corr_q = []
      corr_q.extend(query)
      i = 0
      for word in query:
          new_word = spell.correction(word)
          if new_word != word:
              if self._indexer._is_term_exist_in_idx(new_word):
                  corr_q[i] = new_word
          i += 1
      return corr_q


import random
from kafka import KafkaProducer

producer = KafkaProducer(bootstrap_servers='0.0.0.0:9092')

num = random.randint(0, 10)

num_bytes = bytes(str(num), encoding='utf-8')

is_send = producer.send('test-topic', value=num_bytes, key=num_bytes)
# Block for 'synchronous' sends
try:
    record_metadata = is_send.get(timeout=2)
    print(record_metadata)
except Exception as exc:
    # Decide what to do if produce request failed...
    #log.exception()
    print('Exception: ', exc)

print(' finish ')
# Successful result returns assigned partition and offset

# print(record_metadata.partition)
# print(record_metadata.offset)


# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 10:30:26 2018

@author: Puneet Kumar
"""

x = input("enter the text : ")

#x = 'defgh'

k = x = input("enter the text : ")

#x = 'defgh'

k = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m']

alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
'''
with open('substi.txt','r') as f:
    x = f.read()
  '''

b =[]

t = []

for i in range(len(x)):
    t.append(k[alpha.index(x[i])])
    #b.extend(k[int(ord(x[(i)]) - 97)])

print(t)

for i in range(len(t)):
    b.append(alpha[k.index(t[i])])
    #b.extend(k[int(ord(x[(i)]) - 97)])

print(b)

'''
str = ("".join(b))

print("The Encrypted Massage : ",str)
#print("Entrypted massage is: ",b)

with open('substi.txt','a') as f:
    f.write(str)'''


import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

items = [rock, paper, scissors]

rand_no = random.randint(0 , 2)

user_no = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

if(user_no >= 0 and user_no <= 2):
    print(f"{items[user_no]}\n\nComputer chose:\n{items[rand_no]}\n")
    if(user_no == 0 and rand_no == 2):
        print("You win!")
    elif(user_no == 2 and rand_no == 0):
        print("You lose")
    elif(rand_no > user_no):
        print("You lose")
    elif(user_no > rand_no):
        print("You win!")
    else:
        print("It's a draw")
else:
    print("You typed an invalid number, you lose!")


# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.shortcuts import render
from django.views.generic.base import View
from django.http import JsonResponse
from participa.settings import SEFAZ_API_URL
from participa.auth_sefaz.views import ParticipaSefazRequest, BaseView
from participa.auth_sefaz.models import User
from participa.report.models import Report, MonitoredNFe
from rest_framework.renderers import JSONRenderer

import json

class ReportView(BaseView):

    def get(self):
        pass

    def post(self, *args, **kwargs):
        get_token = self.request.META['HTTP_AUTHORIZATION']
        data = json.loads(str(self.request.body, "utf_8"))
        user = User.objects.filter(cpf=data.get("cpfDestinatario", None)).first()
        if user:
            return_report = self.send_report(json.dumps(data), get_token)
            if return_report:
                report = Report(id_report=return_report.text, user=user)
                report.save()
                return self.success_recive()
        else:
            return self.error_recive()

class QRCodeMonitorView(BaseView):

    def post(self, *args, **kwargs):

        data = json.loads(str(self.request.body, "utf_8"))
        user = User.objects.filter(cpf=data.get("cpf", None)).first()
        qr_code_data = data.get("qrcode_data", None)
        if user and qr_code_data:
            monitor = MonitoredNFe(user=user, qr_code_data=qr_code_data)
            monitor.save()
            return self.success_recive()
        else:
            return self.error_recive()

class QRCodeMonitorListView(BaseView):

    def post(self, *args, **kwargs):
        data = json.loads(str(self.request.body, "utf_8"))
        user = User.objects.filter(cpf=data.get("cpf", None)).first()
        if user:
            monitoreds = MonitoredNFe.objects.filter(user=user)
            monitoreds_serialized = dict(monitoreds=list(monitoreds.values('pk', 'status', 'qr_code_data', 'created_at', 'updated_at')))

            return JsonResponse(monitoreds_serialized)
        else:
            return self.error_recive()


from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from PIL import Image

def make_pages(page, item_list, page_size):

	paginator = Paginator(item_list, page_size)

	try:
		images = paginator.page(int(page))
	except PageNotAnInteger:
		images = paginator.page(1)
	except EmptyPage:
		images = paginator.page(paginator.num_pages)

	return images

def image_rotate(image_url, angle):
	path = '.' + image_url
	oi = Image.open(path)
	oi = oi.rotate(angle)
	oi.save(path)
	return 'success'


class NegativeDigitError(ValueError):
    """Exception raised when digit is negative in power and square_root calculations"""

    def __init__(self, digit):
        self.digit = digit
        self.message = f'Digit "{digit}" has to be positive for powering or square rooting'
        super().__init__(self.message)

class NotIntFloatError(ValueError):
    """Exception raised when input data neither int nor float for any action in calculations"""

    def __init__(self, args):
        self.args  = args
        self.types = {arg: type(arg) for arg in args}
        self.message = f'Values "{self.types}" has to be int or float to proceed calculation'
        super().__init__(self.message)

class Calculator:

    def is_int_or_float(self, x, y) :
        return isinstance(x, (int, float)) and isinstance(y, (int, float))

    def add(self, x, y):
        try:
            if not self.is_int_or_float(x, y) :
                raise NotIntFloatError((x, y))
            return x + y
        except NotIntFloatError as e :
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

    def subtract(self, x, y):
        try:
            if not self.is_int_or_float(x, y) :
                raise NotIntFloatError((x, y))
            return x - y
        except NotIntFloatError as e :
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

    def multiply(self, x, y):
        try:
            if not self.is_int_or_float(x, y) :
                raise NotIntFloatError((x, y))
            return round(x * y, 2)
        except NotIntFloatError as e :
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

    def divide(self, x, y):
        try:
            if not self.is_int_or_float(x, y) :
                raise NotIntFloatError((x, y))
            return round(x / y, 5)
        except NotIntFloatError as e :
            return f'Error: {e}'
        except ZeroDivisionError as e:
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

    def power(self, x, y):
        try:
            if not self.is_int_or_float(x, y) :
                raise NotIntFloatError((x, y))
            if y < 0:
                raise NegativeDigitError(y)
            return x ** y
        except NotIntFloatError as e :
            return f'Error: {e}'
        except NegativeDigitError as e:
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

    def square_root(self, x):
        try:
            if not isinstance(x, (int, float)) :
                raise NotIntFloatError((x))
            if x < 0:
                raise NegativeDigitError(x)
            return round(x ** 0.5, 5)
        except NotIntFloatError as e :
            return f'Error: {e}'
        except NegativeDigitError as e:
            return f'Error: {e}'
        except Exception as e:
            return f'Error: {e}'

calc = Calculator()

print('Except add :' + calc.add('a', 3))
print('Normal add :' + str(calc.add(5, 3)))
print('Except sub :' + calc.subtract(10, [10,15])) # Не понимаю почему здесь выскакивает просто Exception но не NotIntFloatError когда прокидываю list
print('Normal sub :' + str(calc.subtract(10, 4)))
print('Except mul :' + calc.multiply(3, 'hello'))
print('Normal mul :' + str(calc.multiply(3, 0.1111)))
print('Except div :' + calc.divide(8, 0))
print('Except div :' + calc.divide(8, 'bbb'))
print('Normal div :' + str(calc.divide(10, 3)))
print('Except pow :' + calc.power(2, -3))
print('Except pow :' + calc.power(2, 'error'))
print('Normal pow :' + str(calc.power(2, 3)))
print('Except sqr :' + calc.square_root(-3))
print('Except sqr :' + calc.square_root((5,)))
print('Normal sqr :' + str(calc.square_root(8)))


from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Post, Comment
from .forms import CommentForm, ContactForm

# Create your views here.

def home(request):
    return render(request, 'home.html')

def about(request):
    return render(request, 'about.html')

def market_index(request):
    posts = Post.objects.all()
    return render(request, 'market/index.html', {
        'posts': posts
    })

def market_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    return render(request, 'market/detail.html', {
        'post': post, 'comment_form': CommentForm()
    })

def add_comment(request, post_id):
    form = CommentForm(request.POST)
    if form.is_valid():
        new_comment = form.save(commit=False)
        new_comment.post_id = post_id
        new_comment.save()
    return redirect('detail', post_id=post_id)

def add_contact(request, comment_id, post_id):
    form = ContactForm(request.POST)
    if form.is_valid():
        new_contact = form.save(commit=False)
        new_contact.comment_id = comment_id
        new_contact.save()
    return redirect('detail', post_id=post_id)

class PostCreate(CreateView):
    model = Post
    fields = ['item', 'picture', 'description', 'price', 'user']

class PostUpdate(UpdateView):
    model = Post
    fields = ['item', 'picture', 'description', 'price']

class PostDelete(DeleteView):
    model = Post
    success_url = '/market'


def oddHelper(s, k):
    """1 <= k <= n-2"""
    i = 1
    N = min(k, len(s) - 1 - k)
    while i <= N:
        if s[k - i] != s[k + i]:
            break
        else:
            i += 1
    return (1 + 2 * (i - 1), s[k - i + 1 : k + i])

def evenHelper(s, k):
    """1 <= i <= n-2"""
    if s[k] != s[k + 1]:
        return (0, '')
    i = 1
    N = min(k, len(s) - 2 - k)
    while i <= N:
        if s[k - i] != s[k + 1 + i]:
            break
        else:
            i += 1
    return (2 + 2 * (i - 1), s[k - i + 1 : k + i + 1])

def longestPalindrome(s):
    """
    :type s: str
    :rtype: str
    """
    if len(s) == 1:
        return s
    if len(s) == 2:
        if s[0] != s[1]:
            return s[1]
        else:
            return s
    if s[0] == s[1]:
        s_max = (2, s[0:2])
    else:
        s_max = (1, s[0])
    for k in range(1, len(s) - 1):
        tmp_odd = oddHelper(s, k)
        tmp_even = evenHelper(s, k)
        if s_max[0] <= tmp_odd[0]:
            s_max = tmp_odd
        if s_max[0] <= tmp_even[0]:
            s_max = tmp_even
    return s_max[1]


import ast
import networkx as nx
import numpy as np
from collections import defaultdict
import json
from tqdm import tqdm

# nodes = [0, 1, 2, 3, 4]
# graph = [[4, 3, 0.75], [4, 1, 0.81], [4, 2, 0.97], [4, 0, 0.52]]
# page_rank_probs = defaultdict(float)
# DG = nx.DiGraph()
# DG.add_nodes_from(nodes)
# DG.add_weighted_edges_from(graph)
# PAGE_RANK = nx.pagerank(DG, alpha=0.95)
# # for sub_graph in nx.weakly_connected_components(DG):
# #     sub_graph_size = len(sub_graph)
# #     PAGE_RANK = nx.pagerank(DG.subgraph(list(sub_graph)))
# #
# #     normalized_PAGERANK = {k: v * (sub_graph_size) / 5 for k, v in PAGE_RANK.items()}
# #     page_rank_probs.update(normalized_PAGERANK)
# #     # print ('normalized_PAGERANK', normalized_PAGERANK)
# #
# print(page_rank_probs)
# print(PAGE_RANK)
#
# # def find_ngrams(input_list, n):
# #     print ([input_list[i:] for i in range(n)])
# #     return zip(*[input_list[i:] for i in range(n)])
# #
# # # for ng in find_ngrams(['I', 'live', 'in', 'kingston'], 2):
# # #     print ('ng', ng)
# # print (range(5))
#
# # a = np.array([[1, 4, 2], [3, 5, 6]])
# # b = np.array([[1,1], [2,2], [3, 3], [4, 4], [5, 5], [6, 6]])
# # print (b[a[0]])
# a = np.array([1, 2, 4, 5, 56])
# print ( int(np.sum(a > 5)))

# def argsort(seq):
#     # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
#     return sorted(range(len(seq)), key=seq.__getitem__)

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp((x - np.max(x)) * 1)
    return e_x / e_x.sum()

def artificial_nli(cider_data, nli_data, nli_origin, thres):
    d = json.load(open(cider_data, 'r'))
    dn = json.load(open(nli_data, 'r'))
    do = json.load(open(nli_origin, 'r'))['prob_graph']
    prob_array = []
    cnt = 0
    for e in do.values():
        if cnt >= 500:
            break
        for ee in e:
            # print ('ee', ee, 'e', e)
            if ee[2] > 0.5:
                prob_array.append(ee[2])
                cnt += 1
    prob_array = np.array(prob_array)

    prob_edges = []
    node_nums = []
    has_edges = 0
    xxx = 0
    for e, en in tqdm(zip(d, dn)):
        tmp_edges = []
        num = len(en)
        new_e = softmax(np.array([ele[1] for ele in e[:num]]))
        # print (new_e)
        arg_new_e = np.argsort(new_e)
        low = 1.0 / len(en) * (thres)
        high = 1.0 / len(en) * (1.0 / thres)
        small_num = int(np.sum(new_e < low))
        # print ('small_num', small_num)
        large_num = int(np.sum(new_e > high))
        # print ('large_num', large_num)
        if small_num > 0:
            # print (np.random.choice(prob_array, size=(num - small_num,)))
            # print (np.random.rand(num - small_num,) * 0.1)
            sampl = np.random.choice(prob_array, size=(num - small_num,)) + (np.random.rand(num - small_num,) - 0.5) * 0.05
            sampl = np.sort(sampl)
            sampl = np.clip(sampl, 0.501, 0.999)
            # sampl = np.sort(np.random.uniform(low=0.5, high=1.0, size=(num - small_num,)))
            for i in range(num - small_num):
                tmp_edges.append([arg_new_e[small_num-1], arg_new_e[small_num + i], sampl[i]])

        if large_num > 0:
            sampl = np.random.choice(prob_array, size=(large_num,)) + (np.random.rand(large_num,) - 0.5) * 0.1
            sampl = np.sort(sampl)
            sampl = np.clip(sampl, 0.501, 0.999)
            for i in range(1, large_num+1):
                if num - i > small_num:
                    tmp_edges.append([arg_new_e[small_num], arg_new_e[-i], sampl[-i]])
                else:
                    break

        if small_num > 0 or large_num > 0:
            has_edges += 1

        ext_edges = []
        for i in range(len(tmp_edges)):
            cur = tmp_edges[i][1]
            for j in range(i+1, len(tmp_edges)):
                if cur == tmp_edges[j][0]:
                    sampl = np.random.choice(prob_array, size=(1)) + (np.random.rand(1)) * 0.1
                    ext_edges.append([tmp_edges[i][0], tmp_edges[j][1], sampl[0]])
                    xxx += 1
        tmp_edges.extend(ext_edges)

        prob_edges.append(tmp_edges)
        node_nums.append(num)
    print('xxx', xxx)
    json.dump({'edges': prob_edges, 'nodes': node_nums}, open('experiment/coco_nli_graph_pg1.json', 'w'))
    print ('has_edges', has_edges)

    return prob_edges

def minorchanges_nli(cider_data, nli_data, nli_origin, change=True):
    d = json.load(open(cider_data, 'r')) # test and val data excluded
    dn = json.load(open(nli_data, 'r'))
    do = json.load(open(nli_origin, 'r'))

    h_adj, l_adj, no_change, no_change_hi = 0, 0, 0, 0
    for idx, (e, en) in tqdm(enumerate(zip(d, dn))):
        num = len(en)
        new_e = softmax(np.array([ele[1] for ele in e[:num]]))
        # print (new_e)
        if np.array_equal(new_e, np.array([0.2, 0.2, 0.2, 0.2, 0.2])):
            # print ('skip')
            continue
        arg_new_e = np.argsort(new_e)
        lo, hi = arg_new_e[0], arg_new_e[-1]

        nli_e = np.array([ele[1] for ele in en])
        arg_nli_e = np.argsort(nli_e)
        nlo, nhi = arg_nli_e[0], arg_nli_e[-1]
        if lo == nlo and hi == nhi:
            no_change += 1
            continue
        if hi == nhi:
            no_change_hi += 1
        if change:
            current_prob = do['prob_graph'][str(idx)]
            current_edge = do['graph'][str(idx)]

            forward_ix_list, backward_ix_list = [], []
            for ix in range(len(current_prob)):
                if current_prob[ix][0] == lo:
                    forward_ix_list.append(ix)
                if current_prob[ix][0] == hi:
                    backward_ix_list.append(ix)

            assert len(forward_ix_list) > 0 and len(backward_ix_list) > 0, 'has to find the index'

            def samp(a, b):
                return np.random.uniform(low=a, high=b, size=1)[0]
            # sampl2 = np.random.uniform(low=0.01, high=0.05, size=1)[0]

            for f_ix in forward_ix_list:
                if current_prob[f_ix][2] < 0.5:
                    if current_prob[f_ix][1] == hi:
                        current_prob[f_ix][2] = samp(0.89, 0.99)
                        current_edge[f_ix][2] = 1.0
                        h_adj += 1
                    elif np.random.uniform() > 0.85:
                        current_prob[f_ix][2] = samp(0.51, 0.95)
                        current_edge[f_ix][2] = 1.0
                        h_adj += 1

            for b_ix in backward_ix_list:
                if current_prob[b_ix][2] > 0.5:
                    current_prob[b_ix][2] = samp(0.01, 0.05)
                    current_edge[b_ix][2] = 0.0
                    l_adj += 1

            do['prob_graph'][str(idx)] = current_prob
            do['graph'][str(idx)] = current_edge

    print('no need to change', no_change)
    print('h_adj', h_adj, 'l_adj', l_adj, 'nochangehi', no_change_hi)
    if change:
        json.dump(do, open('experiment/coco_nli_new.json', 'w'))

    return

def show_lo_and_high(cider_data, nli_data, data_json):
    d = json.load(open(cider_data, 'r'))  # test and val data excluded
    dn = json.load(open(nli_data, 'r'))
    da = json.load(open(data_json, 'r'))['images']
    cnt = 0
    for idx, (e, en, enn) in tqdm(enumerate(zip(d, dn, da))):
        num = len(en)
        new_e = softmax(np.array([ele[1] for ele in e[:num]]))
        if np.array_equal(new_e, np.array([0.2, 0.2, 0.2, 0.2, 0.2])):
            continue
        arg_new_e = np.argsort(new_e)
        lo, hi = arg_new_e[0], arg_new_e[-1]
        cnt += 1
        if cnt > 100:
            break
        print ("*"*20)
        print ('low:', enn['sentences'][lo]['raw'])
        print ('high', enn['sentences'][hi]['raw'])
        print ("*"*20)

    return

minorchanges_nli('data/prob_cand_inst_v3', 'data/nli_dist_rl', 'experiment/coco_nli_relation.json')
# show_lo_and_high('data/prob_cand_inst_v3', 'data/nli_weights_v2', 'data/dataset_karparthy.json')
# print (np.array([1.0/5]*5))


import numpy as np
import matplotlib.pyplot as plt

n = 6
maxI = 10000000
eps = 1e-6

def f(x):
    return (0.5*np.reshape(x, (1, n))).dot(A).dot(np.reshape(x, (n, 1))) + b.dot(x)

def grad(x):
    return np.reshape(A.dot(x), (1, n)) + b

def H(x):
    return A

def Hinv(x):
    return np.linalg.inv(A)

A = np.random.randn(n, n)*10

b = np.random.rand(n)

x = np.zeros((n,1))
x0 = x

i = 0

while np.linalg.norm(grad(x)) > eps:
    x = x - Hinv(x).dot(np.reshape(grad(x), (n, 1)))
    i += 1
    if (i >= maxI):
        print("Ошибка")
        break

print("Безусловный минимум методом Ньютона")
print(x)

r = np.random.rand(1, 1)
c = np.reshape((x - x0), (1, n)).dot(x - x0)

while c - r*r <= 0:
    r = np.random.rand(1, 1)

print("Число r")
print(r)
print("Проверим, что для безусловного минимума не выполнено условие (x - x0)*(x - x0) -r*r <= 0")
print("(x - x0)*(x - x0) -r*r = ", str(c - r*r))

M = A
col = [0. for i in range(0,n)]
col[0] = float(c)
col = np.array(col, dtype=np.float64)
M = np.column_stack((M, np.reshape(col, (n, 1))))
c1 = np.append(x-x0, 0)
M = np.vstack((M, c1))
B = np.append(-b, r*r)
Y = np.linalg.inv(M.astype('float')).dot(B)
x = Y[0:n]
print("Условный минимум")
print(x)
print("Проверка")
x = np.reshape(x, (n, 1))
print(np.reshape((x - x0), (1, n)).dot(x - x0) - r*r)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan  2 16:13:15 2019

@author: michal
"""

from IOtemp import readAuthors, readPublications
from MKAR_flow import MKAR_FlowTheory
from math import ceil
import networkx as nx

def checkN(workersList):
    N = 0
    for w in workersList:
        N += w.time

    return ceil(N/4.)*3
#
#workersList = readAuthors("data/pracownicy.xls")
workersList = readAuthors("data/adamczykGroup.xls")
publicationsList = readPublications("data/publikacje_update.xls", workersList)
postFix = "All"

N = checkN(workersList)
pm = MKAR_FlowTheory(workersList, publicationsList)
pm.preprocessing()
publicationsIds = pm.getAllPublicationsFromMainGraph()
data = pm.solveFlowProblem(publicationsIds, N, True)

maxPoinst = data["maxPoints"]
maxSlots = data["maxSlots"]
flowG = data["flowGraph"]
flowDict = data["flowDict"]

print("Maksymalna liczba punktow: ", maxPoinst)
print("Maksymalna liczba wykorzystanych slotów: ", maxSlots)

uniqueWeights = set()
for p in pm.publicationList:
    uniqueWeights.add(  p.size)

def writeSlotsUsageLog( pubMatch, flowDict , logName ):
    authorsIds = pubMatch.authorsDict.keys()

    log = open(logName, "w")
    log.write("Author\tSlots available\tSlots used\tSlots used[%]\tall publication no\n")

    for a in authorsIds:
        if a in flowDict:
            slotsUsed = flowDict[a]["t"]/100.
            pubNo = len(list(pubMatch.pubGraph.neighbors(a)))
        else:
            slotsUsed = 0
            pubNo = 0

        slotsAvailable = pm.authorsDict[a].slots/100.

        if slotsAvailable > 0:
            log.write(a+"\t"+str(slotsAvailable)+"\t"+str(slotsUsed)+"\t"+str(slotsUsed*100/slotsAvailable)+"\t"+str(pubNo)+"\n")

    log.close()

writeSlotsUsageLog( pm, flowDict, "slotsUsage"+postFix+".csv" )

def writeUnusedPublicationsLog(pubMatch, flowDict, logName):
    pubIds = pubMatch.publicationDict.keys()

    log = open(logName, "w")
    log.write("Tytul\tRok\tAutorzy\tPunkty\tSlots available\n")

    for p in pubIds:
        if p in flowDict:
            slotsUsed = 0
            for c in flowDict[p]:
                slotsUsed += flowDict[p][c]
        else:
            slotsUsed = 0

        pObj = pm.publicationDict[p]

        if slotsUsed == 0:
            authors = [ a.name for a in pObj.authors ]
            authors = ", ".join(authors)
            log.write(pObj.title.replace("\t", "") +"\t"+str(pObj.year)+"\t"+str(authors)+"\t"+str(pObj.points/100.)+"\t"+str(pObj.size/100.)+"\n")

    log.close()

writeUnusedPublicationsLog(pm, flowDict, "unusedPublications"+postFix+".csv")

def writeUsedPublicationsLog(pubMatch, flowDict, logName):
    pubIds = pubMatch.publicationDict.keys()

    log = open(logName, "w")
    log.write("Tytul\tRok\tAutorzy\tPunkty\tSlots\tFractional\n")

    for p in pubIds:
        authors = []
        if p in flowDict:
            slotsUsed = 0
            for c in flowDict[p]:
                slotsUsed += flowDict[p][c]
                if flowDict[p][c] > 0:
                    authors.append(c+ "("+str(flowDict[p][c])+")")
        else:
            slotsUsed = 0

        pObj = pm.publicationDict[p]

        if slotsUsed > 0:
            authorsNo = len(authors)
            fractional = False
            if authorsNo > 1 or slotsUsed < pObj.size:
                fractional = True

            authors = ", ".join(authors)
            log.write(pObj.title.replace("\t", "") +"\t"+str(pObj.year)+"\t"+str(authors)+"\t"+str(pObj.points/100.)+"\t"+str(pObj.size/100.)+"\t"+str(fractional)+"\n")

    log.close()

writeUsedPublicationsLog(pm, flowDict, "usedPublications"+postFix+".csv")
fractional = pm.extractFractionalGraph(flowDict)
pm.pubGraph = fractional
pm.printStatus()
#layout = nx.spring_layout(fractional)
#nx.draw_networkx(fractional, layout)


tabby_cat = "\tI'm tabbed in."
#The variable tabby_cat strores  the string with a tab\
persian_cat = "I'm split\non a line."
#The variable persian_cat stores the string and creates a new line within the text
backslash = "I'm\\a\\cat."
#The Varibale backslash stores the string and backslashes within

fat_cat = """"
I'will do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
#The variable fat_cat stores the string with tab\ and newline\ within the string
print(tabby_cat)
#Displays the value of the variable tabby_cat
print(persian_cat)
#Displays the value of the variable persian_cat
print(backslash)
#Displays the value of the variable backslash
print(fat_cat)
#Displays the value of the variable fat_cat


# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        resultEx = 0
        for obj in array:
            resultEx ^= obj
        indexof1 = self.findFirstBit1(resultEx)
        num1,num2 = 0,0
        for obj in array:
            if self.isIndex1(obj,indexof1):
                num1 ^= obj
            else:
                num2 ^= obj
        return num1, num2

    def findFirstBit1(self, num):
        indexBit = 0
        while not num & 1:
            num >>= 1
            indexBit += 1
        return indexBit

    def isIndex1(self, num,index):
        num >>= index
        return num & 1


import secrets

from eth_keys import (
    keys,
)
from eth_utils import (
    int_to_big_endian,
)

try:
    import factory
except ImportError:
    raise ImportError(
        "The p2p.tools.factories module requires the `factory_boy` library."
    )

def _mk_private_key_bytes() -> bytes:
    return int_to_big_endian(secrets.randbits(256)).rjust(32, b"\x00")

class PrivateKeyFactory(factory.Factory):
    class Meta:
        model = keys.PrivateKey

    private_key_bytes = factory.LazyFunction(_mk_private_key_bytes)

def _mk_public_key_bytes() -> bytes:
    return PrivateKeyFactory().public_key.to_bytes()

class PublicKeyFactory(factory.Factory):
    class Meta:
        model = keys.PublicKey

    public_key_bytes = factory.LazyFunction(_mk_public_key_bytes)


import numpy as np
import pandas as pd
import math
import requests, json, time
from datetime import datetime

class Processor:
	def __init__(self, history_length):
		self.history_length = history_length

	def fetchHistoricalDataForTicker(self, fsym, tsym, lim):
		df_cols = ['time', 'open', 'high', 'low', 'close', 'volumefrom', 'volumeto']
		curr_ts = str(int(time.time()))
		limit = str(lim)
		histURL = 'https://min-api.cryptocompare.com/data/histominute?fsym=' + fsym + '&tsym=' + tsym + '&limit=' + limit + '&toTs=' + curr_ts + '&aggregate=1' + '&e=Coinbase' #CCCAGG for aggregated
		resp = requests.get(histURL)
		resp_json = json.loads(resp.content.decode('utf-8'))
		df = pd.DataFrame(columns = df_cols)
		for i in range(0, lim):
			data = []
			for count, val in enumerate(df_cols):
				entry = resp_json['Data'][i][val]
				data.append(entry)
			row = pd.Series(data, df_cols)
			df = df.append(row, ignore_index = True)
		if(df.empty):
			return
		df = df.rename(index=str, columns={"time": "ts"})
		df.index = pd.to_datetime(df.ts, unit = 's')
		df = df.drop('ts', axis = 1)
		matrix_df = df.as_matrix()
		return matrix_df

	def fetchData(self):
		data = self.fetchHistoricalDataForTicker('ETH', 'USD', 2000)
		#Arbitrary 1500/500 split
		train_data = data[:1500, :]
		test_data = data[1501:, :]
		return {'train': train_data, 'test': test_data}


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

# In[ ]:

#Library Imports
from __future__ import print_function, division
from keras.models import Sequential, Model
from keras.layers.core import Dense
from keras.layers.recurrent import LSTM, GRU, SimpleRNN
from keras.layers import Input
from keras.utils.data_utils import get_file
from keras.optimizers import Nadam
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras.layers.normalization import BatchNormalization
from collections import Counter
import numpy as np
import random
import sys
import os
import getopt
import copy
import csv
import io
import time
import ipywidgets
import traitlets
from datetime import datetime
from math import log
import pandas as pd
from ATLSTM_layer import ATLSTM_layer

# In[ ]:

def load_data(eventlog, path, sep="|"):
    return pd.read_csv('../../../dataset/'+path+'/%s' % eventlog, sep=sep, error_bad_lines=False).values

# # In[ ]:

def get_divisor(timeseqs):
    return np.mean([item for sublist in timeseqs for item in sublist])

def create_model_folder(name, dirc):
    i = 1

    path_dir = "../../../results/output_files/models/"+dirc
    if os.path.isdir(path_dir) == False:
        try:
            os.mkdir(path_dir)
        except OSError:
            print ("Creation of the directory %s failed" % path_dir)
        else:
            print ("Successfully created the directory %s " % path_dir)

    for i in range(100):
        new_name = name + "_v" + str(i)
        path_name = path_dir + "/" + new_name
        if os.path.isdir(path_name) == False:
            try:
                os.mkdir(path_name)
            except OSError:
                continue
            else:
                print ("Successfully created the directory %s " % path_name)
                break

    return new_name
# In[ ]:

def main(argv = None):
    if argv is None:
        argv = sys.argv

    inputfile = ""
    directory = ""
    sep=""
    num_add_feats = 0

    try:
        opts, args = getopt.getopt(argv, "hi:d:n:")
    except getopt.GetoptError:
        print(os.path.basename(__file__),
              "-i <input_file> -d <directory> -s <separator> -n <num_add_feats>")
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(os.path.basename(__file__),
                  "-i <input_file> -d <directory> -s <separator> -n <num_add_feats>")
            sys.exit()
        elif opt == "-i":
            inputfile = arg
        elif opt == "-d":
            directory = arg
        elif opt == "-s":
            sep = arg
        elif opt == "-n":
            num_add_feats = int(arg)

    begin_time = datetime.now()

    #helper variables
    lines = [] #these are all the activity seq
#     timeseqs = [] #time sequences (differences between two events)
#     timeseqs2 = [] #time sequences (differences between the current and first)
    lastcase = ''
    line = ''
    firstLine = True
    lines = []
    timeseqs = []
    timeseqs2 = []
    timeseqs3 = []
    timeseqs4 = []
    add_feats = []
    times = []
    times2 = []
    times3 = []
    times4 = []
    add_feat = -1
    numlines = 0
    casestarttime = None
    lasteventtime = None

    ascii_offset = 161

    spamreader = load_data(inputfile, directory, sep)

    for row in spamreader:
        t = time.strptime(row[2], "%Y-%m-%d %H:%M:%S")
        if row[0]!=lastcase:
            casestarttime = t
            lasteventtime = t
            lastcase = row[0]
            if not firstLine:
                lines.append(line)
                timeseqs.append(times)
                timeseqs2.append(times2)
                timeseqs3.append(times3)
                timeseqs4.append(times4)
                add_feats.append(list(add_feat))
            line = ''
            times = []
            times2 = []
            times3 = []
            times4 = []
            add_feat = row[3:]
            # add_feat = int(row[3])
            numlines+=1
        line+=chr(int(row[1])+ascii_offset)
        timesincelastevent = datetime.fromtimestamp(time.mktime(t))-datetime.fromtimestamp(time.mktime(lasteventtime))
        timesincecasestart = datetime.fromtimestamp(time.mktime(t))-datetime.fromtimestamp(time.mktime(casestarttime))
        midnight = datetime.fromtimestamp(time.mktime(t)).replace(hour=0, minute=0, second=0, microsecond=0)
        timesincemidnight = datetime.fromtimestamp(time.mktime(t))-midnight
        timediff = 86400 * timesincelastevent.days + timesincelastevent.seconds
        timediff2 = 86400 * timesincecasestart.days + timesincecasestart.seconds
        timediff3 = timesincemidnight.seconds #this leaves only time even occured after midnight
        timediff4 = datetime.fromtimestamp(time.mktime(t)).weekday() #day of the week
        times.append(timediff)
        times2.append(timediff2)
        times3.append(timediff3)
        times4.append(timediff4)
        # add_feats.append(add_feat)
        lasteventtime = t
        firstLine = False

    lines.append(line)
    timeseqs.append(times)
    timeseqs2.append(times2)
    timeseqs3.append(times3)
    timeseqs4.append(times4)
    add_feats.append(add_feat)
    numlines+=1

    divisor = get_divisor(timeseqs) #average time between events
    print('divisor: {}'.format(divisor))
    divisor2 = get_divisor(timeseqs2) #average time between current and first events
    print('divisor2: {}'.format(divisor2))

    elems_per_fold = int(round(numlines/3))
    fold1 = lines[:elems_per_fold]
    fold1_t = timeseqs[:elems_per_fold]
    fold1_t2 = timeseqs2[:elems_per_fold]
    fold1_t3 = timeseqs3[:elems_per_fold]
    fold1_t4 = timeseqs4[:elems_per_fold]
    fold1_ft = add_feats[:elems_per_fold]
    with open('../../../results/output_files/folds/fold1.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row, timeseq in zip(fold1, fold1_t):
            spamwriter.writerow([s +'#{}'.format(t) for s, t in zip(row, timeseq)])

    fold2 = lines[elems_per_fold:2*elems_per_fold]
    fold2_t = timeseqs[elems_per_fold:2*elems_per_fold]
    fold2_t2 = timeseqs2[elems_per_fold:2*elems_per_fold]
    fold2_t3 = timeseqs3[elems_per_fold:2*elems_per_fold]
    fold2_t4 = timeseqs4[elems_per_fold:2*elems_per_fold]
    fold2_ft = add_feats[elems_per_fold:2*elems_per_fold]
    with open('../../../results/output_files/folds/fold2.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row, timeseq in zip(fold2, fold2_t):
            spamwriter.writerow([s +'#{}'.format(t) for s, t in zip(row, timeseq)])

    fold3 = lines[2*elems_per_fold:]
    fold3_t = timeseqs[2*elems_per_fold:]
    fold3_t2 = timeseqs2[2*elems_per_fold:]
    fold3_t3 = timeseqs3[2*elems_per_fold:]
    fold3_t4 = timeseqs4[2*elems_per_fold:]
    fold3_ft = add_feats[2*elems_per_fold:]
    with open('../../../results/output_files/folds/fold3.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row, timeseq in zip(fold3, fold3_t):
            spamwriter.writerow([s +'#{}'.format(t) for s, t in zip(row, timeseq)])

    lines = fold1 + fold2
    lines_t = fold1_t + fold2_t
    lines_t2 = fold1_t2 + fold2_t2
    lines_t3 = fold1_t3 + fold2_t3
    lines_t4 = fold1_t4 + fold2_t4
    lines_ft = fold1_ft + fold2_ft

    step = 1
    sentences = []
    softness = 0
    next_chars = []
    lines = list(map(lambda x: x+'!',lines)) #put delimiter symbol
    maxlen = max(list(map(lambda x: len(x),lines))) #find maximum line size

    # next lines here to get all possible characters for events and annotate them with numbers
    chars = list(map(lambda x: set(x),lines))
    chars = list(set().union(*chars))
    chars.sort()
    target_chars = copy.copy(chars)
    chars.remove('!')
    print('total chars: {}, target chars: {}'.format(len(chars), len(target_chars)))
    char_indices = dict((c, i) for i, c in enumerate(chars))
    indices_char = dict((i, c) for i, c in enumerate(chars))
    target_char_indices = dict((c, i) for i, c in enumerate(target_chars))
    target_indices_char = dict((i, c) for i, c in enumerate(target_chars))
    print(indices_char)

    sentences_t = []
    sentences_t2 = []
    sentences_t3 = []
    sentences_t4 = []
    sentences_ft = []
    next_chars_t = []
    next_chars_t2 = []
    next_chars_t3 = []
    next_chars_t4 = []
    next_chars_ft = []
    for line, line_t, line_t2, line_t3, line_t4, line_ft in zip(lines, lines_t, lines_t2, lines_t3, lines_t4, lines_ft):
        for i in range(0, len(line), step):
            if i==0:
                continue

            #we add iteratively, first symbol of the line, then two first, three...

            sentences.append(line[0: i])
            sentences_t.append(line_t[0:i])
            sentences_t2.append(line_t2[0:i])
            sentences_t3.append(line_t3[0:i])
            sentences_t4.append(line_t4[0:i])
            sentences_ft.append(line_ft)
            next_chars.append(line[i])
            if i==len(line)-1: # special case to deal time of end character
                next_chars_t.append(0)
                next_chars_t2.append(0)
                next_chars_t3.append(0)
                next_chars_t4.append(0)
            else:
                next_chars_t.append(line_t[i])
                next_chars_t2.append(line_t2[i])
                next_chars_t3.append(line_t3[i])
                next_chars_t4.append(line_t4[i])
            next_chars_ft.append(line_ft)
    print('nb sequences:', len(sentences))

    print('Vectorization...')
    num_features = len(chars)+5+num_add_feats+1
    print('num features: {}'.format(num_features))
    X = np.zeros((len(sentences), maxlen, num_features), dtype=np.float32)
    y_a = np.zeros((len(sentences), len(target_chars)), dtype=np.float32)
    y_t = np.zeros((len(sentences)), dtype=np.float32)
    for i, sentence in enumerate(sentences):
        leftpad = maxlen-len(sentence)
        next_t = next_chars_t[i]
        sentence_t = sentences_t[i]
        sentence_t2 = sentences_t2[i]
        sentence_t3 = sentences_t3[i]
        sentence_t4 = sentences_t4[i]
        # sentence_ft = sentences_ft[i][0]
        # sentence_ft2 = sentences_ft[i][1]
        # sentence_ft3 = sentences_ft[i][2]
        for t, char in enumerate(sentence):
            multiset_abstraction = Counter(sentence[:t+1])
            for c in chars:
                if c==char: #this will encode present events to the right places
                    X[i, t+leftpad, char_indices[c]] = 1
            X[i, t+leftpad, len(chars)] = t+1
            X[i, t+leftpad, len(chars)+1] = sentence_t[t]/divisor
            X[i, t+leftpad, len(chars)+2] = sentence_t2[t]/divisor2
            X[i, t+leftpad, len(chars)+3] = sentence_t3[t]/86400
            X[i, t+leftpad, len(chars)+4] = sentence_t4[t]/7
            # X[i, t+leftpad, len(chars)+5] = next_chars_t[t]
            if num_add_feats > 0:
                for f in range(num_add_feats):
                    X[i, t+leftpad, len(chars)+f+5] = sentences_ft[i][f]
            # X[i, t+leftpad, len(chars)+6] = sentence_ft
            # X[i, t+leftpad, len(chars)+7] = sentence_ft2
            # X[i, t+leftpad, len(chars)+8] = sentence_ft3
        for c in target_chars:
            if c==next_chars[i]:
                y_a[i, target_char_indices[c]] = 1-softness
            else:
                y_a[i, target_char_indices[c]] = softness/(len(target_chars)-1)
        y_t[i] = next_t/divisor
        np.set_printoptions(threshold=sys.maxsize)

    # build the model:
    print('Build model...')
    print(X.shape)

    main_input = Input(shape=(maxlen, num_features), name='main_input')
    # train a 2-layer LSTM with one shared layer
    l1 = ATLSTM_layer(128, return_sequences=True)(main_input) # the shared layer

    l2_1 = ATLSTM_layer(128, return_sequences=False)(l1)

    l2_2 = ATLSTM_layer(128, return_sequences=False)(l1)

    d1 = keras.layers.Dropout(.2)(l1)
    d2_1 = keras.layers.Dropout(.2)(l2_1)
    d2_2 = keras.layers.Dropout(.2)(l2_2)

    act_output = Dense(len(target_chars), activation='softmax', kernel_initializer='glorot_uniform', name='act_output')(d2_1)
    time_output = Dense(1, kernel_initializer='glorot_uniform', name='time_output')(d2_2)

    model = Model(inputs=[main_input], outputs=[act_output, time_output])

    model_folder = ""
    if num_add_feats == 0:
        model_folder = create_model_folder("model_nofeat",directory)
    else:
        model_folder = create_model_folder("model_"+num_add_feats+"_feat", directory)

    opt = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004, clipvalue=3)

    model.compile(loss={'act_output':'categorical_crossentropy', 'time_output':'mae'}, optimizer=opt)

    early_stopping = EarlyStopping(monitor='val_loss', patience=42)

    model_checkpoint = ModelCheckpoint("../../../results/output_files/models/"+directory+"/"+model_folder+'/model_{epoch:02d}-{val_loss:.2f}.h5',
                                   monitor='val_loss',
                                   verbose=0,
                                   save_best_only=True,
                                   save_weights_only=False,
                                   mode='auto')

    lr_reducer = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, verbose=0, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)

    model.fit({'main_input': X}, {'act_output':y_a, 'time_output':y_t},
          validation_split=0.2,
          verbose=2,
          callbacks=[early_stopping, model_checkpoint, lr_reducer],
          batch_size=maxlen,
          epochs=200
          )

    print(datetime.now() - begin_time)

if __name__ == "__main__":
    main(sys.argv[1:])


from timeit import default_timer as timer

target = 150

start = timer()
file = open('input.txt')

def permute(vals, target):
	if len(vals) <=1:
		if len(vals) == 1 and vals[0] == target:
			return [vals]
		return []
	else:
		ret = []
		vals = [] + vals
		while(len(vals) > 0):
			val = vals[0]
			vals.pop(0)
			if val > target:
				continue
			if val == target:
				ret.append([val])
				continue
			for perm in permute(vals, target - val):
				ret.append([val] + perm)
		return ret

containers = []
for line in file.readlines():
	containers.append(int(line.strip()))

containers.sort(reverse=True)

# matches = []
# for perm in permute(containers, target):
# 	print perm
# 	total = 0
# 	for container in perm:
# 		total += container
# 	if target == total:
# 		print perm
# 		matches.append(perm)

result = len(permute(containers, target))
print("Completed in %fms" % ((timer() - start) * 1000))
print("%d is the result" % result)