class Solution:
    # TLE
    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        n = len(envelopes)
        dp = [1]*n
        envelopes.sort(key = lambda k:(k[0],-k[1]) )
        for i in range(n):
            cur = envelopes[i]
            for j in range(i):
                tmp = envelopes[j]
                if tmp[0] < cur[0] and tmp[1] < cur[1]:
                    dp[i] = max(dp[i], dp[j]+1)
        return max(dp)

    # after ascend width and descend height, always compare height, replace when height <= dp[i]
    def maxEnvelopes_sort2way(self, envelopes: List[List[int]]) -> int:
        dp = []
        envelopes.sort(key = lambda k:(k[0],-k[1]) )
        for w,h in envelopes:
            i,N = 0,len(dp)
            while i < N:
                if h<=dp[i]:
                    break
                i+=1
            if i == N:
                dp.append(h)
            else:
                dp[i] = h
        return len(dp)

    def maxEnvelopes_bisect(self, envelopes: List[List[int]]) -> int:
        dp = []
        envelopes.sort(key = lambda k:(k[0],-k[1]) )
        for w,h in envelopes:
            i = bisect_left(dp,h)
            if i == len(dp):
                dp.append(h)
            else:
                dp[i] = h
        return len(dp)


#!/usr/bin/env python
import sys, os
import numpy as np
import synergia
import pytest

macroparticles=16
realparticles=4.0e10

nturns=1

mp = synergia.foundation.pconstants.mp

# prop_fixture is a propagator
@pytest.fixture
def prop_fixture():

    channel_madx = """
beam, particle=proton,energy=8.0+pmass;
rfc: rfcavity, l=0.0, volt=1.0, harmon=84;
channel: sequence, l=3200.0, refer=entry;
rfc, at=3200.0;
endsequence;
"""
    reader = synergia.lattice.MadX_reader()
    reader.parse(channel_madx)
    lattice = reader.get_lattice('channel')
    lattice.set_all_string_attribute('extractor_type', 'libff')
    synergia.simulation.Lattice_simulator.tune_linear_lattice(lattice)
    stepper = synergia.simulation.Independent_stepper_elements(1)
    propagator = synergia.simulation.Propagator(lattice, stepper)

    return propagator

# two trains start out with the same reference particle and design reference momentum
# because they are propagating in the
# the same accelerator, but the secondary bunch will have it bunch energy increase
# by 100 MeV to mimic slip stacking. The bunches propagate in the same pipe but one
# secondary moves faster than the primary so its cdt will go negative compared to
# primary.
def create_simulator(ref_part_pri, ref_part_sec):
    sim = synergia.simulation.Bunch_simulator.create_two_trains_simulator(ref_part_pri, ref_part_sec, macroparticles, realparticles)
    bunch_pri = sim.get_bunch(0, 0)
    bunch_pri.checkout_particles()
    lp = bunch_pri.get_particles_numpy()
    lp[:, 0:6] = 0.0
    bunch_pri.checkin_particles()

    design_energy = ref_part_pri.get_total_energy()
    bunch_sec = sim.get_bunch(1, 0)
    bunch_sec.get_reference_particle().set_total_energy(design_energy + 0.100)
    bunch_sec.checkout_particles()
    lp = bunch_sec.get_particles_numpy()
    lp[:, 0:6] = 0.0
    bunch_sec.checkin_particles()

    return sim

def test_co_propagate(prop_fixture):

    #print('lattice: ')
    #print(prop_fixture.get_lattice())

    refpart = prop_fixture.get_lattice().get_reference_particle()

    sim = create_simulator(refpart, refpart)

    simlog = synergia.utils.parallel_utils.Logger(0, synergia.utils.parallel_utils.LoggerV.INFO_TURN, False)
    prop_fixture.propagate(sim, simlog, nturns)

    bunch_pri = sim.get_bunch(0, 0)
    bunch_sec = sim.get_bunch(1, 0)

    # primary bunch should be locked to the main energy so its cdt will be 0
    # the secondary bunch will slip compared to primary so its particle's cdt
    # will be negative.

    lattice = prop_fixture.get_lattice()
    L = lattice.get_length()

    beta_pri = bunch_pri.get_reference_particle().get_beta()
    beta_sec = bunch_sec.get_reference_particle().get_beta()

    print('beta_pri: ', beta_pri)
    print('beta_sec: ', beta_sec)

    bunch_pri.checkout_particles()
    lp_pri = bunch_pri.get_particles_numpy()
    bunch_sec.checkout_particles()
    lp_sec = bunch_sec.get_particles_numpy()

    assert lp_pri[0, 4] == pytest.approx(0.0)
    tdiff = L * (1/beta_sec - 1/beta_pri)
    print('tdiff: ', tdiff)

    assert lp_sec[0, 4] == pytest.approx(tdiff)

    print('lp_pri[0, 4]: ', lp_pri[0, 4])
    print('lp_sec[0, 4]: ', lp_sec[0, 4])

def main():
    pf = prop_fixture()
    test_accel1(pf)

if __name__ == "__main__":
    main()


from flask import Flask, request, render_template
import pymongo
import pandas as pd

from atlas_mongo.Mongo import ConectColl
import atlas_mongo.folium_maps as fmaps
import atlas_mongo.external_api as exa
import machine.prepare_data as mppd
import machine.sandro_rey as sandro

app = Flask(__name__)

@app.route('/hello')
def hello():
    return 'Hi Ovi!'

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/home')
def home_two():
    return render_template('home.html')

@app.route('/create', methods=['POST'])
def create():
    fecha = request.form.get('fecha')
    year = int(request.form.get('year'))
    horario = request.form.get('horario')
    festividad = request.form.get('festividad')
    tipo_accidente = request.form.get('tipo_accidente')
    lesividad = request.form.get('lesividad')
    meteo = request.form.get('meteo')
    distrito = request.form.get('distrito')
    direccion = request.form.get('direccion')
    lon = round(float(request.form.get('lon')), 6)
    lat = round(float(request.form.get('lat')), 6)
    coll.create(fecha, year, horario, festividad, tipo_accidente,
                lesividad, meteo, distrito, direccion, lon, lat)
    coll.acc.create_index([('localizacion', pymongo.GEOSPHERE)])
    return 'Doc Inserted'

# ----
@app.route('/create/pred', methods=['POST'])
def create_pred():
    lon = round(float(request.form.get('lon')), 6)
    lat = round(float(request.form.get('lat')), 6)
    weight = round(float(request.form.get('weights')), 1)
    coll.create_pred(lon, lat, weight)
    coll.pred.create_index([('localizacion', pymongo.GEOSPHERE)])
    return 'Pred Inserted'
# -----

@app.route('/historical/direction', methods=['GET'])
def insert_dir():
    return render_template('historical.html')

@app.route('/historical/direction', methods=['POST'])
def get_coord_dir():
    pto_a = request.form.get('pto_a')
    pto_b = request.form.get('pto_b')
    lat_a, lon_a = exa.get_coord_dir(pto_a)
    lat_b, lon_b = exa.get_coord_dir(pto_b)
    folium_map = fmaps.print_heat_map_dir(coll, lat_a, lon_a, lat_b, lon_b)
    return folium_map._repr_html_()

# Predicciones y buenas noches

@app.route('/prediction/direction', methods=['GET'])
def insert_dir_pred():
    weather, day = exa.get_weather_day()
    fest = mppd.get_fest(day)
    return render_template('prediction.html', vble_w=weather, vble_d=day, vble_f=fest)

@app.route('/prediction/direction', methods=['POST'])
def get_coord_dir_pred():
    pto_a = request.form.get('pto_a')
    pto_b = request.form.get('pto_b')
    horario_cat = request.form.get('horario')

    lat_a, lon_a = exa.get_coord_dir(pto_a)
    lat_b, lon_b = exa.get_coord_dir(pto_b)
    weather, day = exa.get_weather_day()

    data = mppd.prepare_to_predict(
        horario_cat, day, lon_a, lat_a, lon_b, lat_b, weather)
    # data.to_csv('output/X_to_pred.csv', index=False)
    data_to_map = sandro.pred_y_buenas_noches(data)

    folium_map = fmaps.print_heat_map_pred(
        data_to_map, lat_a, lon_a, lat_b, lon_b)
    return folium_map._repr_html_()

if __name__ == '__main__':
    coll = ConectColl()
    app.run(debug=True)


#Read data from the file (FASTA formatted file)
def readFile(filePath):
    """Reading a file and returning a list of lines"""
    with open(filePath, 'r') as f:
        return [l.strip() for l in f.readlines()]
def gc_content(seq):
    """GC Content in a DNA/RNA sequence"""
    return round(((seq.count('C') + seq.count('G'))/len(seq) * 100), 6)

FASTAFile = readFile("")
FASTADict = {}
FASTALabel = ""

for line in FASTAFile:
    if '>' in line:
        FASTALabel = line
        FASTADict[FASTALabel] = ""
    else:
        FASTADict[FASTALabel] += line

print(FASTADict)

RESULTDict = {key: gc_content(value) for (key, value) in FASTADict.items()}

print(RESULTDict)

MaxGCKey = max(RESULTDict, key=RESULTDict.get)

print(f'{MaxGCKey}\n{RESULTDict[MaxGCKey]}')


import cPickle
import networkx as nx

def make_tree(sequences):

	G = nx.Graph()

	for sequence in sequences:
		for i in xrange(len(sequence)-1):
			G.add_edge(code_2_index[sequence[i]], code_2_index[sequence[i+1]])

	return G

mesh_to_seq = cPickle.load(open('mesh_to_seq.pkl','r'))
sequences = mesh_to_seq.values()
sequences = [['SSOS','SOS']+sequence.split(".")+['EOS'] for sequence in sequences]

code_2_index = cPickle.load(open('code_2_index.pkl', 'r'))
G = make_tree(sequences)
nx.write_adjlist(G, './mesh_codes_tree.adj')


from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import warnings
import re
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import numpy as np

maxlen=100
distanceListnum=199
vec_size=50

PositionListPath=".\\Train2013\\PositionList.txt"  #train+test
AllPositionListPath=".\\Train2013\\AllPositionList.txt"
AllPositionMatricxPath=".\\Train2013\\AllPositionMatricx.txt"

traindatapath="Train2013/"
trainIstanceResultpath=".\\Train2013\\trainIstanceResult.txt"
ProcessedtrainIstanceResultpath=".\\Train2013\\ProcessedtrainIstanceResult.txt"
trainIstancepath=".\\Train2013\\trainIstance.txt"
ProcessedtrainIstancepath=".\\Train2013\\ProcessedtestIstance.txt"
trainIstanceDrugpath=".\\Train2013\\trainCsentence_token.txt"
trainIstanceDrugPosition1path=".\\Train2013\\trainIstanceDrugPosition1.txt"
trainIstanceDrugPosition1Processed=".\\Train2013\\ProcessedtrainIstanceDrugPosition1.txt"
trainIstanceDrugPosition2path=".\\Train2013\\trainIstanceDrugPosition2.txt"
trainIstanceDrugPosition2Processed=".\\Train2013\\ProcessedtrainIstanceDrugPosition2.txt"

testIstancepath=".\\Test2013\\testIstance.txt"
testIstanceDrugPosition1path=".\\Test2013\\testIstanceDrugPosition1.txt"
testIstanceDrugPosition1Processed=".\\Test2013\\ProcessedtestIstanceDrugPosition1.txt"
testIstanceDrugPosition2path=".\\Test2013\\testIstanceDrugPosition2.txt"
testIstanceDrugPosition2Processed=".\\Test2013\\ProcessedtestIstanceDrugPosition2.txt"
ProcessedtestIstancepath=".\\Test2013\\ProcessedtestIstance.txt"

deepProcessedtestIstancepath=".\\Test2013\\ProcessedtestIstance.txt"
testIstanceResultpath=".\\Test2013\\testIstanceResult.txt"
ProcessedtestIstanceResultpath=".\\Test2013\\ProcessedtestIstanceResult.txt"
testIstanceDrugpath=".\\Test2013\\testCsentence_token.txt"

testIstanceDrugPositionweighted=".\\Test2013\\testPosition1weighted.txt"
testIstanceDrugPositionweightedProcessed=".\\Test2013\\ProcessedtestPositionweighted.txt"

trainIstanceDrugPositionweighted=".\\Train2013\\trainPosition1weighted.txt"
trainIstanceDrugPositionweightedProcessed=".\\Train2013\\ProcessedtrainPositionweighted.txt"

def preprocess(fp,fw):
    with open(fp, 'rt', encoding='utf-8') as txtFile:
        with open(fw, 'wt', encoding='utf-8') as writeFile:
            for line in txtFile:
                index1=line.find("[")
                if index1!=-1:
                    line=line.replace("[","")
                index2=line.find("'")
                if index2!=-1:
                    line=line.replace("'","")
                index3=line.find("]")
                if index3!=-1:
                    line=line.replace("]","")
                index4 = line.find(",")
                if index4 != -1:
                    line = line.replace(",", " ")
                index5 = line.find("$")
                if index5 != -1:
                    line = line.replace("$", " ")
                index6 = line.find(":")
                if index6 != -1:
                    line = line.replace(":", " ")
                index7 = line.find("\"\"")
                if index7 != -1:
                    line = line.replace("\"\"", " ")
                index9 = line.find("``")
                if index9 != -1:
                    line = line.replace("``", " ")
                for i in range(5):
                    while (line.find("  ") != -1):
                        index8 = line.find("  ")
                        sline = line[index8:index8 + 2]
                        line = line.replace(sline, " ")
                writeFile.write(line)
        writeFile.close()
    txtFile.close()

def find_max_sentence(fp):
    with open(fp, 'rt', encoding='utf-8') as txtFile:
        maxsentence = 0
        maxtxt = str(0)
        j=0
        i=0
        count=0
        for line in txtFile:

            index1=line.find("drug1")
            index2=line.find("drug2")
            if index1==-1 or index2==-1:
                print(i)
                print(line)
                count=count+1
            lines = line.split(" ")

            j=len(lines)
            if maxsentence < j:
                maxsentence = j
                maxtxt = line

            i=i+1
        print("最大句子长度为：", maxsentence)
        print("最大句子为：", maxtxt)
        print(count)
    txtFile.close()

def getsubposition(fp,f1,f2,f3,f4,f5,f6):
    with open(fp, 'rt', encoding='utf-8') as txtFile:
        with open(f1, 'wt', encoding='utf-8') as File1:
            with open(f2, 'wt', encoding='utf-8') as File2:
                with open(f3, 'wt', encoding='utf-8') as File3:
                    with open(f4, 'wt', encoding='utf-8') as File4:
                        with open(f5, 'wt', encoding='utf-8') as File5:
                            with open(f6, 'wt', encoding='utf-8') as File6:
                                for line in txtFile:
                                    PositionToDrug1Listsub1 = []
                                    PositionToDrug1Listsub2 = []
                                    PositionToDrug1Listsub3 = []
                                    PositionToDrug2Listsub1 = []
                                    PositionToDrug2Listsub2 = []
                                    PositionToDrug2Listsub3 = []
                                    line = line.replace("\n", "")
                                    line = line.strip()
                                    lines = line.split(" ")
                                    i = 0
                                    for e in lines:
                                        i = i + 1
                                        if e == "drug1":
                                            key1 = i
                                        if e == "drug2":
                                            key2 = i
                                    j = 0
                                    for e in lines:
                                        j = j + 1
                                        distance1 = j - key1
                                        if distance1 == 0:
                                            distance1 = 100
                                        distance2 = j - key2
                                        if distance2 == 0:
                                            distance2 = 100

                                        if j < key1:
                                            PositionToDrug1Listsub1.append(distance1)
                                        if j >= key1 and j <= key2 :
                                            PositionToDrug1Listsub2.append(distance1)
                                        if j > key2:
                                            PositionToDrug1Listsub3.append(distance1)

                                        if j < key1:
                                            PositionToDrug2Listsub1.append(distance2)
                                        if j >= key1 and j <= key2 :
                                            PositionToDrug2Listsub2.append(distance2)
                                        if j > key2:
                                            PositionToDrug2Listsub3.append(distance2)

                                    File1.write(str(PositionToDrug1Listsub1))
                                    File1.write("\n")
                                    File2.write(str(PositionToDrug1Listsub2))
                                    File2.write("\n")
                                    File3.write(str(PositionToDrug1Listsub3))
                                    File3.write("\n")
                                    File4.write(str(PositionToDrug2Listsub1))
                                    File4.write("\n")
                                    File5.write(str(PositionToDrug2Listsub2))
                                    File5.write("\n")
                                    File6.write(str(PositionToDrug2Listsub3))
                                    File6.write("\n")
                            File6.close()
                        File5.close()
                    File4.close()
                File3.close()
            File2.close()
        File1.close()
    txtFile.close()

def getPosition(fp,f1,f2):
    with open(fp, 'rt', encoding='utf-8') as txtFile:
        with open(f1, 'wt', encoding='utf-8') as writeFile1:
            with open(f2, 'wt', encoding='utf-8') as writeFile2:

                for line in txtFile:
                    PositionToDrug1List = []
                    PositionToDrug2List = []
                    line=line.replace("\n","")
                    line=line.strip()
                    lines = line.split(" ")
                    i=0
                    for e in lines:
                        i=i+1
                        if e == "drug1":
                            key1 = i
                        if e == "drug2" :
                            key2 = i
                    j=0
                    for e in lines:
                        j=j+1
                        distance1 = j - key1
                        if distance1==0:
                            distance1=100
                        distance2 = j - key2
                        if distance2==0:
                            distance2=100
                        PositionToDrug1List.append(distance1)
                        PositionToDrug2List.append(distance2)

                    writeFile1.write(str(PositionToDrug1List))
                    writeFile1.write("\n")
                    writeFile2.write(str(PositionToDrug2List))
                    writeFile2.write("\n")
            writeFile2.close()
        writeFile1.close()
    txtFile.close()

def getPositionWeighted(fp,f1):
    with open(fp, 'rt', encoding='utf-8') as txtFile:
        with open(f1, 'wt', encoding='utf-8') as writeFile1:

                for line in txtFile:
                    Weight = []
                    line=line.replace("\n","")
                    line=line.strip()
                    lines = line.split(" ")
                    i=0
                    for e in lines:
                        i=i+1
                        if e == "drug1":
                            key1 = i
                        if e == "drug2" :
                            key2 = i
                    j=0
                    for e in lines:
                        j=j+1
                        distance1 = abs(j - key1)
                        distance2 = abs(j - key2)
                        distance = min(distance1, distance2)
                        w = 1 - (distance / i)
                        w = round(w,5)
                        Weight.append(w)
                    writeFile1.write(str(Weight))
                    writeFile1.write("\n")

        writeFile1.close()
    txtFile.close()

def getPositionRange(f1,f2,f3,f4,fc):
    with open(f1, 'rt', encoding='utf-8') as txtFile1:
        with open(f2, 'rt', encoding='utf-8') as txtFile2:
            with open(f3, 'rt', encoding='utf-8') as txtFile3:
                with open(f4, 'rt', encoding='utf-8') as txtFile4:
                    with open(fc, 'wt', encoding='utf-8') as writeFile1:
                        distanceList = []
                        count = 0
                        for line in txtFile1:
                            lines = line.split(",")
                            for d in lines:
                                d=d.strip(" ")
                                d=d.strip("\n")
                                if d not in distanceList:
                                    count=count+1
                                    distanceList.append(d)
                        for line in txtFile2:
                            lines = line.split(",")
                            for d in lines:
                                d=d.strip(" ")
                                d = d.strip("\n")
                                if d not in distanceList:
                                    count=count+1
                                    distanceList.append(d)
                        for line in txtFile3:
                            lines = line.split(",")
                            for d in lines:
                                d=d.strip(" ")
                                d = d.strip("\n")
                                if d not in distanceList:
                                    count=count+1
                                    distanceList.append(d)
                        for line in txtFile4:
                            lines = line.split(",")
                            for d in lines:
                                d = d.strip(" ")
                                d = d.strip("\n")
                                if d not in distanceList:
                                    count=count+1
                                    distanceList.append(d)
                        for p in distanceList:
                            writeFile1.write("{}\n".format(p))
                        print("count:", count)
                    writeFile1.close()
                txtFile4.close()
            txtFile3.close()
        txtFile2.close()
    txtFile1.close()

def delete0(f1):
    with open(f1, 'rt', encoding='utf-8') as txtFile1:
        with open(f1, 'wt', encoding='utf-8') as writeFile:
            distance=[]
            for line in txtFile1:
                lines = line.split(",")
                for d in lines:
                    if d=="0":
                        d="100"
                    distance.append(d)
                writeFile(str(distance))
                writeFile.write("\n")
        writeFile.close()
    txtFile1.close()

def creativePositionList(fc):
    distanceList=[]
    with open(fc, 'wt', encoding='utf-8') as writeFile1:
        for i in range(-99,101):
            distanceList.append(i)
        for p in distanceList:
            writeFile1.write("{}\n".format(p))
    writeFile1.close()

def get_Position_matrix(fm,vec_size, distanceListnum):
    length = distanceListnum
    distanceListnum_matrix = np.random.rand(length, vec_size)
    wf = open(fm, 'w', encoding='utf-8')
    for i in range(len(distanceListnum_matrix)):
        for j in range(len(distanceListnum_matrix[i])):
            wf.write(str(distanceListnum_matrix[i][j]) + " ")
        wf.write("\n")
    wf.close()

def getposlist(f1,f2,f3):
    posList = []
    with open(f1, 'rt', encoding='utf-8') as File1:
        for line in File1:
            line=line.strip("\n")
            lines=line.split(" ")
            for word in lines:
                if word not in posList:
                    posList.append(word)
    File1.close()
    with open(f2, 'rt', encoding='utf-8') as File2:
        for line in File2:
            line = line.strip("\n")
            lines=line.split(" ")
            for word in lines:
                if word not in posList:
                    posList.append(word)
    print(len(posList))
    File2.close()
    with open(f3, 'wt', encoding='utf-8') as File3:
        for line in posList:
            File3.write(line)
            File3.write("\n")
    File3.close()

def makeinstance(f1,f2,f3):
    entity1=[]
    entity2=[]
    sent=[]
    with open(f1, 'rt', encoding='utf-8') as file1:
        for line in file1:
            lines=line.split(",")
            entity1.append(lines[0])
            entity2.append(lines[1])
    file1.close()
    with open(f2, 'rt', encoding='utf-8') as file2:
        for line in file2:
            sent.append(line)
    file2.close()
    instance=[]
    for i in range(len(sent)):
        inst=entity1[i]+"$"+entity2[i]+"$"+sent[i]
        instance.append(inst)
    with open(f3, 'wt', encoding='utf-8') as file3:
        for line in instance:
            file3.write(line)

    file3.close()

def makeresultandinstance(f1,f2,f3):
    instance=[]
    result=[]
    with open(f1, 'rt', encoding='utf-8') as txtFile1:
        for line in txtFile1:
            instance.append(line)
    txtFile1.close()
    with open(f2, 'rt', encoding='utf-8') as txtFile2:
        for line in txtFile2:
            line=line.strip("\n")
            result.append(line)
    txtFile2.close()
    example=[]
    for i in range(len(instance)):
        eg=result[i]+"$"+instance[i]
        example.append(eg)
    with open(f3, 'wt', encoding='utf-8') as file3:
        for line in example:
            file3.write(line)
    file3.close()

def changeSpelling(f1,f2):
    lines=[]
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            line=line.lower()
            lines.append(line)
    data_in.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in lines:
            file2.write(line)
    file2.close()

def replaceNumber(f1,f2):

    writeline=[]
    with open(f1, 'rt', encoding='utf-8') as data_in:
        with open(f2, 'wt', encoding='utf-8') as file2:
            for line in data_in:
                line=line.split("$")
                result=line[0].strip(" ")
                entity1=line[1].strip(" ")
                entity2=line[2].strip(" ")
                sent=line[3]
                sentence=sent.split(" ")
                for i in range(len(sentence)):
                    word=sentence[i]
                    if word!=entity1 and word!=entity2 :
                        word1=word.strip("%()*+-<=>@[\]^_`{|}~ ")
                        if word1.isdigit():
                            sent=sent.replace(word,"number")
                writel=result+"$"+entity1+"$"+entity2+"$"+sent
                file2.write(writel)
        file2.close()
    data_in.close()

def deletepair(f1,f2):
    instance = []
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            lines = line.split("$")
            ent1 = lines[2].strip((" "))
            ent2 = lines[3].strip((" "))
            if ent1 != ent2:
                instance.append(line)
    data_in.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in instance:
            file2.write(line)
    file2.close()

def deletepairfinal(f1,f2):
    instance = []
    count = 0
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            lines = line.split("$")
            ent1 = lines[2].strip((" "))
            ent2 = lines[3].strip((" "))
            sentence = lines[4]
            result = lines[1]
            # "drug1 , drug2"  ("drug2 , drug1"dont exist)
            if "drug1 , drug2" in sentence :
                if result!="none":
                    print("have wrong instance in drug1,drug2:",result)
                else:
                    count=count+1
            else :
                instance.append(line)

            # "drug1 ( drug2 )"
            # if "drug1 ( drug2 )" in sentence:
            #     if result!="none":
            #         print("have wrong instance in drug1,drug2:",result)
            #     else:
            #         count=count+endsematten+newwordvector
            # else :
            #     instance.append(line)

            # "drug1 , drug2 , and drug0" "drug1 , drug0 , and drug2"  "drug0 , drug1 , and drug2"
            # if "drug1 , drug2 , and drug0" in sentence or "drug1 , drug0 , and drug2" in sentence or "drug0 , drug1 , and drug2" in sentence:
            #     if result != "none":
            #         print("have wrong instance in drug1,drug2:", result)
            #     else:
            #         count = count + endsematten+newwordvector
            # else:
            #     instance.append(line)

            # "drug1 such as drug2"
            # if "drug1 such as drug2" in sentence :
            #     if result != "none":
            #         print("have wrong instance in drug1,drug2:", result)
            #     else:
            #         count = count + endsematten+newwordvector
            # else:
            #     instance.append(line)

            # if "drug1 such as drug0 or drug2" in sentence :
            #     if result != "none":
            #         print("have wrong instance in drug1 such as drug0 or drug2:", result)
            #     else:
            #         count = count + endsematten+newwordvector
            # else:
            #     instance.append(line)

            # sentence=sentence.strip(" ")
            # index1 = sentence.find("drug1 :")
            # index2 = sentence.find("drug2 :")
            # if index1 == 0 or index2 == 0:
            #     if result!="none":
            #         print("have wrong instance in drug1,drug2:",result)
            #     else:
            #         count=count+endsematten+newwordvector
            # else :
            #     instance.append(line)
    print("count:",count)
    data_in.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in instance:
            file2.write(line)
    file2.close()
def loadsentence(f1,f2):
    instance = []
    result=[]
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            lines = line.split("$")
            # result.append(lines[0])
            sentence=lines[3]
            instance.append(sentence)
    data_in.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in instance:
            file2.write(line)

    file2.close()

def cleanfuhao(f1,f2):
    sentence=[]
    r ="drug0"
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            line = line.replace(r," ")
            for i in range(4):
                while (line.find("  ") != -1):
                    index8 = line.find("  ")
                    sline = line[index8:index8 + 2]
                    line = line.replace(sline, " ")
            sentence.append(line)
    data_in.close()

    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in sentence:
            file2.write(line)
    file2.close()
    # sentence = []
    # r = '[’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]+'
    # with open(f1, 'rt', encoding='utf-8') as data_in:
    #     for line in data_in:
    #         line = re.sub(r, '', line)
    #         for i in range(4):
    #             while (line.find("  ") != -endsematten+newwordvector):
    #                 index8 = line.find("  ")
    #                 sline = line[index8:index8 + 2]
    #                 line = line.replace(sline, " ")
    #         sentence.append(line)
    # data_in.close()
    #
    # with open(f2, 'wt', encoding='utf-8') as file2:
    #     for line in sentence:
    #         file2.write(line)
    # file2.close()

def makefile(f1,f2):
    sentence = []
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            sentence.append(line)
    data_in.close()
    with open(f2, 'a', encoding='utf-8') as file2:
        for line in sentence:
            file2.write(line)
            file2.write("\n")
    file2.close()

def deletedrug0(f1,f2):
    sentence = []
    sentences=[]
    with open(f1, 'rt', encoding='utf-8') as data_in:
        for line in data_in:
            line=line.replace("drug0","")
            sentence.append(line)
    data_in.close()

    r = '[’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]+'
    for line in sentence:
        line = re.sub(r, '', line)
        for i in range(6):
            while (line.find("  ") != -1):
                index8 = line.find("  ")
                sline = line[index8:index8 + 2]
                line = line.replace(sline, " ")
        sentences.append(line)

    data_in.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for line in sentences:
            file2.write(line)
            file2.write("\n")
    file2.close()

def getsubsection(f1,f2,f3,f4):
    subsentence1=[]
    subsentence2=[]
    subsentence3=[]
    with open(f1, 'rt', encoding='utf-8') as file1:
        for line in file1:
            index1=line.find("drug1")
            index2=line.find("drug2")
            line1=line[0:index1]
            line2=line[index1:index2+6]
            line3=line[index2+6:]
            line1=line1.strip(" ")
            line1=line1.strip("\n")
            line2 = line2.strip(" ")
            line2 = line2.strip("\n")
            line3 = line3.strip(" ")
            line3 = line3.strip("\n")
            subsentence1.append(line1)
            subsentence2.append(line2)
            subsentence3.append(line3)
    file1.close()
    with open(f2, 'wt', encoding='utf-8') as file2:
        for i in subsentence1:
            file2.write(i)
            file2.write("\n")
    file2.close()
    with open(f3, 'wt', encoding='utf-8') as file3:
        for i in subsentence2:
            file3.write(i)
            file3.write("\n")
    file3.close()
    with open(f4, 'wt', encoding='utf-8') as file4:
        for i in subsentence3:
            file4.write(i)
            file4.write("\n")
    file4.close()

def model_weigted():
    i=0
    F=0.737
    model_weighted_attention_dot=[]
    model_weighted_attention=[]
    model_weighted_attention_dense=[]
    model_weighted_sen_sdp_matric=[]

    model_weight_filepath = open(".\\modelweight\\" + str(F) + "model_weighted_attention_dot" + ".txt", "r")
    for line in model_weight_filepath:
        model_weighted_attention_dot.append(line.strip("\n"))
    model_weight_filepath.close()
    model_weight_filepath = open(".\\modelweight\\" + str(F) + "model_weighted_attention" + ".txt", "r")
    for line in model_weight_filepath:
        model_weighted_attention.append(line.strip("\n"))
    model_weight_filepath.close()
    model_weight_filepath = open(".\\modelweight\\" + str(F) + "model_weighted_attention_dense" + ".txt", "r")
    for line in model_weight_filepath:
        model_weighted_attention_dense.append(line.strip("\n"))
    model_weight_filepath.close()
    model_weight_filepath = open(".\\modelweight\\" + str(F) + "model_weighted_sen_sdp_matric" + ".txt", "r")
    model_weighted_sen_sdp_matric.append(line.strip("\n"))
    model_weight_filepath.close()

    model_weighted_attention_dot=str(model_weighted_attention_dot)
    model_weighted_attention_dot=model_weighted_attention_dot.split("]")
    print(model_weighted_attention_dot[0])

    print(model_weighted_attention_dot[473])
    print(model_weighted_attention_dot[474])
    print(model_weighted_attention_dot[475])
    print(model_weighted_attention_dot[-1])

def main():
    model_weigted()
    # preprocess(".\\Train2013\\analysis\\trainSentence_text.txt",".\\Train2013\\analysis\\processedtrainSentence_text.txt")
    # preprocess(".\\Test2013\\analysis\\testSentence_text.txt", ".\\Test2013\\analysis\\processedtestSentence_text.txt")
    # makeinstance(".\Train2013\\oldprocessed\\ProcessedtrainIstance.txt",".\Train2013\\oldprocessed\\trainIstance.txt",".\Train2013\\traindrugIstance.txt")
    # makeinstance(".\Test2013\\oldprocesseddata\\ProcessedtestIstance.txt",".\Test2013\\oldprocesseddata\\testIstance.txt", ".\Test2013\\testdrugIstance.txt")
    # deletepair(".\Train2013\\alltrainIstance.txt",".\Train2013\\processedalltrainIstance.txt")
    # preprocess(trainIstancepath, ProcessedtrainIstancepath)
    # find_max_sentence(trainIstanceDrugpath)#80
    # changeSpelling(".\Test2013\\testIstance.txt",".\Test2013\\Istance.txt")
    # changeSpelling(".\Train2013\\trainIstance.txt", ".\Train2013\\Istance.txt")

    # replaceNumber(".\Test2013\\Istance.txt",".\Test2013\\NIstance.txt")
    # replaceNumber(".\Train2013\\Istance.txt",".\Train2013\\NIstance.txt")

    # deletepairfinal(".\Train2013\\dIstance.txt", ".\Train2013\\dIstance1.txt")
    # deletepair(".\Train2013\\Istance.txt", ".\Train2013\\dIstance.txt")
    # getPosition(trainIstanceDrugpath, trainIstanceDrugPosition1path, trainIstanceDrugPosition2path)
    # getsubposition(trainIstanceDrugpath, ".\\Train2013\\trainTodrug1PositionSub1List.txt", ".\\Train2013\\trainTodrug1PositionSub2List.txt", ".\\Train2013\\trainTodrug1PositionSub3List.txt", ".\\Train2013\\trainTodrug2PositionSub1List.txt", ".\\Train2013\\trainTodrug2PositionSub2List.txt", ".\\Train2013\\trainTodrug2PositionSub3List.txt")
    # getsubposition(testIstanceDrugpath, ".\\Test2013\\testTodrug1PositionSub1List.txt", ".\\Test2013\\testTodrug1PositionSub2List.txt", ".\\Test2013\\testTodrug1PositionSub3List.txt", ".\\Test2013\\testTodrug2PositionSub1List.txt", ".\\Test2013\\testTodrug2PositionSub2List.txt", ".\\Test2013\\testTodrug2PositionSub3List.txt")
    # preprocess(".\\Train2013\\trainTodrug1PositionSub1List.txt", ".\\Train2013\\protrainTodrug1PositionSub1List.txt")
    # preprocess(".\\Train2013\\trainTodrug1PositionSub2List.txt", ".\\Train2013\\protrainTodrug1PositionSub2List.txt")
    # preprocess(".\\Train2013\\trainTodrug1PositionSub3List.txt", ".\\Train2013\\protrainTodrug1PositionSub3List.txt")
    # preprocess(".\\Train2013\\trainTodrug2PositionSub1List.txt", ".\\Train2013\\protrainTodrug2PositionSub1List.txt")
    # preprocess(".\\Train2013\\trainTodrug2PositionSub2List.txt", ".\\Train2013\\protrainTodrug2PositionSub2List.txt")
    # preprocess(".\\Train2013\\trainTodrug2PositionSub3List.txt", ".\\Train2013\\protrainTodrug2PositionSub3List.txt")
    # preprocess(".\\Test2013\\testTodrug1PositionSub1List.txt",".\\Test2013\\protestTodrug1PositionSub1List.txt")
    # preprocess(".\\Test2013\\testTodrug1PositionSub2List.txt", ".\\Test2013\\protestTodrug1PositionSub2List.txt")
    # preprocess(".\\Test2013\\testTodrug1PositionSub3List.txt", ".\\Test2013\\protestTodrug1PositionSub3List.txt")
    # preprocess(".\\Test2013\\testTodrug2PositionSub1List.txt", ".\\Test2013\\protestTodrug2PositionSub1List.txt")
    # preprocess(".\\Test2013\\testTodrug2PositionSub2List.txt", ".\\Test2013\\protestTodrug2PositionSub2List.txt")
    # preprocess(".\\Test2013\\testTodrug2PositionSub3List.txt", ".\\Test2013\\protestTodrug2PositionSub3List.txt")
    # preprocess(".\\Test2013\\testIstanceResult.txt", ".\\Test2013\\protestIstanceResult.txt")

    # getPosition(testIstanceDrugpath, testIstanceDrugPosition1path, testIstanceDrugPosition2path)
    # preprocess(trainIstanceDrugPosition1path,trainIstanceDrugPosition1Processed)
    # preprocess(trainIstanceDrugPosition2path, trainIstanceDrugPosition2Processed)
    # preprocess(testIstanceDrugPosition1path, testIstanceDrugPosition1Processed)
    # preprocess(testIstanceDrugPosition2path, testIstanceDrugPosition2Processed)
    # getPositionRange(trainIstanceDrugPosition1Processed,trainIstanceDrugPosition2Processed,testIstanceDrugPosition1Processed,testIstanceDrugPosition2Processed,PositionListPath)
    # getPositionWeighted(testIstanceDrugpath, testIstanceDrugPositionweighted)
    # getPositionWeighted(trainIstanceDrugpath, trainIstanceDrugPositionweighted)
    # preprocess(testIstanceDrugPositionweighted,testIstanceDrugPositionweightedProcessed)
    # preprocess(trainIstanceDrugPositionweighted, trainIstanceDrugPositionweightedProcessed)

    # creativePositionList(AllPositionListPath)
    # get_Position_matrix(AllPositionMatricxPath, vec_size, distanceListnum=200)
    # makeresultandinstance(".\Test2013\\testdrugIstance.txt",ProcessedtestIstanceResultpath,".\Test2013\\testresultIstance.txt" )
    # makeresultandinstance(".\Train2013\\traindrugIstance.txt",ProcessedtrainIstanceResultpath,".\Train2013\\trainresultIstance.txt" )

    # preprocess(trainIstanceResultpath, ProcessedtrainIstanceResultpath)
    # preprocess(testIstanceResultpath, ProcessedtestIstanceResultpath)
    #最大句子长度为94
    # preprocess(testIstancepath, ProcessedtestIstancepath)
    # find_max_sentence(testIstanceDrugpath)#87

    # loadsentence(".\Train2013\\trainIstanceD.txt", ".\Train2013\\trainCsentence_token.txt")
    # loadsentence(".\Train2013\\Csentence.txt", ".\Train2013\\Ksentence.txt")

    # getpos(".\Test2013\\sentence.txt",".\Test2013\\testpos.txt")
    # getpos(".\Train2013\\sentence.txt", ".\Train2013\\trainpos.txt")
    # preprocess(".\Test2013\\testpos.txt",".\Test2013\\pos.txt")
    # preprocess(".\Train2013\\trainpos.txt", ".\Train2013\\pos.txt")
    # getposlist(".\Test2013\\pos.txt",".\Train2013\\pos.txt",".\Train2013\\AllposList.txt")
    # get_Position_matrix(".\Train2013\\AllposMatrix.txt", vec_size=50, distanceListnum=31)
    # cleanfuhao(".\wordvector\Apubmed_All_Ab.txt", ".\wordvector\processedApubmed_All_Ab.txt")
    # changeSpelling(".\wordvector\processedApubmed_All_Ab.txt", ".\wordvector\cpApubmed_All_Ab.txt")
    # cleanfuhao(".\Test2013\\Ksentence.txt",".\Test2013\\Kdsentence.txt")
    # cleanfuhao(".\Train2013\\Ksentence.txt", ".\Train2013\\Kdsentence.txt")
    # makefile(".\\word.txt", ".\\wordvector\\cpApubmed_All_Ab.txt")
    # deletedrug0(".\\Train2013\\trainCsentence_token.txt",".\\Train2013\\trainCsentence_token(deletedrug0).txt")
    # deletedrug0(".\\Test2013\\testCsentence_token.txt",".\\Test2013\\testCsentence_token(deletedrug0).txt")
    # getsubsection(".\\Test2013\\testCsentence_token.txt",".\\Test2013\\testCsentence_token1.txt",".\\Test2013\\testCsentence_token2.txt",".\\Test2013\\testCsentence_token3.txt")
    # getsubsection(".\\Train2013\\trainCsentence_token.txt",".\\Train2013\\trainCsentence_token1.txt",".\\Train2013\\trainCsentence_token2.txt",".\\Train2013\\trainCsentence_token3.txt")

    # find_max_sentence(".\\Test2013\\testCsentence_token.txt")
    # find_max_sentence(".\\Test2013\\testCsentence_token2.txt")
    # find_max_sentence(".\\Test2013\\testCsentence_token3.txt")
    # find_max_sentence(".\\Train2013\\trainCsentence_token1.txt")
    # find_max_sentence(".\\Train2013\\trainCsentence_token2.txt")
    # find_max_sentence(".\\Train2013\\trainCsentence_token3.txt")
    # find_max_sentence(".\\Train2013\\trainCsentence_token.txt")
    # find_max_sentence(".\\Test2013\\testCsentence_token.txt")
if __name__ == "__main__":
    main()


class Vertex(object):
    def __init__(self, value):
        self.value = value
        self.visited = False

class Graph(object):
    def __init__(self):
        from collections import deque
        self.vertices = []
        self.edges = []
        self.stack = []
        self.queue = deque()

    def add_vertex(self, value):
        self.vertices.append(Vertex(value))
        self.edges = [x + [0] for x in self.edges]
        self.edges.append([0] * len(self.vertices))

    def add_edge(self, start, end, weight=1):
        l = len(self.edges)
        if 0 < start >= l or 0 < end >= l:
            print("Add edge error")
        else:
            self.edges[start][end] = self.edges[end][start] = weight

    def find_next_adjacent(self, index):
        for vert_index, value in enumerate(self.edges[index]):
            if (value and not self.vertices[vert_index].visited):
                return vert_index

        return None

    def display_vertex(self, index):
        return f"{self.vertices[index].value}"

    def dfs(self):
        result = []
        if not self.vertices:
            return result

        index = 0
        self.vertices[index].visited = True
        result.append(self.display_vertex(index))
        self.stack.append(index)

        while (self.stack):
            index = self.find_next_adjacent(self.stack[-1])
            if index:
                self.vertices[index].visited = True
                result.append(self.display_vertex(index))
                self.stack.append(index)
            else:
                index = self.stack.pop()

        return result

    def bfs(self):
        result = []
        if not self.vertices:
            return result

        index = 0
        self.vertices[index].visited = True
        result.append(self.display_vertex(index))
        self.queue.appendleft(index)

        while(self.queue):
            index = self.find_next_adjacent(self.queue[-1])
            if index:
                self.vertices[index].visited = True
                result.append(self.display_vertex(index))
                self.queue.appendleft(index)
            else:
                index = self.queue.pop()

        return result


__all__ = ['pretty_print_model_fields']

def _get_class_full_name(cls_):
    return cls_.__module__ + '.' + cls_.__name__

class _ModelFieldRow(object):

    def __init__(self, field):
        self.field = field
        self.name = field.name
        self.type_ = _get_class_full_name(type(field))
        if self.field.many_to_many\
                or self.field.many_to_one\
                or self.field.one_to_many\
                or self.field.one_to_one:
            self.related_model = _get_class_full_name(self.field.remote_field.model)
        else:
            self.related_model = 'N/A'

    def pretty_print(self, max_name_len, max_type_len, max_rel_model_len):
        row = []
        row.append(self.name)
        row.append(' ' * (max_name_len - len(self.name)))
        row.append('|')
        row.append(self.type_)
        row.append(' ' * (max_type_len - len(self.type_)))
        row.append('|')
        row.append(self.related_model)
        row.append(' ' * (max_rel_model_len - len(self.related_model)))
        print(''.join(row))

def pretty_print_model_fields(model):
    field_info_rows = []
    max_lens = [0, 0, 0]
    for field in model._meta.get_fields():
        field_info_rows.append(_ModelFieldRow(field))
        max_lens[0] = max(max_lens[0], len(field_info_rows[-1].name))
        max_lens[1] = max(max_lens[1], len(field_info_rows[-1].type_))
        max_lens[2] = max(max_lens[2], len(field_info_rows[-1].related_model))
    print('=' * (sum(max_lens) + len(max_lens) - 1))
    for row in field_info_rows:
        row.pretty_print(*max_lens)
        print('=' * (sum(max_lens) + len(max_lens) - 1))


# from collections import OrderedDict
#
#
# def find_node_without_dependencies(dependencies_by_node):
#     for node, dependencies in dependencies_by_node.items():
#         if dependencies == 0:
#             return node
#     return None
#
#
# def find_dependencies(graph):
#     result = {}
#     for node, children in graph.items():
#         if node not in result:
#             result[node] = 0
#         for child in children:
#             if child not in result:
#                 result[child] = 1
#             else:
#                 result[child] += 1
#     return result
#
#
# graph = {}
# while True:
#     a = input()
#     if a == 'End':
#         break
#     vhod = a.split('->')
#     node = vhod[0].strip()
#     child = vhod[1].strip().split() if vhod[1] else []
#     graph[node] = child
#
# dependencies_by_node = find_dependencies(graph)
# sorted_nodes = []
# dependencies_by_node = OrderedDict(reversed(list(dependencies_by_node.items())))
# while dependencies_by_node:
#     node_to_remove = find_node_without_dependencies(dependencies_by_node)
#     dependencies_by_node.pop(node_to_remove)
#     sorted_nodes.append(node_to_remove)
#     for child in graph[node_to_remove]:
#         dependencies_by_node[child] -= 1
#
# print(' '.join(sorted_nodes))

def dfs(node, graph, visited, result):
    if node in visited:
        return
    visited.add(node)
    for child in graph[node]:
        dfs(child, graph, visited, result)
    result.append(node)

graph = {}
while True:
    a = input()
    if a == 'End':
        break
    vhod = a.split('->')
    node = vhod[0].strip()
    child = vhod[1].strip().split() if vhod[1] else []
    graph[node] = child

visited = set()
result = []
for node in graph:
    dfs(node, graph, visited, result)

print(' '.join(reversed(result)))

Algorithms with Python/Exam preparation/The story telling.py


"""Word Drop Module."""
from .OneDim import OneDim

import copy
import math
import numpy as np
import pandas as pd
import random
import spacy

from progress.bar import ShadyBar
from checklist.perturb import Perturb

class DropWordsOneDim(OneDim):
    """Class for word drop task."""

    __slots__ = [
        "texts", "results", "dmgd_texts",
        "combined_results", "step_arr", "path",
        "name", "df", "descr"]

    def __init__(self, params: dict):
        """Initialize."""
        super(DropWordsOneDim, self).__init__(params=params)
        self.name = "dropped_words"
        self.descr = "Dropped words"

    @staticmethod
    def drop_single(
            sentence: str,
            doc: spacy.tokens.doc.Doc,
            step: float) -> tuple:
        """Drop words.

        Params
        ------
        sentence : str
            sentence
        doc : spacy.tokens.doc.Doc
            spacy document containing linguistic information
            about the sentence
        step : float
            fraction of how many tokens are to be dropped

        Returns
        -------
        tuple
            Tuple including sentence and success of modification
        """
        bound: float = 1 - 1 / len(doc)
        if len(doc) == 0:
            return sentence, False

        if step == 0:
            return sentence, True

        candidates: list = []
        for i in range(len(doc)):
            if doc[i].pos_ != "PUNCT":
                candidates.append(i)
            else:
                continue

        # one word must be in the sentence at least
        if step > bound:
            step = bound

        prop: float = int(math.floor(step * len(candidates)))
        drop_list: list = random.sample(candidates, k=prop)

        sent: str = ""

        for i in range(len(doc)):

            # exclude words to be dropped
            if i in drop_list:
                continue

            # TODO annotate
            token = doc[i]

            word = ""
            if i == 0:
                word = token.text
            else:
                if token.pos_ == "PUNCT":
                    word = token.text
                else:
                    word = " " + token.text
            sent += word

        if len(sent.strip()) == 0:
            print("Sentence empty! Word drop")
            return sent, False

        return sent, True

    def perturbate(self) -> None:
        """Perturbate sentences."""
        bar: ShadyBar = ShadyBar(
            message="Perturbating " + self.name + " ",
            max=len(self.step_arr) * len(self.texts))

        for step in self.step_arr:
            ret_tuple: tuple = ([], [])
            for _, (sentences, doc) in enumerate(self.texts):

                sentences: list = copy.deepcopy(sentences)
                indices: list = []

                for i in range(len(sentences)):

                    if len(doc[i]) < 2:
                        continue

                    new_sentence = sentences[i]
                    new_sentence, success = self.drop_single(
                        sentence=sentences[i],
                        doc=doc[i],
                        step=step)

                    if success:
                        indices.append(i)
                        sentences[i] = new_sentence

                ret_tuple[0].append(sentences)
                ret_tuple[1].append(indices)
                bar.next()

            self.dmgd_texts.append(ret_tuple)

        bar.finish()


'''
给定一个整数数组 nums 和一个目标值 target，
请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是，你不能重复利用这个数组中同样的元素。
'''
import numpy as np
import logging

def two_sum(nums, target):
    # nums是数组，遍历nums，找target-nums【i】，
    if len(nums)>2:
        result = []
        for idx,value in enumerate(nums):
            for i in range(len(nums)-idx):
                if nums[idx+i] == target - value:
                    result.append((idx, idx+i))
        return result
    else:
        logging.error("nums len less than 2")
        return 0

if __name__=="__main__":
    nums = [2, 7, 11, 15, 4, 3, 5, 6, 12, 9]
    target = 15
    print(two_sum(nums, target))


"""Defines URL patterns for pages."""
from django.urls import path

from . import views

app_name = 'pages'
urlpatterns = [
    #Home page
    path('', views.home, name='home'),
    path('home/', views.home, name='home'),
    # Page that show services section.
    path('services/', views.services, name='services'),
    #Page that show skills section.
    path('skills/', views.skills, name='skills'),
    #Page that show teams section.
    path('projects/', views.projects, name='projects'),
    #Page that show contact section.
    path('contact/', views.contact, name='contact')
]


import folium
from folium import plugins
import random

def createstart(startloc):
    map = folium.Map(location=startloc, zoom_start=8, tiles='openstreetmap')
    #display map
    folium.Marker(startloc, popup='Start Location',icon=folium.Icon(color='green')).add_to(map)
    map.save('templates/map.html')

def createdest(startloc, destloc):
    map = folium.Map(location=startloc, zoom_start=8, tiles='openstreetmap')
    #display map
    folium.Marker(startloc, popup='Start Location',icon=folium.Icon(color='green')).add_to(map)
    folium.Marker(destloc, popup='Destination Location',icon=folium.Icon(color='red')).add_to(map)
    map.save('templates/map.html')

def plotroute(route1,danger1,route2,danger2,route3,danger3):
    if route1!= None:
        route1 = route1["coordinates"]
        for item in route1:
            temp = item[0]
            item[0]=item[1]
            item[1]=temp
    if route2!= None:
        route2 = route2["coordinates"]
        for item in route2:
            temp = item[0]
            item[0]=item[1]
            item[1]=temp

    if route3 != None:
        route3 = route3["coordinates"]
        for item in route3:
            temp = item[0]
            item[0]=item[1]
            item[1]=temp

    if route2 != None:
        map_plot_antroute = folium.Map(location=route2[int((len(route2)/2)-1):int(len(route2)/2)][0], zoom_start=15)
    else:
        map_plot_antroute = folium.Map(location=route1[int((len(route1)/2)-1):int(len(route1)/2)][0], zoom_start=15)

    folium.Marker(route1[0], popup='Start Location',icon=folium.Icon(color='green')).add_to(map_plot_antroute)
    folium.Marker(route1[-1], popup='Destination Location',icon=folium.Icon(color='red')).add_to(map_plot_antroute)

    if route1 != None:
        # added lat long to route
        route_lats_longs = route1
        if danger1 in [0,1]:
            color = 'green'
        if danger1 in [2,3]:
            color = 'orange'
        if danger1 in [4,5]:
            color = 'red'
        # Ploting ant-route
        plugins.AntPath(route_lats_longs,color='green').add_to(map_plot_antroute)

    if route2 != None:
        # added lat long to route
        route_lats_longs = route2
        if danger2 in [0,1]:
            color = 'green'
        if danger2 in [2,3]:
            color = 'orange'
        if danger2 in [4,5]:
            color = 'red'
        # Ploting ant-route
        plugins.AntPath(route_lats_longs,color='orange').add_to(map_plot_antroute)

    if route3 != None:
        # added lat long to route
        route_lats_longs = route3
        if danger3 in [0,1]:
            color = 'green'
        if danger3 in [2,3]:
            color = 'orange'
        if danger3 in [4,5]:
            color = 'red'
        # Ploting ant-route
        plugins.AntPath(route_lats_longs,color='red').add_to(map_plot_antroute)

    map_plot_antroute.save('templates/map.html')


import pandas as pd

def solution(info, query):
    answer = []

    lang_list = []
    stack_list = []
    career_list = []
    food_list = []
    score_list = []
    for inf in info :
        lang, stack, career, food, score = inf.split(' ')
        score = int(score)
        lang_list.append(lang)
        stack_list.append(stack)
        career_list.append(career)
        food_list.append(food)
        score_list.append(score)

    info_df = pd.DataFrame(data = {'언어' : lang_list,
                              '스택' : stack_list,
                              '경력' : career_list,
                              '소울푸드' : food_list,
                              '점수' : score_list})

    for q in query :
        lang, stack, career, food_score = q.split('and')
        lang = lang.strip()
        stack = stack.strip()
        career = career.strip()
        food_score = food_score.strip()
        food = food_score.split(' ')[0]
        score = int(food_score.split(' ')[1])

        new_df = info_df[info_df['점수'] >= score]

        if lang == '-' :
            pass
        else :
            new_df = new_df[new_df['언어'] == lang]

        if stack == '-' :
            pass
        else :
            new_df = new_df[new_df['스택'] == stack]

        if career == '-' :
            pass
        else :
            new_df = new_df[new_df['경력'] == career]

        if food == '-' :
            pass
        else :
            new_df = new_df[new_df['소울푸드'] == food]

        answer.append(len(new_df))
    return answer

# 시간초과
import pandas as pd

def solution(info, query):
    answer = []

    dataframe = pd.DataFrame()
    languages, stacks, careers, foods, scores = [], [], [], [], []
    for information in info: # O(50000)
        language, stack, career, food, score = information.split()
        languages.append(language)
        stacks.append(stack)
        careers.append(career)
        foods.append(food)
        scores.append(int(score))

    dataframe['언어'] = languages
    dataframe['직군'] = stacks
    dataframe['경력'] = careers
    dataframe['푸드'] = foods
    dataframe['점수'] = scores

    for q in query: # O(100000)
        language, stack, career, food_score = q.split('and')
        food, score = food_score.split()

        if language.strip() == '-': language = ''
        if stack.strip() == '-': stack = ''
        if career.strip() == '-': career = ''
        if food.strip() == '-': food = ''
        if score.strip() == '-': score = ''

        d_l = dataframe[dataframe['언어'] == language.strip()] if language else dataframe
        d_s = d_l[d_l['직군'] == stack.strip()] if stack else d_l
        d_c = d_s[d_s['경력'] == career.strip()] if career else d_s
        d_f = d_c[d_c['푸드'] == food.strip()] if food else d_c
        d_ss = d_f[d_f['점수'] >= int(score.strip())] if score else d_f
        answer.append(len(d_ss))
    return answer

# 시간초과
from itertools import product, combinations
import numpy as np

def solution(info, query):
    answer = []

    languages = ['cpp', 'java', 'python']
    stacks = ['backend', 'frontend']
    careers = ['junior', 'senior']
    foods = ['chicken', 'pizza']

    combination_dict = {'empty': []}
    for prod in list(product(languages, stacks, careers, foods)):
        for i in range(1, 5):
            for comb in combinations(prod, i):
                combination_dict[comb] = []

    for information in info:
        language, stack, career, food, score = information.split()
        combination_dict['empty'].append(score)
        for i in range(1, 5):
            for comb in combinations([language, stack, career, food], i):
                combination_dict[comb].append(score)

    for q in query:
        language, stack, career, food_score = q.split(' and ')
        food, score = food_score.split()

        name = []
        if language != '-': name.append(language)
        if stack != '-': name.append(stack)
        if career != '-': name.append(career)
        if food != '-': name.append(food)
        name = tuple(name)

        if not name:
            name = 'empty'

        check_score = combination_dict[name]

        check_score = combination_dict[name]
        check_score = list(map(int, check_score))
        check_score = np.array(check_score)
        count = len(check_score[check_score >= int(score)])

        answer.append(count)

        # count = 0
        # cnt = [1 if int(s) >= int(score) else 0 for s in check_score ]
        # answer.append(sum(cnt))
        # for s in check_score:
        #     if int(s) >= int(score):
        #         count += 1
        # answer.append(count)
    return answer

# 통과
from itertools import product, combinations

from typing import List

def binary_search(check_score: List, score: int) -> int:
    if len(check_score) == 0:
        return 0

    start, end = 0, len(check_score)-1

    min_idx = len(check_score)
    while start <= end:
        mid = (start + end) // 2

        if check_score[mid] >= score:
            end = mid-1
            min_idx = min(min_idx, mid)
        else:
            start = mid+1
    return len(check_score) - min_idx

def solution(info, query):
    answer = []

    languages = ['cpp', 'java', 'python']
    stacks = ['backend', 'frontend']
    careers = ['junior', 'senior']
    foods = ['chicken', 'pizza']

    combination_dict = {'empty': []}
    for prod in list(product(languages, stacks, careers, foods)):
        for i in range(1, 5):
            for comb in combinations(prod, i):
                combination_dict[comb] = []

    for information in info:
        language, stack, career, food, score = information.split()
        combination_dict['empty'].append(int(score))
        for i in range(1, 5):
            for comb in combinations([language, stack, career, food], i):
                combination_dict[comb].append(int(score))

    for key in combination_dict.keys():
        combination_dict[key].sort()

    for q in query:
        language, stack, career, food_score = q.split(' and ')
        food, score = food_score.split()

        name = []
        if language != '-': name.append(language)
        if stack != '-': name.append(stack)
        if career != '-': name.append(career)
        if food != '-': name.append(food)
        name = tuple(name)

        if not name:
            name = 'empty'

        check_score = combination_dict[name]

        count = binary_search(check_score, int(score))
        answer.append(count)

    return answer


import pickle
import streamlit as st
import requests
import pandas as pd

def fetch_poster(movie_id):
    url = "https://api.themoviedb.org/3/movie/{}?api_key=d4b65d015870427bde13e7261ad70435&language=en-US".format(movie_id)
    data = requests.get(url)
    data = data.json()
    poster_path = data['poster_path']
    full_path = "https://image.tmdb.org/t/p/w500/" + poster_path
    return full_path

def recommend(movie):
    movie_index = movies[movies['title'] == movie].index[0]
    distances = similarity[movie_index]
    movie_list=sorted(list(enumerate(distances)),reverse=True,key=lambda x:x[1])[1:6]
    recommended_movies = []
    recommended_movie_posters = []
    for i in movie_list:
        # fetch the movie poster
        movie_id = movies.iloc[i[0]].movie_id
        recommended_movie_posters.append(fetch_poster(movie_id))
        recommended_movies.append(movies.iloc[i[0]].title)

    return recommended_movies,recommended_movie_posters

st.header('Movie Recommender System')
movies = pickle.load(open('movie_.pkl','rb'))
similarity = pickle.load(open('similarity.pkl','rb'))

movie_list = movies['title'].values
selected_movie = st.selectbox(
    "Type or select a movie from the dropdown to get recommendations",
    movies['title'].values)

if st.button('Show Recommendation'):
    names,posters = recommend(selected_movie)
    col1, col2, col3, col4, col5 = st.columns(5)
    with col1:
        st.text(names[0])
        st.image(posters[0])
    with col2:
        st.text(names[1])
        st.image(posters[1])

    with col3:
        st.text(names[2])
        st.image(posters[2])
    with col4:
        st.text(names[3])
        st.image(posters[3])
    with col5:
        st.text(names[4])
        st.image(posters[4])


# 27. Remove Element
from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if len(nums)==0:
            return 0
        i=0
        j = len(nums)-1
        while (i<=j):
            if nums[i] != val:
                i = i+1
            elif nums[j]== val:
                j = j-1
            else:
                nums[i] = nums[j]
                i = i+1
                j = j-1
        return i

s = Solution
nums = [0,1,2,2,3,0,4,2]
val = 2
nums = [3,2,2,3]; val = 3
nums = [0]; val = 0
# nums = [3,3,3,3]; val = 3
# nums = [2]; val = 3
# nums = [4,5]; val = 4
print(s.removeElement(s, nums, val))
print(nums)


"""
1. Write a program that asks the user to enter a number and displays whether
entered number is an odd number or even number?
"""

fromUser = int(input("Please enter a number"))
if(fromUser % 2 == 0):
    print("The entered number is a even number")
else:
    print("The entered number is an odd number")

# using shorthand

print("The entered number is a even number") if fromUser % 2 == 0 else print("The entered number is an odd number")

"""

Write a program that prompts the user to input a number.
The program should then output the number and a message saying whether
the number is positive, negative, or zero.

"""

fromUser = int(input("Please enter a number"))
if(fromUser == 0):
    print("Number is equal to zero")
elif(fromUser > 0):
    print("Number is grater than zero")
else:
    print("Number is lesser than zero")

"""
Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
"""
bill = 0
telephoneUseage = int(input("Please enter the number of call"))
if(telephoneUseage <= 100 ):
    bill = 200
elif(telephoneUseage <= 150):
    bill = 200 + (telephoneUseage - 100) * 0.60
elif(telephoneUseage <= 200):
    bill = 200 + (50 * 0.60) + ((telephoneUseage - 150) * 0.60)
else:
    bill = 200 + 50 * 0.60 + 50 * 0.50 + (telephoneUseage - 200) * 0.40
print("Telephone bill is ",bill)


import numpy as np

import torch
import torch.nn as nn
from torch.nn.parameter import Parameter

class TransformerEmbedding(nn.Module):
    """Embeddings matrix mixed with positional encoding for sequences."""

    def __init__(self, vocab_size, num_units, use_positional_encoding):
        super(TransformerEmbedding, self).__init__()
        self.num_units = num_units
        self.use_positional_encoding = use_positional_encoding
        self.embed = nn.Embedding(vocab_size, num_units)

    def _sin_cos_enc(self, from_length, to_length, embedding_size):
        position_enc = np.array(
            [[
                pos / np.power(10000, 2 * i / embedding_size)
                for i in range(embedding_size)
            ] for pos in range(from_length, to_length)],
            dtype=np.float32)

        # put sinusodial on even position
        position_enc[:, 0::2] = np.sin(position_enc[:, 0::2])
        # put cosine on odd position
        position_enc[:, 1::2] = np.cos(position_enc[:, 1::2])

        result = Parameter(torch.from_numpy(position_enc))  # Why is this a parameter?
        if next(self.embed.parameters()).is_cuda:
            result = result.cuda()
        return result

    def forward(self, ids):
        embed = self.embed(ids)
        if self.use_positional_encoding:
            embed += self._sin_cos_enc(0, embed.size(1), self.num_units)
        return embed

    def sample(self, ids, position):
        embed = self.embed(ids)
        if self.use_positional_encoding:
            embed += self._sin_cos_enc(position, position + 1, self.num_units)
        return embed


import requests
import json
from statistics import mean, stdev
from os import environ

# get_quarter(int) -> string
# takes a month and returns the quarter
# it belongs to as string to use as key
# for gas_per_quarter dictionary
def get_quarter(month):
	if 1 <= month <= 3:
		return "Q1"
	elif 4 <= month <= 6:
		return "Q2"
	elif 7 <= month <= 9:
		return "Q3"
	elif 10 <= month <= 12:
		return "Q4"

# series_id specifies which data set you want to get
# in particular, ELEC.CONS_TOT.NG-TX-99.M has the
# total consumption of natural gas in thousand McF
# per month in Texas
parameters = {
	"api_key": environ['API_KEY'],
	"series_id": "ELEC.CONS_TOT.NG-TX-99.M",
	"start": 201801,
	"end": 201812
}

# try to fetch from endpoint
try:
	response = requests.get("https://api.eia.gov/series", params=parameters)
	response.raise_for_status()

# if connection unsuccessful raise and print error info
except requests.exceptions.HTTPError as err:
	print(f"HTTP error: {err.response.status_code}")

else:
	# retrieve the data we care about
	data = response.json()['series'][0]['data']
	# retrieve unit of data for later printing of statistics
	units = response.json()['series'][0]['units']

	# dict to store gas consumption per quarter
	gas_per_quarter = {"Q1":[], "Q2":[], "Q3":[], "Q4":[]}

	# since the date format given is YYYYMM, splice the
	# last two chars from date, cast to int and save as
	# month variable. then append consumption value into
	# corresponding quarter in gas_per_quarter
	for date, val in data:
		month = int(date[-2:])
		gas_per_quarter[get_quarter(month)].append(float(val))

	# retrieve data per quarter and output statistics
	print("Total consumption of natural gas in Texas in 2018")
	print("Quarterly statistics:\n")
	for quarter in gas_per_quarter.keys():
		print(f"{quarter}:")
		print(f"average: {mean(gas_per_quarter[quarter])}")
		print(f"standard deviation: {stdev(gas_per_quarter[quarter])}")
		print(f"max value: {max(gas_per_quarter[quarter])}")
		print(f"min value: {min(gas_per_quarter[quarter])}")
		print("")


import pickle
import sys, os
from os import listdir
from os.path import isfile, join
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix, f1_score
from collections import Counter
import pandas as pd

mypath = sys.argv[1]
onlyfiles = [os.path.join(mypath, f )for f in listdir(mypath) if isfile(join(mypath, f))]
max_acc = 0
mean_acc = 0
def transpose(labels):
    labels = np.array(labels)
    labels[np.where(labels==0)] = 2
    labels[np.where(labels==1)] = 0
    labels[np.where(labels==2)] = 1

    return list(labels)

def calculatePrecisionRecallAccuracy(labels, outputs):
    tp = 0
    fp = 0
    tn = 0
    fn = 0
    for label, output in zip(labels, outputs):
        if label==output and label ==0:
            tn = tn+1
        elif label==output and label==1:
            tp = tp+1
        elif label!=output and label == 0:
            fp = fp+1
        else:
            fn = fn +1
    precision = tp*1.0/(tp+fp)
    recall = tp*1.0/(tp+fn)
    accuracy = (tp+tn)*1.0/(tp+fp+fn+tn)
#    print("tp:", tp, "fp:", fp, "fn:", fn)
    return  precision, recall, accuracy

onlyfiles.sort(key=lambda x: (int(os.path.basename(x).split('_')[0]), x) )

for f in onlyfiles:
    basename = os.path.basename(f)
    splits = basename.split('_')
    epoch = splits[0]
    scale = splits[2]
    resize = splits[3]
    accuracy, labels, outputs = pickle.load(open(f,'rb'))
#    accuracy = f1_score(labels, outputs, average='macro')
#    print("accuracy:", accuracy, f)

#    c = Counter(labels)
#    out = []
#    lbl = []
#    for idx, label in enumerate(labels):
#        if c[label] != 1:
#            out.append(outputs[idx])
#            lbl.append(label)

#    outputs = out
#    labels = lbl

    accuracy = f1_score(labels, outputs, average='macro')
    print("accuracy:", accuracy, f)

    y_true = pd.Series(labels, name="Actual")
    y_pred = pd.Series(outputs, name="Predicted")
    df_confusion = pd.crosstab(y_true, y_pred, margins=True)
                #confusion_matrix = ConfusionMatrix(y_true, y_pred)
    df_confusion.to_csv("confusion.csv")

    #outputs = transpose(outputs)
#    precision, recall, accuracy = calculatePrecisionRecallAccuracy(labels, outputs)
#    print(classification_report(labels, outputs))
#    matrix = confusion_matrix(outputs, labels)
#    print(matrix)
    if max_acc < accuracy:
      max_acc = accuracy
    mean_acc += accuracy
#    print("precision:%.3f"%precision, "recall:%.3f"%recall,"accuracy:%.3f"%accuracy, "epoch:", epoch, "scale;", scale, "resize:", resize)

print("maximum accuracy:", max_acc)
print("Mean_accuracy:", mean_acc/len(onlyfiles))


from .models import PriceOfTicket
from django.db import transaction
import requests
import traceback
from datetime import datetime, timedelta

class ParserData:

    def __init__(self):
        self.headers = {
            'Content-Type': 'application/json'
        }
        self.respons = []
        self.data_by_date = {}

    def start_parse(self, url):
        responce = self.get_data(url)
        self.sort_by_date(responce)
        self.parse_data()

    def check_url(self, dict_check):
        response = self.get_data(dict_check["url"])
        self.cheking_data(response, dict_check["id"])

    def cheking_data(self, data, id):
        obj = PriceOfTicket.objects.get(pk=id)
        obj.flights_checked = data.get('flights_checked')
        obj.flights_invalid = data.get('flights_invalid')
        obj.price_change = data.get('price_change')
        obj.save()

    def get_data(self, url):
        try:
            response = requests.get(url=url, headers=self.headers)
            if response.status_code == 404:
                return
            if response.status_code != 200:
                raise ValueError('Request to {} responded with status {}'.format(url, response.status_code))
            else:
                return response.json()
        except Exception:
            raise Exception('Error in getting html\n' + str(traceback.format_exc()))

    def sort_by_date(self, response):
        data = response['data']
        for i in data:
            date = str(datetime.utcfromtimestamp(i['dTime']).strftime('%Y-%m-%d'))  # .strftime('%Y-%m-%d %H:%M:%S')
            if date in self.data_by_date:
                self.data_by_date[date].append(i)
            else:
                self.data_by_date[date] = []
                self.data_by_date[date].append(i)

    def parse_data(self):
        for k, v in self.data_by_date.items():
            seq_price = [x['price'] for x in v]
            min_price = min(seq_price)
            v = [x for x in v if x['price'] == min_price]
            rows_for_ins = []
            with transaction.atomic():
                for i in v:
                    PriceOfTicket.objects.filter(id_in_api=i["id"]).delete()
                    pot = PriceOfTicket(id_in_api=i["id"],
                                      date=k,
                                      city_from=i["cityFrom"],
                                      city_to=i["cityTo"],
                                      price=i["price"],
                                      booking_token=i["booking_token"])
                    rows_for_ins.append(pot)

                PriceOfTicket.objects.bulk_create(rows_for_ins)

def create_urls():
    from_to = [
        {'from': "ALA", "to": "TSE"},
        {'from': "TSE", "to": "ALA"},
        {'from': "ALA", "to": "MOW"},
        {'from': "MOW", "to": "ALA"},
        {'from': "ALA", "to": "CIT"},
        {'from': "CIT", "to": "ALA"},
        {'from': "TSE", "to": "MOW"},
        {'from': "MOW", "to": "TSE"},
        {'from': "TSE", "to": "LED"},
        {'from': "LED", "to": "RSE"},
    ]
    date_now = datetime.now().strftime("%d/%m/%Y")
    now_30 = (datetime.now() + timedelta(30)).strftime("%d/%m/%Y")
    urls = [
        f'https://api.skypicker.com/flights?fly_from={i["from"]}&fly_to={i["to"]}&date_from={date_now}&date_to={now_30}&partner=picky'
        for i in from_to]
    return urls

def check_urls():
    urls = []
    objs = PriceOfTicket.objects.all()
    for i in objs:
        url = f'https://booking-api.skypicker.com/api/v0.1/check_flights?v=2&booking_token={i.booking_token}' \
              '&bnum=1' \
              '&pnum=1' \
              '&affily=picky_{market}' \
              '&currency=EUR&' \
              'adults=1' \
              '&children=0' \
              '&infants=0'
        urls.append({"url": url, "id": i.id})
    return urls


from django.shortcuts import render
from django.views import generic
from django.urls import reverse_lazy
from .forms import UserCreateForm
from .forms import CommentUpdateForm
from .forms import SearchForm
from .forms import FingerprintCreateForm
from .models import LabAttendanceTb
from .models import LabFingerprintTb
from .models import LabTips
from django.db.models import Q
import random
import json
from django.db.models.signals import post_save
from django.dispatch import receiver

from datetime import date,timedelta

# Create your views here.
# どのhtmlで出力するかの指定
# 出席情報画面
class AttendanceListView(generic.ListView):
    model = LabAttendanceTb
    template_name = 'attendance/attendance_list.html'

    def get_context_data(self, **kwargs):
        model_list = LabAttendanceTb.objects.all()

        tips_list = LabTips.objects.all()
        tips_size = tips_list.count()
        random_num = random.randint(1, tips_size)

        query = LabTips.objects.get(pk = random_num)

        context = {
            'labattendancetb_list': model_list,
            'image_name': "img/" + query.image,
            'text': query.sentence,
        }
        return context

# ユーザ登録画面
class UserCreateView(generic.CreateView):
    model = LabAttendanceTb
    form_class = UserCreateForm
    template_name = 'attendance/user_create.html'
    # ユーザ作成成功時のリダイレクト先
    success_url = reverse_lazy('attendance:attendance_list')

# 指紋登録画面
class FingerprintCreateView(generic.CreateView):
    model = LabFingerprintTb
    form_class = FingerprintCreateForm
    template_name = 'attendance/fingerprint_create.html'
    # ユーザ作成成功時のリダイレクト先
    success_url = reverse_lazy('attendance:attendance_list')

# コメント編集画面
class CommentUpdateView(generic.UpdateView):
    model = LabAttendanceTb
    form_class = CommentUpdateForm
    template_name = 'attendance/comment_update.html'
    # ユーザ作成成功時のリダイレクト先
    success_url = reverse_lazy('attendance:attendance_list')

# 検索画面
class SearchView(generic.ListView):
    template_name = 'attendance/search.html'
    model = LabAttendanceTb

    paginate_by = 5

    def post(self, request, *args, **kwargs):
        form_value = [
            self.request.POST.get('user_id', None),
            self.request.POST.get('user_name', None),
            self.request.POST.get('status', None),
        ]
        request.session['form_value'] = form_value
        # 検索時にページネーションに関連したエラーを防ぐ
        self.request.GET = self.request.GET.copy()
        self.request.GET.clear()
        return self.get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # sessionに値がある場合、その値をセットする。（ページングしてもform値が変わらないように）
        user_id = ''
        user_name = ''
        status = ''

        if 'form_value' in self.request.session:
            form_value = self.request.session['form_value']
            user_id = form_value[0]
            user_name = form_value[1]
            status = form_value[2]
        default_data = {'user_id': user_id,
                        'user_name': user_name,
                        'status': status,
                        }
        test_form = SearchForm(initial=default_data) # 検索フォーム
        context['test_form'] = test_form
        return context

    def get_queryset(self):
        # sessionに値がある場合、その値でクエリ発行する。
        if 'form_value' in self.request.session:
            form_value = self.request.session['form_value']
            user_id = form_value[0]
            user_name = form_value[1]
            status = form_value[2]
            # 検索条件
            condition_user_id = Q()
            condition_user_name = Q()
            condition_status = Q()
            if len(user_id) != 0 and user_id[0]:
                condition_user_id = Q(user_id__contains=user_id)
            if len(user_name) != 0 and user_name[0]:
                condition_user_name = Q(user_name__icontains=user_name)
            if len(status) != 0 and status[0]:
                condition_status = Q(status__icontains=status)
            return LabAttendanceTb.objects.select_related().filter(condition_user_id & condition_user_name & condition_status )
        else:
            # 何も返さない
            return LabAttendanceTb.objects.none()


import espressomd
import object_in_fluid as oif
import numpy as np

from espressomd import shapes

#when calling in the script, use:
#boundaries = list()
#FillBoundaries(boundaries, vtk_directory, par_ax, par_ay, par_az)
#for boundary in boundaries:
#    system.lbboundaries.add(lbboundaries.LBBoundary(shape=boundary))
#    system.constraints.add(shape=boundary, particle_type=10, penetrable=False)

def FillBoundaries(boundaries, vtk_directory, ax, ay, az, boxX, boxY, boxZ, width):
    # GEOMETRY
    # rectangular channel with size boxX*boxY*boxZ, the width of the borders is set with width
    # of the narrow rectangle part in the middle with cross-section ay*az and length ax, the entrance is smoothed

    # center of the channel
    cx = boxX / 2
    cy = boxY / 2
    cz = boxZ / 2

    # size of obstacles that create the narrow part
    # horizontal
    ah = ax
    bh = 2 * width + boxY
    ch = width + (boxZ - az) / 2
    # vertical
    av = ax
    bv = width + (boxY - ay) / 2
    cv = 2 * width + boxZ

    # corners for obstacles
    # A
    A_x = cx - ax / 2
    A_y = -width
    A_z = -width
    # B
    B_x = cx - ax / 2
    B_y = (boxY + ay) / 2
    B_z = -width
    # C
    C_x = cx - ax / 2
    C_y = -width
    C_z = (boxZ + az) / 2

    # size of obstacles that create 45 degree angle narrowing Left+Right
    odvesna = (boxY - ay)/2 - width
    vyska = boxZ+2*width

    # corners for obstacles that create 45 degree angle narrowing Left+Right
    # R
    R_x = cx - ax/2 - odvesna
    R_y = -width
    R_z = -width
    # L
    L_x = cx - ax / 2 - odvesna
    L_y = boxY + width
    L_z = -width

    # cylinder
    polomer = (boxY - ay)/4

    # cylinder entrance centres
    #left
    Cl_x = cx - ax / 2
    Cl_y = cy + ay/2 + polomer
    Cl_z = cz
    #right
    Cr_x = cx - ax / 2
    Cr_y = cy - ay/2 - polomer
    Cr_z = cz

    wallBottom = shapes.Rhomboid(corner=[-width, -width, -width], a=[boxX+2*width, 0.0, 0.0], b=[0.0, boxY+2*width, 0.0], c=[0.0, 0.0, width], direction=1)
    wallTop = shapes.Rhomboid(corner=[-width, -width, boxZ], a=[boxX+2*width, 0.0, 0.0], b=[0.0, boxY+2*width, 0.0], c=[0.0, 0.0, width], direction=1)
    wallBack = shapes.Rhomboid(corner=[-width, boxY, -width], a=[boxX+2*width, 0.0, 0.0], b=[0.0, width, 0.0], c=[0.0, 0.0, boxZ+2*width], direction=1)
    wallFront = shapes.Rhomboid(corner=[-width, -width, -width], a=[boxX+2*width, 0.0, 0.0], b=[0.0, width, 0.0], c=[0.0, 0.0, boxZ+2*width], direction=1)
    horizBottom = shapes.Rhomboid(corner=[A_x, A_y, A_z], a=[ah, 0, 0],    b=[0, bh, 0], c=[0, 0, ch], direction = 1)
    horizTop = shapes.Rhomboid(corner=[C_x, C_y, C_z], a=[ah, 0, 0],   b=[0, bh, 0], c=[0, 0, ch], direction = 1)
    verticLeft = shapes.Rhomboid(corner=[A_x, A_y, A_z], a=[av, 0, 0], b=[0, bv, 0], c=[0, 0, cv], direction = 1)
    verticRight = shapes.Rhomboid(corner=[B_x, B_y, B_z], a=[av, 0, 0],   b=[0, bv, 0], c=[0, 0, cv], direction = 1)

    entranceLeft = shapes.Rhomboid(corner=[L_x - (np.sqrt(3) / 2)*polomer + width, L_y , L_z], a=[odvesna, -odvesna, 0], b=[odvesna, 0, 0], c=[0, 0, vyska], direction=1)
    entranceRight = shapes.Rhomboid(corner=[R_x - (np.sqrt(3) / 2)*polomer + width, R_y, R_z], a=[odvesna, 0, 0], b=[odvesna, odvesna, 0], c=[0, 0, vyska], direction=1)

    entrCylLeft = shapes.Cylinder(center=[Cl_x, Cl_y, Cl_z], axis=[0, 0, 1], length=boxZ + 2*width, radius=polomer, direction=1)
    entrCylRight = shapes.Cylinder(center=[Cr_x, Cr_y, Cr_z], axis=[0, 0, 1], length=boxZ + 2*width, radius=polomer, direction=1)

    exitLeft = shapes.Rhomboid(corner=[L_x + ax + odvesna - width + (np.sqrt(3) / 2)*polomer, L_y , L_z], a=[-odvesna, -odvesna, 0], b=[odvesna, 0, 0], c=[0, 0, vyska], direction=1)
    exitRight = shapes.Rhomboid(corner=[R_x + ax + odvesna - width + (np.sqrt(3) / 2)*polomer, R_y , R_z], a=[odvesna, 0, 0], b=[-odvesna, odvesna, 0], c=[0, 0, vyska], direction=1)

    exitCylLeft = shapes.Cylinder(center=[Cl_x + ax, Cl_y, Cl_z], axis=[0, 0, 1], length=boxZ + 2*width, radius=polomer, direction=1)
    exitCylRight = shapes.Cylinder(center=[Cr_x + ax, Cr_y, Cr_z], axis=[0, 0, 1], length=boxZ + 2*width, radius=polomer, direction=1)

    oif.output_vtk_rhomboid(rhom_shape=wallBottom, out_file=vtk_directory + "/wallBottom.vtk")
    oif.output_vtk_rhomboid(rhom_shape=wallTop, out_file=vtk_directory + "/wallTop.vtk")
    oif.output_vtk_rhomboid(rhom_shape=wallBack, out_file=vtk_directory + "/wallBack.vtk")
    oif.output_vtk_rhomboid(rhom_shape=wallFront, out_file=vtk_directory + "/wallFront.vtk")
    oif.output_vtk_rhomboid(rhom_shape=horizBottom, out_file=vtk_directory + "/horizBottom.vtk")
    oif.output_vtk_rhomboid(rhom_shape=horizTop, out_file=vtk_directory + "/horizTop.vtk")
    oif.output_vtk_rhomboid(rhom_shape=verticLeft, out_file=vtk_directory + "/verticLeft.vtk")
    oif.output_vtk_rhomboid(rhom_shape=verticRight, out_file=vtk_directory + "/verticRight.vtk")

    oif.output_vtk_rhomboid(rhom_shape=entranceLeft, out_file=vtk_directory + "/entranceLeft.vtk")
    oif.output_vtk_rhomboid(rhom_shape=entranceRight, out_file=vtk_directory + "/entranceRight.vtk")

    oif.output_vtk_cylinder(cyl_shape=entrCylLeft, n=20, out_file=vtk_directory + "/entrCylLeft.vtk")
    oif.output_vtk_cylinder(cyl_shape=entrCylRight, n=20, out_file=vtk_directory + "/entrCylRight.vtk")

    oif.output_vtk_rhomboid(rhom_shape=exitLeft, out_file=vtk_directory + "/exitLeft.vtk")
    oif.output_vtk_rhomboid(rhom_shape=exitRight, out_file=vtk_directory + "/exitRight.vtk")

    oif.output_vtk_cylinder(cyl_shape=exitCylLeft, n=20, out_file=vtk_directory + "/exitCylLeft.vtk")
    oif.output_vtk_cylinder(cyl_shape=exitCylRight, n=20, out_file=vtk_directory + "/exitCylRight.vtk")

    boundaries.append(wallBottom)
    boundaries.append(wallTop)
    boundaries.append(wallBack)
    boundaries.append(wallFront)
    boundaries.append(horizBottom)
    boundaries.append(horizTop)
    boundaries.append(verticLeft)
    boundaries.append(verticRight)
    boundaries.append(entranceLeft)
    boundaries.append(entranceRight)
    boundaries.append(entrCylLeft)
    boundaries.append(entrCylRight)
    boundaries.append(exitLeft)
    boundaries.append(exitRight)
    boundaries.append(exitCylLeft)
    boundaries.append(exitCylRight)

    return 0


import time
import pyfirmata

current_time = time.localtime(time.time())
#Note Monday is day 0
print("Day of the week:", current_time.tm_wday)
print("Current Hour:", current_time.tm_hour)
print("Minute of the hour:", current_time.tm_min)

def isRightDay(userDay):
    if userDay == current_time.tm_wday:
        return True
    else:
        return False

def isRightTime(userTime1, userTime2):
    if userTime1 <= current_time.tm_hour <= userTime2:
        return True
    else:
        return False

#Checks if can pills given the day, and two time period in which the method returns true
def canDispense(userDay, userTime1, userTime2):
    if(isRightDay(userDay) == True and isRightTime(userTime1, userTime2) == True):
        return True
    else:
        return False

print("Checking Date:", isRightDay(3))
print("Checking Time:", isRightTime(10,14))
print("Can Disense?:", canDispense(2,12,14))
print("Can Disense?:", canDispense(3,10,12))
print("Can Disense?:", canDispense(3,12,14))


# source : https://leetcode.com/problems/climbing-stairs/

class Solution:
    def climbStairs(self, n):

        if n <= 2:
            return n

        dp = [0 for i in range(n+1)]
        dp[0] = 0 # 없는 값이지만 계산을 쉽게 하기 위해 0으로 초기화
        dp[1] = 1
        dp[2] = 2

        for i in range(3, n+1):
            dp[i] = dp[i - 1] + dp[i - 2]

        return dp[n]


# -*- coding: utf-8 -*-
import os
import xmltodict
import json
import xml.etree.ElementTree as ET
from utils.fileUtil import append_json, write_json

def remove_xml_special_chars(d):
    result = {}
    for key, value in d.items():
        if isinstance(value, dict):
            value = remove_xml_special_chars(value)
        elif isinstance(value, list):
            value = [remove_xml_special_chars(x) if isinstance(x, dict) else x for x in value]

        # 去掉其中的命名空间
        if ':' in key:
            new_key = key[key.index(':') + 1:]
            result[new_key] = value
        elif ('@' in key) or ('#' in key):
            new_key = key.replace('#', '').replace('@', '')
            result[new_key] = value
    return result

# 定义xml转json的函数
def xmltojson(xmlstr):
    # parse是的xml解析器
    xmlparse = xmltodict.parse(xmlstr)
    parse_dict = remove_xml_special_chars(xmlparse)
    # print(parse_dict)
    # json库dumps()是将dict转化成json格式，loads()是将json转化成dict格式。
    # dumps()方法的ident=1，格式化json
    jsonstr = json.dumps(parse_dict, ensure_ascii=False)
    return jsonstr

def readXml(filepath, loop_xpath, ns):
    '''read xml by elementTree
    input: xml filepath
    output: xml linelist to csv'''

    try:
        # prase to tree
        tree = ET.parse(filepath)
    except:
        print('xml损坏无法解析：', filepath)
        return None

    # loop_xpath
    root = tree.getroot()
    nodes = root.findall(loop_xpath, ns)
    # print(list(nodes))
    return [ET.tostring(node, encoding='utf-8', method='xml') for node in nodes]

def parse_xml_part(xml_ele_str):
    return xmltojson(xml_ele_str)

def handle_one_xml(xml_path):
    xml_name = os.path.basename(xml_path)
    xml_name_noext = os.path.splitext(xml_name)[0]
    # 读取xml
    nodes = readXml(xml_path, loop_xpath, ns)
    first_time = True
    for node in nodes:
        # 将该node转为json
        json_str = parse_xml_part(node)
        json_file = '%s/%s.json' % (json_dir, xml_name_noext)
        # 第一次覆盖写入，以后append进去
        if first_time:
            write_json(json_str, json_file)
            first_time = False
        else:
            append_json(json_str, json_file)

if __name__ == '__main__':
    # xml文件中一个里面有500个项目数据，需要先拆分开，然后使用xmltodict转为json，并保存下来
    # 配置
    xml_dir = r'F:\全球项目库数据\280_xml_3'
    json_dir = r'F:\全球项目库数据\json_all'
    ns = {'istic': 'http://matadata.istic.ac.cn/elements/2019',
          'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
          'xsd': 'http://www.w3.org/2001/XMLSchema'}
    loop_xpath = './istic:ProjectData/istic:Project'

    for base_dir, dir_names, xml_names in os.walk(xml_dir):
        for xml_name in xml_names:
            xml_path = os.path.join(base_dir, xml_name)
            handle_one_xml(xml_path)


#https://www.acmicpc.net/problem/2655
# 백준 2655, 가장 높은 탑 쌓기

#테스트용 입력
import os
file = open(os.path.join(os.path.dirname(__file__), 'data.txt'), 'r')

# 난이도 : 상
# 동적프로그래밍, LIS
# 50분

""" 해결 아이디어
벽돌의 번호를 출력해야 하므로, 계산된 테이블을 역추적해야함

1. 벽돌을 ㄱ무게 기준 정렬
2. D[i] = 인덱스가 i인 벽돌을 가장 아래에 두었을 때의 최대 높이
3. 각 벽돌에 대해 확인하며 D[i] 갱신
4. 모든 0 <= j < i 에 대해 D[i]] = max (D[i],D[j] + height[i]) if area[i] > area[j])
                                    현재 보고있는 벽돌이 넓이가 더 넓다면 높이를 업데이트

점화식 자체가 이해안됨

"""

"""
제출용 입력
import sys
file = sys.stdin
"""

n = int(file.readline().replace('\n',''))
array = []

array.append((0,0,0,0))

for i in range(1, n + 1):
  area, height, weight = map(int, file.readline().replace('\n','').split())
  array.append((i, area, height, weight))

# 무게를 기준으로 정렬
array.sort(key=lambda data:data[3])

dp = [0] * (n+1)

#매 벽돌마다 비교해서 테이블 바꿔줌
for i in range(1, n + 1):
  for j in range(0, i):
    if array[i][1] > array[j][1]: # 넓을때만
      dp[i] = max(dp[i], dp[j] + array[i][2])
max_value = max(dp) #역추적
index = n
result = []

#어떻게 벽돌 쌓아야되는지
while index != 0:
  if max_value == dp[index]:
    result.append(array[index][0])
    max_value -= array[index][2]

  index -= 1

result.reverse()
print(len(result))
[print(i) for i in result] #벽돌번호 출력


from django.urls import path
from cities import views

app_name = 'cities'

urlpatterns = [
    # path('', views.home, name='home'),
    path('', views.CityListView.as_view(), name='home'),
    path('detail/<int:pk>/', views.CityDetailView.as_view(), name='detail'),
    path('update/<int:pk>/', views.CityUpdateView.as_view(), name='update'),
    path('delete/<int:pk>/', views.CityDeleteView.as_view(), name='delete'),
    path('add', views.CityCreateView.as_view(), name='create'),
]


"""
This program receives a DNA string and presents a group of four integers (separated by spaces)
counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s.

A = adenine
C = cytosine
G = guanine
T = thymine
"""

dna = input('Input your DNA string: ')
dna_index = {'A': 0, 'C': 0, 'G': 0, 'T': 0}

for i in dna:
    dna_index[i] = dna_index[i] + 1

"""
Used the * at the beginning of dna_index to remove the dict structure
In other words, if I had use print (dna_index.values()) the program would present:
dict_values([20, 12, 17, 21])
"""
print(*dna_index.values())


# 이야기의 진실을 아는 사람이 있을 경우
# 어떤 사람이 어떤 파티에서는 진실, 다른 파티에서는 거짓을 들을 경우

N, M = list(map(int, input().split()))
true_know = list(map(int, input().split()))
if len(true_know) == 0:
    know = []
else:
    know = true_know[1:] # 이야기의 진실을 아는 사람의 번호

party = []
for _ in range(M):
    people = list(map(int, input().split()))
    party.append(people[1:])

# 겹치는 people들을 묶어서 know list 만들기
before_know = []
while True:
    for p in party:
        talk = False
        for people in p:
            if people in know:
                talk = True
                break

        if talk:
            know += p
        know = list(set(know))

    if before_know == know:
        break
    else:
        before_know = know.copy()

# 하나씩 돌면서 know_list에 없으면 count
cnt = 0
for p in party:
    talk = False
    for people in p:
        if people in know:
            talk = True
            break

    if talk:
        continue
    else:
        cnt += 1

print(cnt)


import numpy as np

if __name__ == "__main__":
    x = np.linspace(-10, 10, 50)

    # masking
    mask = (0 < x) & (x < 3)  # [F, T, F, T ....]

    # filter values from x with mask
    x_filter = x[mask]
    print(x_filter)

    # get indexs of the filter
    print(np.where(mask)[0])