# coding=UTF-8
#############################################
#1.对输入序列进行截断，根据中心位点为K、P、R、T，分为27长度的序列
#2.提取特征，CC和9PCP
#3.根据排好序的fscore文件，对特征文件进行排序
#############################################
def getSampleSequenceFile(inSeqFile, aaLabel):
    """对输入序列进行截断
        1个 seq 对应 多个27长度的样本seq
        并判断是否包含非法字符
        return 生成的文件名， 源文件的注释， 源文件的序列
    """
    file_path = os.getcwd()#获得当前工作目录
    prefix_name = file_path + "/output/" + os.path.basename(inSeqFile).split('.')[0]
    outFile =  prefix_name + "_seq.txt"

    g = open(outFile, 'w')
    f = open(inSeqFile)
    noteLine = ""
    for eachline in f:
        if eachline[0] == ">":
            noteLine = eachline.strip()
        else:
            if noteLine != "":
                sequence = eachline.strip()
                sequence = sequence.upper() #转换为大写字母
                #判断序列是否含有非法字符
                eachline = str(sequence)
                pattern1 =  re.findall(r'B',eachline)
                pattern2 =  re.findall(r'J',eachline)
                pattern3 =  re.findall(r'O',eachline)
                pattern4 =  re.findall(r'Z',eachline)
                pattern5 =  re.findall(r'U',eachline)
                if pattern1 or pattern2 or pattern3 or pattern4 or pattern5:
                    print('ERROR: The sequence of %s contains illegal characters: B, J, O, Z or U. Please check it!'%(noteLine))
                    continue

                for i in range(len(sequence)):
                    if sequence[i] == aaLabel:
                        if i < 13 and i < len(sequence)-13:
                            seq = 'X'*(13-i) + sequence[:i] + sequence[i: i+13+1]
                        elif i > len(sequence)-13 and i>13:
                            seq = sequence[i-13:i] + sequence[i:] + 'X'*(13-(len(sequence)-i)+1)
                        else:
                            seq = sequence[i-13: i+13+1]

                        if len(seq)==27:
                            g.write(noteLine)
                            g.write(" Postion:%d is %s\n"%(i+1, aaLabel))
                            g.write(seq+"\n")

    g.close()

    f.close()
    return outFile, noteLine, sequence

def ObtainCCAndPCPFeature(inputfile,PCPFile):
######################################第一部分：提取CC特征#########################################
######################提取序列坐标,生成各组氨基酸的xyz均值以及所有组的xyz均值########################
    lst = []
    num_seq = 0
    f=open(inputfile,'r')
    for line in f:
        if line.startswith('>'):
            num_seq+=1
        else:
            line = line.upper()
            line = line.strip('\n\r')
            seq_length = len(line)
            F1=F2=F3=F4=F5=F6=F7=F8=F9=F10=F11=F12=F13=F14=F15=F16=F17=F18=F19=F20=0
            for i in range(0,len(line)):
                if line[i] == 'A':
                    F1 += 1
                elif line[i] == 'V':
                    F2 += 1
                elif line[i] == 'L':
                    F3 += 1
                elif line[i] == 'I':
                    F4 += 1
                elif line[i] == 'P':
                    F5 += 1
                elif line[i] == 'F':
                    F6 += 1
                elif line[i] == 'W':
                    F7 += 1
                elif line[i] == 'M':
                    F8 += 1
                elif line[i] == 'G':
                    F9 += 1
                elif line[i] == 'S':
                    F10 += 1
                elif line[i] == 'T':
                    F11 += 1
                elif line[i] == 'C':
                    F12 += 1
                elif line[i] == 'Y':
                    F13 += 1
                elif line[i] == 'N':
                    F14 += 1
                elif line[i] == 'Q':
                    F15 += 1
                elif line[i] == 'K':
                    F16 += 1
                elif line[i] == 'R':
                    F17 += 1
                elif line[i] == 'H':
                    F18 += 1
                elif line[i] == 'D':
                    F19 += 1
                elif line[i] == 'E':
                    F20 += 1
            Type1Xvalue=F1*(-36.6794)+F2*(-66.6159)+F3*(-94.4033)+F4*(-100.0599)+F5*(-84.6835)+F6*(-101.0966)+F7*(-12.5874)+F8*(-111.3198)
            Type1Yvalue=F1*(58.8302)+F2*(62.1625)+F3*(38.8595)+F4*(20.2361)+F5*(29.1446)+F6*(-79.3826)+F7*(-158.3870)+F8*(-32.9407)
            Type1Zvalue=F1*(-55.9682)+F2*(-73.5564)+F3*(-82.4134)+F4*(-82.4134)+F5*(-72.3001)+F6*(-103.7705)+F7*(-128.2684)+F8*(-93.7201)
            Type2Xvalue=F9*(-24.7561)+F10*(-43.6432)+F11*(-25.2154)+F12*(-52.4159)+F13*(-53.3563)+F14*(-44.2471)+F15*(-65.6344)
            Type2Yvalue=F9*(26.2092)+F10*(25.3163)+F11*(51.3147)+F12*(-25.2563)+F13*(-68.7011)+F14*(-45.4289)+F15*(-24.8605)
            Type2Zvalue=F9*(65.8804)+F10*(92.1974)+F11*(104.4787)+F12*(106.3209)+F13*(158.9550)+F14*(115.8828)+F15*(128.2518)
            Type3Xvalue=F16*(-3.6804)+F17*(-2.1627)+F18*(-0.6273)
            Type3Yvalue=F16*(-1.8878)+F17*(-4.4286)+F18*(4.3459)
            Type3Zvalue=F16*(-146.1415)+F17*(-174.1303)+F18*(-155.1379)
            Type4Xvalue=F19*(-15.3220)+F20*(-16.9336)
            Type4Yvalue=F19*(43.3370)+F20*(-47.8954)
            Type4Zvalue=F19*(-124.9110)+F20*(-138.0496)
            Type1Xmean=Type1Xvalue/8
            Type1Ymean=Type1Yvalue/8
            Type1Zmean=Type1Zvalue/8
            Type2Xmean=Type2Xvalue/7
            Type2Ymean=Type2Yvalue/7
            Type2Zmean=Type2Zvalue/7
            Type3Xmean=Type3Xvalue/3
            Type3Ymean=Type3Yvalue/3
            Type3Zmean=Type3Zvalue/3
            Type4Xmean=Type4Xvalue/2
            Type4Ymean=Type4Yvalue/2
            Type4Zmean=Type4Zvalue/2
            AllXmean=(Type1Xvalue+Type2Xvalue+Type3Xvalue+Type4Xvalue)/seq_length
            AllYmean=(Type1Yvalue+Type2Yvalue+Type3Yvalue+Type4Yvalue)/seq_length
            AllZmean=(Type1Zvalue+Type2Zvalue+Type3Zvalue+Type4Zvalue)/seq_length

            lst.append(Type1Xmean)
            lst.append(Type1Ymean)
            lst.append(Type1Zmean)
            lst.append(Type2Xmean)
            lst.append(Type2Ymean)
            lst.append(Type2Zmean)
            lst.append(Type3Xmean)
            lst.append(Type3Ymean)
            lst.append(Type3Zmean)
            lst.append(Type4Xmean)
            lst.append(Type4Ymean)
            lst.append(Type4Zmean)
            lst.append(AllXmean)
            lst.append(AllYmean)
            lst.append(AllZmean)
    cc = np.array(lst).reshape(num_seq,15)
    f.close()
###########################提取累积几何中心特征###############################
################第一步，将每条序列中每个氨基酸用空间坐标表示##################
    lst1 = []
    lst2 = []
    lst3 = []
    num_seq = 0
    f=open(inputfile,'r')
    for line in f:
        if line.startswith('>'):
            num_seq+=1
        else:
            line = line.upper()        #将碱基序列转换成大写
            line = line.strip('\n\r')
            for i in range(0,len(line)):
                if line[i] == 'A':
                    sx='-36.6794'
                    sy='58.8302'
                    sz='-55.9682'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'V':
                    sx='-66.6159'
                    sy='62.1625'
                    sz='73.5564'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'L':
                    sx='-94.4003'
                    sy='38.8595'
                    sz='-82.4134'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'I':
                    sx='-100.5090'
                    sy='20.2361'
                    sz='-82.4134'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'P':
                    sx='-84.6835'
                    sy='29.1446'
                    sz='-72.3001'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'F':
                    sx='-101.0996'
                    sy='-79.3826'
                    sz='-103.7705'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'W':
                    sx='-12.5874'
                    sy='-158.3870'
                    sz='-128.2684'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'M':
                    sx='-111.3198'
                    sy='-32.9407'
                    sz='-93.7201'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'G':
                    sx='-24.7561'
                    sy='26.2092'
                    sz='65.8804'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'S':
                    sx='-43.6432'
                    sy='25.313163'
                    sz='92.1974'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'T':
                    sx='-25.2154'
                    sy='51.3147'
                    sz='104.3787'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'C':
                    sx='-51.4159'
                    sy='-25.2563'
                    sz='106.3209'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'Y':
                    sx='-53.3563'
                    sy='-68.7011'
                    sz='158.9550'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'N':
                    sx='-44.2471'
                    sy='-45.4280'
                    sz='115.8828'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'Q':
                    sx='-65.6344'
                    sy='-24.8605'
                    sz='128.2518'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'K':
                    sx='-3.6804'
                    sy='-1.8878'
                    sz='-146.1415'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'R':
                    sx='-2.1627'
                    sy='-4.4286'
                    sz='-174.1303'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'H':
                    sx='-0.6273'
                    sy='4.3459'
                    sz='-155.1379'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'D':
                    sx='-15.3220'
                    sy='43.3370'
                    sz='-124.9110'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

                elif line[i] == 'E':
                    sx='-16.9336'
                    sy='-47.8954'
                    sz='-138.0496'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)
                elif line[i] == 'X':
                    sx='0'
                    sy='0'
                    sz='0'
                    lst1.append(sx)
                    lst2.append(sy)
                    lst3.append(sz)

    Dx = np.array(lst1).reshape(num_seq,27)
    Dy = np.array(lst2).reshape(num_seq,27)
    Dz = np.array(lst3).reshape(num_seq,27)
    f.close()

##########第二步，将每条序列中的每个坐标分量的累加求和再取均值，计算出各分量的累加坐标平均值################
    #x分量的累计平均值
    Dax = []
    for i in range(0,Dx.shape[0]):
        s=[0]*Dx.shape[1]
        s[0]=float(Dx[i][0])
        for j in range(1,Dx.shape[1]):
            s[j]=s[j-1]+float(Dx[i][j])
        ax=sum(s)/Dx.shape[1]
        Dax.append(ax)
    Dax = np.array(Dax)
    Dax = Dax.reshape(Dx.shape[0],1)

    #y分量的累计平均值
    Day = []
    for i in range(0,Dy.shape[0]):
        s=[0]*Dy.shape[1]
        s[0]=float(Dy[i][0])
        for j in range(1,Dx.shape[1]):
            s[j]=s[j-1]+float(Dy[i][j])
        ay=sum(s)/Dy.shape[1]
        Day.append(ay)
    Day = np.array(Day)
    Day = Day.reshape(Dy.shape[0],1)

    #z分量的累计平均值
    Daz = []
    for i in range(0,Dz.shape[0]):
        s=[0]*Dz.shape[1]
        s[0]=float(Dz[i][0])
        for j in range(1,Dz.shape[1]):
            s[j]=s[j-1]+float(Dz[i][j])
        az=sum(s)/Dz.shape[1]
        Daz.append(az)
    Daz = np.array(Daz)
    Daz = Daz.reshape(Dz.shape[0],1)
#################第三步，将上述坐标分量合并，每条序列都用一个18维向量表示###############
    CCFeaValue = np.hstack((cc,Dax,Day,Daz))
    df_CCFeaValue = pd.DataFrame(CCFeaValue)
    df_CCFeaValue.columns = ['Type1Xmean','Type1Ymean','Type1Zmean',
                         'Type2Xmean','Type2Ymean','Type2Zmean',
                         'Type3Xmean','Type3Ymean','Type3Zmean',
                         'Type4Xmean','Type4Ymean','Type4Zmean',
                         'AllXmean','AllYmean','AllZmean',
                         'Leiji_xmean','Leiji_ymean','Leiji_zmean']
######################################第二部分：提取9_PCPs特征##########################################
    nine = pd.read_csv(PCPFile,sep='\t')
    seq=[]
    f=open(inputfile,'r')
    for line in f:
        line=line.strip('\n')
        if line.startswith('>'):
            pass
        else:
            seq.append(line)
    f.close()

    #第一种理化性质
    a1 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a1[i,j]= nine['A'][0]

            elif  seq[i][j]== 'C':
                a1[i,j]= nine['C'][0]

            elif  seq[i][j]== 'D':
                a1[i,j]= nine['D'][0]

            elif  seq[i][j]== 'E':
                a1[i,j]= nine['E'][0]

            elif  seq[i][j]== 'F':
                a1[i,j]= nine['F'][0]

            elif  seq[i][j]== 'G':
                a1[i,j]= nine['G'][0]

            elif  seq[i][j]== 'H':
                a1[i,j]= nine['H'][0]

            elif  seq[i][j]== 'I':
                a1[i,j]= nine['I'][0]

            elif  seq[i][j]== 'K':
                a1[i,j]= nine['K'][0]

            elif  seq[i][j]== 'L':
                a1[i,j]= nine['L'][0]

            elif  seq[i][j]== 'M':
                a1[i,j]= nine['M'][0]

            elif  seq[i][j]== 'N':
                a1[i,j]= nine['N'][0]

            elif  seq[i][j]== 'P':
                a1[i,j]= nine['P'][0]

            elif  seq[i][j]== 'Q':
                a1[i,j]= nine['Q'][0]

            elif  seq[i][j]== 'R':
                a1[i,j]= nine['R'][0]

            elif  seq[i][j]== 'S':
                a1[i,j]= nine['S'][0]

            elif  seq[i][j]== 'T':
                a1[i,j]= nine['T'][0]

            elif  seq[i][j]== 'V':
                a1[i,j]= nine['V'][0]

            elif  seq[i][j]== 'W':
                a1[i,j]= nine['W'][0]

            elif  seq[i][j]== 'Y':
                a1[i,j]= nine['Y'][0]

            elif  seq[i][j]== 'X':
                a1[i,j]= 0

    col_name = []
    df1 = pd.DataFrame(a1)
    for j in range(1,28):
        col_name.append('Hydrophobicity_%s' %j)
    df1.columns = col_name

    #第二种理化性质
    a2 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a2[i,j]= nine['A'][1]

            elif  seq[i][j]== 'C':
                a2[i,j]= nine['C'][1]

            elif  seq[i][j]== 'D':
                a2[i,j]= nine['D'][1]

            elif  seq[i][j]== 'E':
                a2[i,j]= nine['E'][1]

            elif  seq[i][j]== 'F':
                a2[i,j]= nine['F'][1]

            elif  seq[i][j]== 'G':
                a2[i,j]= nine['G'][1]

            elif  seq[i][j]== 'H':
                a2[i,j]= nine['H'][1]

            elif  seq[i][j]== 'I':
                a2[i,j]= nine['I'][1]

            elif  seq[i][j]== 'K':
                a2[i,j]= nine['K'][1]

            elif  seq[i][j]== 'L':
                a2[i,j]= nine['L'][1]

            elif  seq[i][j]== 'M':
                a2[i,j]= nine['M'][1]

            elif  seq[i][j]== 'N':
                a2[i,j]= nine['N'][1]

            elif  seq[i][j]== 'P':
                a2[i,j]= nine['P'][1]

            elif  seq[i][j]== 'Q':
                a2[i,j]= nine['Q'][1]

            elif  seq[i][j]== 'R':
                a2[i,j]= nine['R'][1]

            elif  seq[i][j]== 'S':
                a2[i,j]= nine['S'][1]

            elif  seq[i][j]== 'T':
                a2[i,j]= nine['T'][1]

            elif  seq[i][j]== 'V':
                a2[i,j]= nine['V'][1]

            elif  seq[i][j]== 'W':
                a2[i,j]= nine['W'][1]

            elif  seq[i][j]== 'Y':
                a2[i,j]= nine['Y'][1]

            elif  seq[i][j]== 'X':
                a2[i,j]= 0

    col_name = []
    df2 = pd.DataFrame(a2)
    for j in range(1,28):
        col_name.append('Hydrophilicity_%s' %j)
    df2.columns = col_name

    #第三种理化性质
    a3 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a3[i,j]= nine['A'][2]

            elif  seq[i][j]== 'C':
                a3[i,j]= nine['C'][2]

            elif  seq[i][j]== 'D':
                a3[i,j]= nine['D'][2]

            elif  seq[i][j]== 'E':
                a3[i,j]= nine['E'][2]

            elif  seq[i][j]== 'F':
                a3[i,j]= nine['F'][2]

            elif  seq[i][j]== 'G':
                a3[i,j]= nine['G'][2]

            elif  seq[i][j]== 'H':
                a3[i,j]= nine['H'][2]

            elif  seq[i][j]== 'I':
                a3[i,j]= nine['I'][2]

            elif  seq[i][j]== 'K':
                a3[i,j]= nine['K'][2]

            elif  seq[i][j]== 'L':
                a3[i,j]= nine['L'][2]

            elif  seq[i][j]== 'M':
                a3[i,j]= nine['M'][2]

            elif  seq[i][j]== 'N':
                a3[i,j]= nine['N'][2]

            elif  seq[i][j]== 'P':
                a3[i,j]= nine['P'][2]

            elif  seq[i][j]== 'Q':
                a3[i,j]= nine['Q'][2]

            elif  seq[i][j]== 'R':
                a3[i,j]= nine['R'][2]

            elif  seq[i][j]== 'S':
                a3[i,j]= nine['S'][2]

            elif  seq[i][j]== 'T':
                a3[i,j]= nine['T'][2]

            elif  seq[i][j]== 'V':
                a3[i,j]= nine['V'][2]

            elif  seq[i][j]== 'W':
                a3[i,j]= nine['W'][2]

            elif  seq[i][j]== 'Y':
                a3[i,j]= nine['Y'][2]

            elif  seq[i][j]== 'X':
                a3[i,j]= 0

    col_name = []
    df3 = pd.DataFrame(a3)
    for j in range(1,28):
        col_name.append('Mass_%s' %j)
    df3.columns = col_name

    #第四种理化性质
    a4 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a4[i,j]= nine['A'][3]

            elif  seq[i][j]== 'C':
                a4[i,j]= nine['C'][3]

            elif  seq[i][j]== 'D':
                a4[i,j]= nine['D'][3]

            elif  seq[i][j]== 'E':
                a4[i,j]= nine['E'][3]

            elif  seq[i][j]== 'F':
                a4[i,j]= nine['F'][3]

            elif  seq[i][j]== 'G':
                a4[i,j]= nine['G'][3]

            elif  seq[i][j]== 'H':
                a4[i,j]= nine['H'][3]

            elif  seq[i][j]== 'I':
                a4[i,j]= nine['I'][3]

            elif  seq[i][j]== 'K':
                a4[i,j]= nine['K'][3]

            elif  seq[i][j]== 'L':
                a4[i,j]= nine['L'][3]

            elif  seq[i][j]== 'M':
                a4[i,j]= nine['M'][3]

            elif  seq[i][j]== 'N':
                a4[i,j]= nine['N'][3]

            elif  seq[i][j]== 'P':
                a4[i,j]= nine['P'][3]

            elif  seq[i][j]== 'Q':
                a4[i,j]= nine['Q'][3]

            elif  seq[i][j]== 'R':
                a4[i,j]= nine['R'][3]

            elif  seq[i][j]== 'S':
                a4[i,j]= nine['S'][3]

            elif  seq[i][j]== 'T':
                a4[i,j]= nine['T'][3]

            elif  seq[i][j]== 'V':
                a4[i,j]= nine['V'][3]

            elif  seq[i][j]== 'W':
                a4[i,j]= nine['W'][3]

            elif  seq[i][j]== 'Y':
                a4[i,j]= nine['Y'][3]

            elif  seq[i][j]== 'X':
                a4[i,j]= 0

    col_name = []
    df4 = pd.DataFrame(a4)
    for j in range(1,28):
        col_name.append('pK1_%s' %j)
    df4.columns = col_name

    #第五种理化性质
    a5 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a5[i,j]= nine['A'][4]

            elif  seq[i][j]== 'C':
                a5[i,j]= nine['C'][4]

            elif  seq[i][j]== 'D':
                a5[i,j]= nine['D'][4]

            elif  seq[i][j]== 'E':
                a5[i,j]= nine['E'][4]

            elif  seq[i][j]== 'F':
                a5[i,j]= nine['F'][4]

            elif  seq[i][j]== 'G':
                a5[i,j]= nine['G'][4]

            elif  seq[i][j]== 'H':
                a5[i,j]= nine['H'][4]

            elif  seq[i][j]== 'I':
                a5[i,j]= nine['I'][4]

            elif  seq[i][j]== 'K':
                a5[i,j]= nine['K'][4]

            elif  seq[i][j]== 'L':
                a5[i,j]= nine['L'][4]

            elif  seq[i][j]== 'M':
                a5[i,j]= nine['M'][4]

            elif  seq[i][j]== 'N':
                a5[i,j]= nine['N'][4]

            elif  seq[i][j]== 'P':
                a5[i,j]= nine['P'][4]

            elif  seq[i][j]== 'Q':
                a5[i,j]= nine['Q'][4]

            elif  seq[i][j]== 'R':
                a5[i,j]= nine['R'][4]

            elif  seq[i][j]== 'S':
                a5[i,j]= nine['S'][4]

            elif  seq[i][j]== 'T':
                a5[i,j]= nine['T'][4]

            elif  seq[i][j]== 'V':
                a5[i,j]= nine['V'][4]

            elif  seq[i][j]== 'W':
                a5[i,j]= nine['W'][4]

            elif  seq[i][j]== 'Y':
                a5[i,j]= nine['Y'][4]

            elif  seq[i][j]== 'X':
                a5[i,j]= 0

    col_name = []
    df5 = pd.DataFrame(a5)
    for j in range(1,28):
        col_name.append('pK2_%s' %j)
    df5.columns = col_name

    #第六种理化性质
    a6 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a6[i,j]= nine['A'][5]

            elif  seq[i][j]== 'C':
                a6[i,j]= nine['C'][5]

            elif  seq[i][j]== 'D':
                a6[i,j]= nine['D'][5]

            elif  seq[i][j]== 'E':
                a6[i,j]= nine['E'][5]

            elif  seq[i][j]== 'F':
                a6[i,j]= nine['F'][5]

            elif  seq[i][j]== 'G':
                a6[i,j]= nine['G'][5]

            elif  seq[i][j]== 'H':
                a6[i,j]= nine['H'][5]

            elif  seq[i][j]== 'I':
                a6[i,j]= nine['I'][5]

            elif  seq[i][j]== 'K':
                a6[i,j]= nine['K'][5]

            elif  seq[i][j]== 'L':
                a6[i,j]= nine['L'][5]

            elif  seq[i][j]== 'M':
                a6[i,j]= nine['M'][5]

            elif  seq[i][j]== 'N':
                a6[i,j]= nine['N'][5]

            elif  seq[i][j]== 'P':
                a6[i,j]= nine['P'][5]

            elif  seq[i][j]== 'Q':
                a6[i,j]= nine['Q'][5]

            elif  seq[i][j]== 'R':
                a6[i,j]= nine['R'][5]

            elif  seq[i][j]== 'S':
                a6[i,j]= nine['S'][5]

            elif  seq[i][j]== 'T':
                a6[i,j]= nine['T'][5]

            elif  seq[i][j]== 'V':
                a6[i,j]= nine['V'][5]

            elif  seq[i][j]== 'W':
                a6[i,j]= nine['W'][5]

            elif  seq[i][j]== 'Y':
                a6[i,j]= nine['Y'][5]

            elif  seq[i][j]== 'X':
                a6[i,j]= 0

    col_name = []
    df6 = pd.DataFrame(a6)
    for j in range(1,28):
        col_name.append('pI_%s' %j)
    df6.columns = col_name

    #第七种理化性质
    a7 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a7[i,j]= nine['A'][6]

            elif  seq[i][j]== 'C':
                a7[i,j]= nine['C'][6]

            elif  seq[i][j]== 'D':
                a7[i,j]= nine['D'][6]

            elif  seq[i][j]== 'E':
                a7[i,j]= nine['E'][6]

            elif  seq[i][j]== 'F':
                a7[i,j]= nine['F'][6]

            elif  seq[i][j]== 'G':
                a7[i,j]= nine['G'][6]

            elif  seq[i][j]== 'H':
                a7[i,j]= nine['H'][6]

            elif  seq[i][j]== 'I':
                a7[i,j]= nine['I'][6]

            elif  seq[i][j]== 'K':
                a7[i,j]= nine['K'][6]

            elif  seq[i][j]== 'L':
                a7[i,j]= nine['L'][6]

            elif  seq[i][j]== 'M':
                a7[i,j]= nine['M'][6]

            elif  seq[i][j]== 'N':
                a7[i,j]= nine['N'][6]

            elif  seq[i][j]== 'P':
                a7[i,j]= nine['P'][6]

            elif  seq[i][j]== 'Q':
                a7[i,j]= nine['Q'][6]

            elif  seq[i][j]== 'R':
                a7[i,j]= nine['R'][6]

            elif  seq[i][j]== 'S':
                a7[i,j]= nine['S'][6]

            elif  seq[i][j]== 'T':
                a7[i,j]= nine['T'][6]

            elif  seq[i][j]== 'V':
                a7[i,j]= nine['V'][6]

            elif  seq[i][j]== 'W':
                a7[i,j]= nine['W'][6]

            elif  seq[i][j]== 'Y':
                a7[i,j]= nine['Y'][6]

            elif  seq[i][j]== 'X':
                a7[i,j]= 0

    col_name = []
    df7 = pd.DataFrame(a7)
    for j in range(1,28):
        col_name.append('Rigidity_%s' %j)
    df7.columns = col_name

    #第八种理化性质
    a8 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a8[i,j]= nine['A'][7]

            elif  seq[i][j]== 'C':
                a8[i,j]= nine['C'][7]

            elif  seq[i][j]== 'D':
                a8[i,j]= nine['D'][7]

            elif  seq[i][j]== 'E':
                a8[i,j]= nine['E'][7]

            elif  seq[i][j]== 'F':
                a8[i,j]= nine['F'][7]

            elif  seq[i][j]== 'G':
                a8[i,j]= nine['G'][7]

            elif  seq[i][j]== 'H':
                a8[i,j]= nine['H'][7]

            elif  seq[i][j]== 'I':
                a8[i,j]= nine['I'][7]

            elif  seq[i][j]== 'K':
                a8[i,j]= nine['K'][7]

            elif  seq[i][j]== 'L':
                a8[i,j]= nine['L'][7]

            elif  seq[i][j]== 'M':
                a8[i,j]= nine['M'][7]

            elif  seq[i][j]== 'N':
                a8[i,j]= nine['N'][7]

            elif  seq[i][j]== 'P':
                a8[i,j]= nine['P'][7]

            elif  seq[i][j]== 'Q':
                a8[i,j]= nine['Q'][7]

            elif  seq[i][j]== 'R':
                a8[i,j]= nine['R'][7]

            elif  seq[i][j]== 'S':
                a8[i,j]= nine['S'][7]

            elif  seq[i][j]== 'T':
                a8[i,j]= nine['T'][7]

            elif  seq[i][j]== 'V':
                a8[i,j]= nine['V'][7]

            elif  seq[i][j]== 'W':
                a8[i,j]= nine['W'][7]

            elif  seq[i][j]== 'Y':
                a8[i,j]= nine['Y'][7]

            elif  seq[i][j]== 'X':
                a8[i,j]= 0

    col_name = []
    df8 = pd.DataFrame(a8)
    for j in range(1,28):
        col_name.append('Flexibility_%s' %j)
    df8.columns = col_name

    #第九种理化性质
    a9 = np.zeros(shape=(len(seq),27))
    for i in range(len(seq)):
        for j in range(27):
            if seq[i][j]== 'A':
                a9[i,j]= nine['A'][8]

            elif  seq[i][j]== 'C':
                a9[i,j]= nine['C'][8]

            elif  seq[i][j]== 'D':
                a9[i,j]= nine['D'][8]

            elif  seq[i][j]== 'E':
                a9[i,j]= nine['E'][8]

            elif  seq[i][j]== 'F':
                a9[i,j]= nine['F'][8]

            elif  seq[i][j]== 'G':
                a9[i,j]= nine['G'][8]

            elif  seq[i][j]== 'H':
                a9[i,j]= nine['H'][8]

            elif  seq[i][j]== 'I':
                a9[i,j]= nine['I'][8]

            elif  seq[i][j]== 'K':
                a9[i,j]= nine['K'][8]

            elif  seq[i][j]== 'L':
                a9[i,j]= nine['L'][8]

            elif  seq[i][j]== 'M':
                a9[i,j]= nine['M'][8]

            elif  seq[i][j]== 'N':
                a9[i,j]= nine['N'][8]

            elif  seq[i][j]== 'P':
                a9[i,j]= nine['P'][8]

            elif  seq[i][j]== 'Q':
                a9[i,j]= nine['Q'][8]

            elif  seq[i][j]== 'R':
                a9[i,j]= nine['R'][8]

            elif  seq[i][j]== 'S':
                a9[i,j]= nine['S'][8]

            elif  seq[i][j]== 'T':
                a9[i,j]= nine['T'][8]

            elif  seq[i][j]== 'V':
                a9[i,j]= nine['V'][8]

            elif  seq[i][j]== 'W':
                a9[i,j]= nine['W'][8]

            elif  seq[i][j]== 'Y':
                a9[i,j]= nine['Y'][8]

            elif  seq[i][j]== 'X':
                a9[i,j]= 0

    col_name = []
    df9 = pd.DataFrame(a9)
    for j in range(1,28):
        col_name.append('Irreplaceability_%s' %j)
    df9.columns = col_name
    #按列合并得到所有理化性质值,共27*9=243维
    df_9PCP = pd.concat([df1,df2, df3, df4, df5, df6, df7, df8, df9],axis=1)

###################################第三部分：最后合并两种特征值，为最终特征向量（18+243 = 261维）
    df_CCAndPCPFeature = df_CCFeaValue.join(df_9PCP) #按列合并

    sampleLabels = []
    f = open(inputfile,'r')
    for eachline in f:
        if eachline[0] == '>':
            sampleLabels.append('1')
        else:
            sampleSeq = eachline.strip()
    f.close()

    return df_CCAndPCPFeature, sampleLabels

def getFscoreSortFeatureVector(sortedfile, proLabels):
    """通过特征排序的文件，获得排序的特征向量的 index向量
    """
    f = open(sortedfile,'r')
    fscore = []
    for eachline in f:
        tmp = eachline.split()
        if tmp[0] == "Rank":
            continue
        fscore.append(tmp[1])
    f.close()

    indexList = list(
        map(lambda a: proLabels.index(a), fscore)
        )

    return indexList

import os
import re
import pandas as pd
import numpy as np
#inSeqFile = sys.argv[1] #原始输入序列文件
#aaLabel = sys.argv[2] #pred_type
#PCPFile = sys.argv[3]#理化性质
#sortedfile = sys.argv[4]#.fscore

def main(inSeqFile,aaLabel,PCPFile,sortedfile):
    file_path = os.getcwd()#获得当前工作目录
    prefix_name = file_path + "/output/" + os.path.basename(inSeqFile).split('.')[0]
    outfeaFile = prefix_name + "_fscore_sorted.csv"
    outFile, noteLine, sequence = getSampleSequenceFile(inSeqFile, aaLabel)
    df_CCAndPCPFeature, sampleLabels = ObtainCCAndPCPFeature(outFile,PCPFile)
    FeaVals = df_CCAndPCPFeature.values
    col_name = df_CCAndPCPFeature.columns.values.tolist()
    indexList = getFscoreSortFeatureVector(sortedfile, col_name)
    # 根据F-score排序后的特征index向量，生成csv格式文件，保存在outfeaFile
    g = open(outfeaFile, 'w')
    for i in range(len(sampleLabels)):
        wLine = sampleLabels[i]
        featureList = list(FeaVals[i])
        for j in range(len(indexList)):
            wLine += ",%.6f"%(featureList[indexList[j]])
        g.write(wLine + "\n")

    g.close()


import requests
import re

url = "https://discordrollout.nekos.sh/api/data/status"

def get_info():
    nitro_info = ""
    nonnitro_info = ""

    response = requests.request("GET", url)

    match = re.search(r'"nitro":"([^"]+)"', response.text)
    if match:
        nitro_info = match.group(1)

    match = re.search(r'"nonnitro":"([^"]+)"', response.text)
    if match:
        nonnitro_info = match.group(1)

    complete = nitro_info + "|" + nonnitro_info

    return complete


#!/usr/bin/python3

import intcode
from collections import defaultdict
from screen import display
canvas = defaultdict(lambda: 0)

code = [int(c) for c in open('day13.txt').read().split(',')]
machine = intcode.IntProc(code)
try:
    while True:
        x, y, t = machine.read(3)
        canvas[(x,y)] = t
except intcode.Terminated:
    print(sum(1 for _, t in canvas.items()
              if t == 2))

cmp = lambda a, b: (a > b) - (a < b)

BLANK = 0
WALL = 1
BLOCK = 2
PADDLE = 3
BALL = 4

# part 2
SYMBOLS = {
    BLANK:  ' ',
    WALL:   '#',
    BLOCK:  '*',
    PADDLE: '_',
    BALL:   'O',
}
code[0] = 2
score = 0
ball = 0
paddle = 0
outbuf = []

import asyncio

@intcode.grouped(3)
async def handle_output(x, y, t):
    global score, ball, paddle
    if x == -1 and y == 0:
        score = t
    else:
        canvas[(x,y)] = t
        if t == BALL:
            ball = x
        elif t == PADDLE:
            paddle = x

async def provide_input():
    return cmp(ball, paddle)

cpu = intcode.AsyncIntCode(code, input=provide_input, output=handle_output)
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(cpu.run())
    print(score)
finally:
    loop.close()


"""This module 'ea_operations' encapsulates the necessary evolutionary algorithm (EA) operations for
genetic modifications in GEP, including one/two-point mutation, inversion mutation, transpose
mutation, and recombination between multi-genetic chromosomes.
    **Ref: Ferreira, Cândida. Gene expression programming: mathematical modeling by an artificial
           intelligence. Vol. 21. Springer, 2006 (Chapter 3)
"""
import random

_DEBUG = False

def select_cell(pset):
    return random.choice(pset.cell_symbols)

def select_program(pset):
    return random.choice(pset.ps_functions + pset.ps_terminal)

def cross_one_point(indv1, indv2):
    """Get one-point recombination of two individuals/chromosomes. The operation is performed in
    place, and the two children/chromosomes are returned.
    :param indv1: obj, the first individual as parent_1 in the crossover operation
    :param indv2: obj, the second individual as parent_2 in the crossover operation
    :return: tuple, the two offspring of the parents
    """
    assert len(indv1) == len(indv2), 'Chromosomes must have same # of genes'
    gene_size = len(indv1[0])
    indv_size = len(indv1)
    if indv_size > 1:
        gene = random.randint(0, indv_size - 1)
        cx_pt = random.randint(0, gene_size - 1)
        indv1[gene:], indv2[gene:] = indv2[gene:], indv1[gene:]
        indv1[gene][cx_pt:], indv2[gene][cx_pt:] = indv2[gene][cx_pt:], indv1[gene][cx_pt:]
        if _DEBUG: print('Gene {} crossed at point {}'.format(gene, cx_pt))
    elif indv_size == 1:
        cx_pt = random.randint(0, gene_size - 1)
        indv1[0][cx_pt:], indv2[0][cx_pt:] = indv2[0][cx_pt:], indv1[0][cx_pt:]
        if _DEBUG: print('Genes crossed at point {}'.format(cx_pt))
    return indv1, indv2

def cross_two_point(indv1, indv2):
    """Get two-point recombination of two individuals/chromosomes. The operation is performed in
    place, and the two children/chromosomes are returned.
    :param indv1: obj, the first individual as parent_1 in the crossover operation
    :param indv2: obj, the second individual as parent_2 in the crossover operation
    :return: tuple, the two offspring of the parents
    """
    assert len(indv1) == len(indv2), 'Chromosomes must have same # of genes'
    gene_size = len(indv1[0])
    indv_size = len(indv1)
    if indv_size > 1:
        gene1 = random.randint(0, indv_size - 2)
        gene2 = random.randint(0, indv_size - 1)
        g1_cx_pt = random.randint(0, gene_size - 2)
        g2_cx_pt = random.randint(0, gene_size - 1)
        if gene1 > gene2:
            gene1, gene2 = gene2, gene1
        elif gene1 == gene2:
            gene2 += 1
        if g1_cx_pt > g2_cx_pt:
            g1_cx_pt, g2_cx_pt = g2_cx_pt, g1_cx_pt
        elif g1_cx_pt == g2_cx_pt:
            g2_cx_pt += 1
        indv1[gene1:gene2], indv2[gene1:gene2] = indv2[gene1:gene2], indv1[gene1:gene2]
        indv1[gene1][g1_cx_pt:], indv2[gene1][g1_cx_pt:] = indv2[gene1][g1_cx_pt:], indv1[gene1][g1_cx_pt:]
        indv1[gene2][:g2_cx_pt + 1], indv2[gene2][:g2_cx_pt + 1] = \
            indv2[gene2][:g2_cx_pt + 1], indv1[gene2][:g2_cx_pt + 1]
        if _DEBUG: print('Gene {} and Gene {} crossed at points {} and {} respectively'
                  .format(gene1, gene2, g1_cx_pt, g2_cx_pt))
    elif indv_size == 1:
        cx_pt1 = random.randint(0, gene_size - 2)
        cx_pt2 = random.randint(0, gene_size - 1)
        if cx_pt1 > cx_pt2:
            cx_pt1, cx_pt2 = cx_pt2, cx_pt1
        elif cx_pt1 == cx_pt2:
            cx_pt2 += 1
        indv1[0][cx_pt1:cx_pt2 + 1], indv2[0][cx_pt1:cx_pt2 + 1] = \
            indv2[0][cx_pt1:cx_pt2 + 1], indv1[0][cx_pt1:cx_pt2 + 1]
        if _DEBUG: print('Genes crossed at points {} and {} '.format(cx_pt1, cx_pt2))
    return indv1, indv2

def cross_gene(indv1, indv2):
    """Get gene recombination of two individuals/chromosomes. An entire gene is exchanged between two
    individual parents. The operation is performed in place, and the two children/chromosomes
    are returned.
    :param indv1: obj, the first individual as parent_1 in the crossover operation
    :param indv2: obj, the second individual as parent_2 in the crossover operation
    :return: tuple, the two offspring of the parents
    """
    assert len(indv1) == len(indv2), 'Chromosomes must have same # of genes'
    length = len(indv1)
    if length > 1:
        cx_gene = random.randint(0, length - 1)
        indv1[cx_gene], indv2[cx_gene] = indv2[cx_gene], indv1[cx_gene]
        if _DEBUG: print('Genes at position {} crossed'.format(cx_gene))
    else:
        raise ValueError('Chromosome has only one gene')
    return indv1, indv2

def mutate_uniform(indv, pset, indpb=None):
    """Get uniform mutation of each gene in a chromosome. Each gene's primitive symbols in
    an individual (chromosome) is changed to a randomly selected primitive symbol with a given
    probability (mutation rate). Typically, primitive symbol mutation rate 'indpb' is
    equivalent to two one-point mutations per chromosome. That is, indpb = 2 / len(chromosome) * len(gene).
    :param indv: obj, the individual/chromosome to be mutated
    :param pset: obj, the primitive set (gene codes) of the individual
    :param indpb: float,
    :return: tuple, one child of an individual parent
    """
    if indpb is None:
        indpb = 2 / (len(indv) * len(indv[0]))
    head = indv[0].head_length
    cell = indv[0].cell_length
    for i, gene in enumerate(indv):
        if random.random() < indpb:
            for j in range(head):
            # if random.random() < indpb:
                gene[j] = select_program(pset)
                if _DEBUG: print('Gene {} mutated at point {}'.format(i, j))
            for k in range(head, head + cell):
            # if random.random() < indpb:
                gene[k] = select_cell(pset)
                if _DEBUG: print('Gene {} mutated at point {}'.format(i, k))
    return indv,

def mutate_transposition(indv, size=2):
    """
    Get insertion-sequence transposition mutation of a chromosome with a given probability.
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to transpose
    :return: tuple, one child of an individual parent
    """
    if random.random() < 0.5:
        return transpose_program(indv=indv, size=size)
    else:
        return transpose_cell(indv=indv, size=size)

def mutate_inversion(indv, size=2):
    """
    Get inversion mutation of a chromosome with a given probability.
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to invert
    :return: tuple, one child of an individual parent
    """
    if random.random() < 0.5:
        return invert_program(indv=indv, size=size)
    else:
        return invert_cell(indv=indv, size=size)

def invert_program(indv, size=2):
    """Get program-symbol inversion mutation of a chromosome with a given probability. A gene in a
    chromosome is randomly selected, and sequence of program-symbols within the gene is randomly selected and inverted.
    Typically, inversion rate is set to 0.1
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to invert
    :return: tuple, one child of an individual parent
    """
    head = indv[0].head_length
    if head < size:
        return indv,

    length = len(indv)
    if length > 1:
        idx = random.randint(0, length - 1)
        gene = indv[idx]
        stpt = random.randint(0, head - size)
        endpt = stpt + size
        gene[stpt:endpt] = reversed(gene[stpt:endpt])
        if _DEBUG: print('{} program-symbols of gene {} are inverted at positions [{} - {}]'
                  .format(size, idx, stpt, endpt - 1))
    elif length == 1:
        stpt = random.randint(0, head - size)
        endpt = stpt + size
        indv[0][stpt:endpt] = reversed(indv[0][stpt:endpt])
        if _DEBUG: print('{} program-symbols have been inverted at positions [{} - {}]'
                         .format(size, stpt, endpt - 1))
    return indv,

def invert_cell(indv, size=2):
    """Get cell inversion mutation of a chromosome with a given probability. A gene in a
    chromosome is randomly selected, and sequence of cells within the gene is randomly selected and inverted.
    Typically, inversion rate is set to 0.1
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to invert
    :return: tuple, one child of an individual parent
    """
    cell = indv[0].cell_length
    if cell < size:
        return indv,

    length = len(indv)
    head = indv[0].head_length
    if length > 1:
        idx = random.randint(0, length - 1)
        gene = indv[idx]
        stpt = random.randint(head, head + cell - size )
        endpt = stpt + size
        gene[stpt:endpt] = reversed(gene[stpt:endpt])
        if _DEBUG: print('{} cells of gene {} are inverted at positions [{} - {}]'
                         .format(size, idx, stpt, endpt - 1))
    elif length == 1:
        stpt = random.randint(head, head + cell - size)
        endpt = stpt + size
        indv[0][stpt:endpt] = reversed(indv[0][stpt:endpt])
        if _DEBUG: print('{} cells have been inverted at positions [{} - {}]'.format(size, stpt, endpt - 1))
    return indv,

def transpose_program(indv, size=2):
    """Get program insertion-sequence transposition mutation of a chromosome with a given probability.
    A gene in a chromosome is randomly selected, and a sequence of program-symbols is randomly selected,
    and a copy is afterwards inserted at a randomly selected point in the head of another gene in the chromosome.
    Typically, transposition rate is set to 0.1
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to transpose
    :return tuple, one child of an individual parent
    """
    length = len(indv)
    head = indv[0].head_length
    if length == 1 or head < size:
        return indv,

    gene1 = random.randint(0, length - 2)
    gene2 = random.randint(0, length - 1)
    if gene1 > gene2:
        gene1, gene2 = gene2, gene1
    elif gene1 == gene2:
        gene2 += 1
    stpt1 = random.randint(0, head - size)
    stpt2 = random.randint(0, head - size)
    endpt1 = stpt1 + size
    endpt2 = stpt2 + size
    donner, target = indv[gene1], indv[gene2]
    target[stpt2:endpt2] = donner[stpt1:endpt1]
    if _DEBUG: print('Gene {} transposed program-symbols at positions [{} - {}] to Gene {} at positions '
                     '[{} - {}]'.format(gene1, stpt1, endpt1 - 1, gene2, stpt2, endpt2 - 1))
    return indv,

def transpose_cell(indv, size=2):
    """Get cell insertion-sequence transposition mutation of a chromosome with a given probability.
    A gene in a chromosome is randomly selected, and a sequence of cells is randomly selected, and a copy
    is afterwards inserted at a randomly selected point in the cell domain of another gene in the chromosome.
    Typically, transposition rate is set to 0.1
    :param indv: obj, the individual/chromosome to be mutated
    :param size: int, the length of string to transpose
    :return: tuple, one child of an individual parent
    """
    length = len(indv)
    head = indv[0].head_length
    cell = indv[0].cell_length
    if length == 1 or cell < size:
        return indv,

    gene1 = random.randint(0, length - 2)
    gene2 = random.randint(0, length - 1)
    if gene1 > gene2:
        gene1, gene2 = gene2, gene1
    elif gene1 == gene2:
        gene2 += 1
    stpt1 = random.randint(head, head + cell - size)
    stpt2 = random.randint(head, head + cell - size)
    endpt1 = stpt1 + size
    endpt2 = stpt2 + size
    donner, target = indv[gene1], indv[gene2]
    target[stpt2:endpt2] = donner[stpt1:endpt1]
    if _DEBUG: print('Gene {} transposed cells at positions [{} - {}] to Gene {} at positions [{} - {}]'
              .format(gene1, stpt1, stpt1 - 1, gene2, stpt2, endpt2 - 1))
    return indv,

def transpose_gene(indv):
    """Get gene transposition mutation of a chromosome with a given probability. A gene in a
    chromosome is randomly selected, and the entire gene is transposed to the beginning of the
    chromosome. To maintain the length of the chromosome, the transposon (the gene which was
    transposed) is deleted at its place of origin. Typically, transposition rate is set to 0.1
    :param indv: obj, the individual/chromosome to be mutated
    :return: tuple, one child of an individual parent
    """
    if len(indv) == 1:
        return indv,

    idx = random.randint(1, len(indv) - 1)
    gene = indv[idx]
    indv.remove(gene)
    indv.insert(0, gene)
    if _DEBUG: print('Gene {} has been transposed to position 0'.format(idx))
    return indv,

# exported functions
__all__ = ['cross_one_point', 'cross_two_point', 'cross_gene', 'mutate_uniform', 'mutate_inversion',
           'mutate_transposition', 'transpose_gene']


import os

folder = r'C:\Users\elelo\OneDrive\Documents\Cours Terminale\SIN\PYTHON\renommage de masse\images\\'
count = 1

for file_name in os.listdir(folder):
    source = folder + file_name

    destination = folder + "image_" + str(count) + ".png"
    os.renames(source, destination)
    count += 1
print('Nouveaux Noms :')
res = os.listdir(folder)
print(res)


import random
# Decida por mim

#Definido possibilidades
possiveis_respostas = ['Sim', 'Não', 'Acho melhor não', 'Acho melhor sim', 'Faz oque seu coração manda', 'Não perca essa oportunidade', 'Corre! É furada']

#Pergunda do usuário
pergunta = str((input('Qual a sua pergunda? ')))

#Respondendo pergunda aleatoriamente
print(possiveis_respostas[random.randint(0, 6)])


n = int(input())
c = list(map(int, input().split()))
u = set()
r = True

while len(u) < n:
    u.add(c[0])
    for i in range(n):
        if i % 2 == 0:
            c[i] = (c[i] + 1) % n
        else:
            c[i] = (c[i] - 1) % n
    r = True
    for i in range(n):
        if c[i] != i:
            r = False
            break
    if r:
        break

if r:
    print("Yes")
else:
    print("No")


import torch
import torch.nn as nn
import torch.nn.functional as F
from model.general.attention.additive import AdditiveAttention

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

class TextEncoder(torch.nn.Module):
    def __init__(self, word_embedding, word_embedding_dim, num_filters,
                 window_size, query_vector_dim, dropout_probability):
        super(TextEncoder, self).__init__()
        self.word_embedding = word_embedding
        self.dropout_probability = dropout_probability
        self.CNN = nn.Conv2d(1,
                             num_filters, (window_size, word_embedding_dim),
                             padding=(int((window_size - 1) / 2), 0))
        self.additive_attention = AdditiveAttention(query_vector_dim,
                                                    num_filters)

    def forward(self, text):
        # batch_size, num_words_text, word_embedding_dim
        text_vector = F.dropout(self.word_embedding(text),
                                p=self.dropout_probability,
                                training=self.training)
        # batch_size, num_filters, num_words_title
        convoluted_text_vector = self.CNN(
            text_vector.unsqueeze(dim=1)).squeeze(dim=3)
        # batch_size, num_filters, num_words_title
        activated_text_vector = F.dropout(F.relu(convoluted_text_vector),
                                          p=self.dropout_probability,
                                          training=self.training)

        # batch_size, num_filters
        text_vector = self.additive_attention(
            activated_text_vector.transpose(1, 2))
        return text_vector

class ElementEncoder(torch.nn.Module):
    def __init__(self, embedding, linear_input_dim, linear_output_dim):
        super(ElementEncoder, self).__init__()
        self.embedding = embedding
        self.linear = nn.Linear(linear_input_dim, linear_output_dim)

    def forward(self, element):
        return F.relu(self.linear(self.embedding(element)))

class NewsEncoder(torch.nn.Module):
    def __init__(self, config, pretrained_word_embedding):
        super(NewsEncoder, self).__init__()
        self.config = config
        if pretrained_word_embedding is None:
            word_embedding = nn.Embedding(config.num_words,
                                          config.word_embedding_dim,
                                          padding_idx=0)
        else:
            word_embedding = nn.Embedding.from_pretrained(
                pretrained_word_embedding, freeze=False, padding_idx=0)
        assert len(config.dataset_attributes['news']) > 0
        text_encoders_candidates = ['title', 'abstract']
        self.text_encoders = nn.ModuleDict({
            name:
            TextEncoder(word_embedding, config.word_embedding_dim,
                        config.num_filters, config.window_size,
                        config.query_vector_dim, config.dropout_probability)
            for name in (set(config.dataset_attributes['news'])
                         & set(text_encoders_candidates))
        })
        category_embedding = nn.Embedding(config.num_categories,
                                          config.category_embedding_dim,
                                          padding_idx=0)
        element_encoders_candidates = ['category', 'subcategory']
        self.element_encoders = nn.ModuleDict({
            name:
            ElementEncoder(category_embedding, config.category_embedding_dim,
                           config.num_filters)
            for name in (set(config.dataset_attributes['news'])
                         & set(element_encoders_candidates))
        })
        if len(config.dataset_attributes['news']) > 1:
            self.final_attention = AdditiveAttention(config.query_vector_dim,
                                                     config.num_filters)

    def forward(self, news):
        """
        Args:
            news:
                {
                    "category": batch_size,
                    "subcategory": batch_size,
                    "title": batch_size * num_words_title,
                    "abstract": batch_size * num_words_abstract,
                }
        Returns:
            (shape) batch_size, num_filters
        """
        text_vectors = [
            encoder(news[name].to(device))
            for name, encoder in self.text_encoders.items()
        ]
        element_vectors = [
            encoder(news[name].to(device))
            for name, encoder in self.element_encoders.items()
        ]

        all_vectors = text_vectors + element_vectors

        if len(all_vectors) == 1:
            final_news_vector = all_vectors[0]
        else:
            final_news_vector = self.final_attention(
                torch.stack(all_vectors, dim=1))
        return final_news_vector


def find_second(lst):
    lst.sort()
    return lst[2]

N = int(input())

arr = []
for _ in range(N):
    temp = list(map(int, input().split()))
    arr.append(temp)

while N != 1:
    result = []
    for i in range(N//2):
        for j in range(N//2):
            r1 = 2*i
            r2 = 2*i + 1
            c1 = 2*j
            c2 = 2*j + 1

            temp_list = [(arr[r1][c1], r1, c1), (arr[r1][c2], r1, c2), (arr[r2][c1], r2, c1), (arr[r2][c2], r2, c2)]
            value, r, c = find_second(temp_list)
            if j == 0:
                result.append([value])
            else:
                result[i].append(value)
    arr = result
    N //= 2
print(result[0][0])


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

parser=argparse.ArgumentParser(description="Plot 1d differential scattering cross section output from GGADT")
parser.add_argument('file_name',metavar='ggadt-output-file',type=str, nargs=1, help="a file containing the output of GGADT")

args = parser.parse_args()

file_name = args.file_name[0]

dscs = np.loadtxt(file_name, dtype=np.dtype([('theta', np.float_), ('dCdOm', np.float_)]))
dscs['theta'] *= 206264.806 # convert to arcseconds

# now plot!
f = plt.figure()
ax = f.add_subplot(111)

ax.plot(dscs['theta'], dscs['dCdOm'])
ax.set_xlabel("$\\theta$ [arcseconds]")
ax.set_ylabel("$dQ_{\\rm sca}/d\\Omega$ [sr$^{-1}$]")
ax.set_yscale('log')
plt.show(block=True)


from abc import abstractmethod, ABCMeta

from octobot_commons.logging.logging_util import get_logger

class AbstractWebsocket:
    __metaclass__ = ABCMeta

    def __init__(self, config, exchange_manager):
        self.config = config
        self.exchange_manager = exchange_manager
        self.client = None
        self.name = self.get_name()
        self.logger = get_logger(f"WebSocket - {self.name}")

    # Abstract methods
    @classmethod
    def get_name(cls):
        raise NotImplementedError("get_name not implemented")

    @classmethod
    def has_name(cls, name: str) -> bool:
        raise NotImplementedError("has_name not implemented")

    @staticmethod
    def get_websocket_client(config, exchange_manager):
        raise NotImplementedError("get_websocket_client not implemented")

    @abstractmethod
    def is_handling(self, feed_name):
        raise NotImplementedError("is_handling not implemented")

    @abstractmethod
    async def init_websocket(self, time_frames, trader_pairs):
        raise NotImplementedError("init_websocket not implemented")

    @abstractmethod
    async def start_sockets(self):
        raise NotImplementedError("start_sockets not implemented")

    @abstractmethod
    async def wait_sockets(self):
        raise NotImplementedError("wait_sockets not implemented")

    @abstractmethod
    async def close_and_restart_sockets(self):
        raise NotImplementedError("close_and_restart_sockets not implemented")

    @abstractmethod
    async def stop_sockets(self):
        raise NotImplementedError("stop_sockets not implemented")


import re
import sys

def main():
    print(validate(input("IPv4 Address: ")))

def validate(ip):
    ip = ip.strip()
    if not re.search(r'^\d+\.\d+\.\d+\.\d+$',ip):
        return False
    nums = ip.split('.')
    for i in nums:
        if int(i)<0 or int(i)>255:
            return False
    return True

if __name__ == "__main__":
    main()


from django.shortcuts import render_to_response, redirect
from Inventar.models import Geraet, GeraeteTyp
from django.db.models import Q
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from ClientManagement.models import ComputerType, WindowsKey, Computer
from ClientManagement.forms import ComputerTypeForm, WindowsKeyForm, ComputerForm
from django.contrib import messages
import re

@login_required
def index(request):
	computers = Computer.objects.all().order_by('name')
	types = ComputerType.objects.all().order_by('vendor', 'name')
	keys = WindowsKey.objects.all()

	return render_to_response('clientmanagement/index.html', {'computers': computers, 'types': types, 'keys': keys, 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def computer_edit(request, id):
	try:
		c = Computer.objects.get(pk=id)
	except Computer.DoesNotExist:
			return render_to_response('clientmanagement/404.html')

	if request.method == 'POST':
		form = ComputerForm(request.POST, instance=c)
		if form.is_valid():
			c = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Computer "' + c.name + '" wurde erfolgreich bearbeitet.')
			return redirect('/pool/')
	else:
		form = ComputerForm(instance=c)

	return render_to_response('clientmanagement/computer_form.html', {'form': form, 'action': 'Speichern', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def computer_create(request):
	if request.method == 'POST':
		form = ComputerForm(request.POST)
		if form.is_valid():
			c = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Computer "' + c.name + '" wurde erfolgreich erstellt.')
			return redirect('/pool/')
	else:
		form = ComputerForm()

	return render_to_response('clientmanagement/computer_form.html', {'form': form, 'action': 'Erstellen', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def type_edit(request, id):
	try:
		t = ComputerType.objects.get(pk=id)
	except ComputerType.DoesNotExist:
			return render_to_response('clientmanagement/404.html')

	if request.method == 'POST':
		form = ComputerTypeForm(request.POST, instance=t)
		if form.is_valid():
			t = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Computertyp "' + t.name + '" wurde erfolgreich bearbeitet.')
			return redirect('/pool/')
	else:
		form = ComputerTypeForm(instance=t)

	return render_to_response('clientmanagement/type_form.html', {'form': form, 'action': 'Speichern', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def type_create(request):
	if request.method == 'POST':
		form = ComputerTypeForm(request.POST)
		if form.is_valid():
			t = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Computertyp "' + t.name + '" wurde erfolgreich erstellt.')
			return redirect('/pool/')
	else:
		form = ComputerTypeForm()

	return render_to_response('clientmanagement/type_form.html', {'form': form, 'action': 'Erstellen', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def key_create(request):
	if request.method == 'POST':
		form = WindowsKeyForm(request.POST)
		if form.is_valid():
			k = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Windows Key wurde erfolgreich erstellt.')
			return redirect('/pool/')
	else:
		form = WindowsKeyForm()

	return render_to_response('clientmanagement/key_form.html', {'form': form, 'action': 'Erstellen', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def key_edit(request, id):
	try:
		k = WindowsKey.objects.get(pk=id)
	except WindowsKey.DoesNotExist:
			return render_to_response('clientmanagement/404.html')

	if request.method == 'POST':
		form = WindowsKeyForm(request.POST, instance=k)
		if form.is_valid():
			k = form.save()
			messages.add_message(request, messages.SUCCESS, 'Der Windows Key wurde erfolgreich bearbeitet.')
			return redirect('/pool/')
	else:
		form = WindowsKeyForm(instance=k)

	return render_to_response('clientmanagement/key_form.html', {'form': form, 'action': 'Speichern', 'active': 'clientManagement'}, context_instance=RequestContext(request))

@login_required
def dhcp_config(request):
	computers = Computer.objects.filter(~Q(name='') and ~Q(ip_address=''))

	computer_list = []
	for c in computers:
		if re.search('([a-fA-F0-9]{2}[:|\-]?){6}', c.mac_address):
			computer_list.append(c)

	return render_to_response('clientmanagement/dhcp_config.txt', {'computers': computer_list}, content_type='text/plain', context_instance=RequestContext(request))


import pandas as pd
from typing import List, Dict
from modules.utilities.keyword_extractor import extract_keywords_from_input, keywords_df

# Simplified Color Conversion
def letter_to_color(color: str) -> str:
    color_dict = {
        'W': 'White',
        'U': 'Blue',
        'B': 'Black',
        'R': 'Red',
        'G': 'Green'
    }
    return color_dict.get(color, '')

# Refactored determine_colors
def determine_colors(user_input: str) -> List[str]:
    color_keywords = {
        'W': ['white', 'life', 'heal', 'humans', 'warriors', 'wipe'],
        'U': ['blue', 'counter', 'draw', 'bounce', 'removal'],
        'B': ['black', 'swamp', 'graveyard', 'death', 'removal', 'destroy', 'loss'],
        'R': ['red', 'burn', 'dragon', 'aggro', 'aggressive', 'lightning', 'quick'],
        'G': ['green', 'elf', 'forest', 'strong', 'heavy', 'hitters', 'big', 'dinosaur']
    }

    user_input = user_input.lower()
    included_colors = []

    for color, keywords in color_keywords.items():
        if any(keyword in user_input for keyword in keywords):
            included_colors.append(color)

    return included_colors

# Refactor Scoring Functions
def score_card(card: pd.Series, keywords: list, primary_color: str, selected_cards: pd.DataFrame) -> Dict[str, float]:
    text = card['Text'].lower()

    # Theme Score
    token_keywords = ['create', 'token', 'tokens', 'creature tokens']
    theme_score = sum([text.count(keyword.lower()) for keyword in keywords]) + \
                  sum([text.count(token_keyword) * 5 for token_keyword in token_keywords])

    # Mana Curve Score
    try:
        mana_cost = float(card['Mana Cost'])
        mana_curve_score = 1 / mana_cost
    except ValueError:
        mana_curve_score = 0

    # Color Consistency Score
    colors = ['W', 'U', 'B', 'R', 'G']
    color_score = sum([1 for color in colors if color in card['Mana Cost'] and color == primary_color])

    # Synergy Score
    synergy_score = 0
    for _, selected_card in selected_cards.iterrows():
        selected_card_text = selected_card['Text'].lower()
        shared_keywords = set(text.split()).intersection(set(selected_card_text.split()))
        synergy_score += len(shared_keywords)
        # Increase synergy score if the selected card also focuses on tokens
        if any(token_keyword in selected_card_text for token_keyword in token_keywords):
            synergy_score += 5

    return {
        'Theme Score': theme_score,
        'Mana Curve Score': mana_curve_score,
        'Color Score': color_score,
        'Synergy Score': synergy_score
    }

def calculate_land_distribution(selected_cards: pd.DataFrame, deck_size: int) -> Dict[str, int]:
    """
    Calculate land distribution based on the mana symbols in the mana costs of the selected cards.
    """
    # Count the total occurrences of each mana symbol in the selected cards' mana costs
    mana_symbols_count = {'W': 0, 'U': 0, 'B': 0, 'R': 0, 'G': 0}

    for _, card in selected_cards.iterrows():
        for symbol, count in mana_symbols_count.items():
            mana_symbols_count[symbol] += card['Mana Cost'].count(symbol)

    # Calculate the total number of mana symbols
    total_symbols = sum(mana_symbols_count.values())

    # Calculate the number of lands to add
    total_lands = deck_size - len(selected_cards)

    # Distribute the lands based on the proportion of each mana symbol
    land_distribution = {}
    for symbol, count in mana_symbols_count.items():
        land_distribution[letter_to_color(symbol)] = int(total_lands * (count / total_symbols))

    return land_distribution

def build_deck(user_input: str, cards_df: pd.DataFrame, deck_size=60, max_copies_per_card=4) -> dict:
    # Extract keywords from user input
    keywords = extract_keywords_from_input(user_input, keywords_df)

    # Determine the included colors based on user input
    included_colors = determine_colors(user_input)

    # Convert letters to full color names for filtering
    included_color_names = [letter_to_color(color) for color in included_colors]

    # Prepare a dictionary to track card counts to ensure we don't exceed max_copies_per_card
    card_counts = {}

    # Prepare a DataFrame to store selected cards
    selected_cards_df = pd.DataFrame()

    # Filter cards based on included colors and exclude cards that require other colors
    valid_cards_df = cards_df[cards_df['Mana Cost'].fillna('').apply(
        lambda x: all(color in x for color in included_colors) and all(
            color not in x for color in ['W', 'U', 'B', 'R', 'G'] if color not in included_colors))].copy()

    # Score the cards
    scores_df = valid_cards_df.apply(lambda card: score_card(card, keywords, included_colors, selected_cards_df),
                                     axis=1, result_type='expand')
    valid_cards_df = pd.concat([valid_cards_df, scores_df], axis=1)
    valid_cards_df['Total Score'] = valid_cards_df[
        ['Theme Score', 'Mana Curve Score', 'Color Score', 'Synergy Score']].sum(axis=1)

    # Sort cards by Total Score in descending order for selection
    valid_cards_df = valid_cards_df.sort_values(by='Total Score', ascending=False)

    for _, card in valid_cards_df.iterrows():
        if len(selected_cards_df) >= (deck_size - 24):  # Reserve space for approximately 24 lands
            break

        card_name = card['Name']
        if card_name not in card_counts:
            card_counts[card_name] = 0

        if card_counts[card_name] < max_copies_per_card:
            card_counts[card_name] += 1
            selected_cards_df = pd.concat([selected_cards_df, card.to_frame().T], ignore_index=True)

    # Calculate land distribution
    land_distribution = calculate_land_distribution(selected_cards_df, deck_size)

    # Adjust the land count based on the average mana cost of the selected cards
    average_mana_cost = selected_cards_df['Mana Cost'].str.count('[WUBRGC]').mean()
    total_land_count = int(20 + (4 * average_mana_cost))

    for land, count in land_distribution.items():
        difference = total_land_count - sum(land_distribution.values())
        land_distribution[land] += min(difference, count)

    # Prepare the final deck dictionary with card counts
    deck_dict = {}
    for _, card in selected_cards_df.iterrows():
        card_name = card['Name']
        if card_name in deck_dict:
            deck_dict[card_name] += 1
        else:
            deck_dict[card_name] = 1

    # Convert color names to actual land names
    color_to_land_map = {
        "White": "Plains",
        "Blue": "Island",
        "Black": "Swamp",
        "Red": "Mountain",
        "Green": "Forest"
    }
    for color, land_name in color_to_land_map.items():
        if color in included_color_names:
            deck_dict[land_name] = deck_dict.get(land_name, 0) + land_distribution[color]

    return deck_dict


# loop 1 to 10
for n in range(1,11):
    # n += 1
   print('all nums 1 to 10:', n)

# n to m
m = int(input('start num? '))
n = int(input('end num? '))
for b in range(m,n+1):
   print('M to N ', b)

# print odd numbers

for r in range(1,11):
    if r % 2 != 0:
        print(r)

# creating a box
for i in range(0,5):
    for j in range(0,5):
        print("*" , end = " ")
    print(i)


import torch, os, pickle
import numpy as np
from sklearn.metrics import (
    confusion_matrix,
    precision_recall_fscore_support
)

class TrainTest():
    def __init__(self, model, criterion, logger=None, writer=None):
        self.model = model
        self.criterion = criterion
        self.logger = logger
        self.writer = writer
        self.tr_metrics = {
            'train_loss': [],
            'train_accuracy': [],
            'valid_loss': [],
            'valid_accuracy': [],
        }

    def train(
            self, train_loader, valid_loader,
            num_epochs, device, eval_interval,
            clip=None, model_path=None,
            save_per_epoch=None, results_path=None,
            model_name=''
    ):
        total_itrs = num_epochs * len(train_loader)
        num_tr, total_tr_loss, itr, step = 0, 0, 0, 0
        self.model.train()
        for epoch in range(num_epochs):
            for i, tr_inputs in enumerate(train_loader):
                self.optimizer.zero_grad()
                tr_output, tr_labels = self.feed_forward(tr_inputs, device)
                tr_loss = self.compute_loss(tr_output, tr_labels)
                # nn.utils.clip_grad_norm_(model.parameters(), clip)
                if self.logger:
                    self.logger.info(f'Training: {itr}/{total_itrs} -- loss: {tr_loss.item()}')
                tr_loss.backward()
                self.optimizer.step()
                num_tr += 1
                total_tr_loss += tr_loss
                if itr % eval_interval == 0 or itr + 1 == total_itrs:
                    self.tr_metrics['train_loss'].append(total_tr_loss.cpu().item() / num_tr)
                    tr_accuracy = self.cal_accuracy(tr_output, tr_labels)
                    self.tr_metrics['train_accuracy'].append(tr_accuracy)
                    num_tr, total_tr_loss = 0, 0
                    val_loss = 0
                    self.model.eval()
                    val_accuracy = []
                    with torch.no_grad():
                        for i, val_inputs in enumerate(valid_loader):
                            self.optimizer.zero_grad()
                            val_output, val_labels = self.feed_forward(val_inputs, device)
                            val_loss += self.compute_loss(val_output, val_labels)
                            val_accuracy.append(self.cal_accuracy(val_output, val_labels))
                    self.tr_metrics['valid_accuracy'].append(np.mean(val_accuracy))
                    self.tr_metrics['valid_loss'].append(val_loss.cpu().item() / len(valid_loader))
                    self.model.train()
                    if self.logger:
                        self.logger.info(f'Training: iteration: {itr}/{total_itrs} -- epoch: {epoch} -- '
                                         f' train_loss: {self.tr_metrics["train_loss"][-1]:.3f} -- train_accuracy: {self.tr_metrics["train_accuracy"][-1]:.2f}'
                                         f' valid_loss: {self.tr_metrics["valid_loss"][-1]:.3f} -- valid_accuracy: {self.tr_metrics["valid_accuracy"][-1]:.2f}')
                        self.writer.add_scalar('train-loss', self.tr_metrics["train_loss"][-1], global_step=step)
                        self.writer.add_scalar('valid-loss', self.tr_metrics["valid_loss"][-1], global_step=step)
                        self.writer.add_scalar('train-accuracy', self.tr_metrics["train_accuracy"][-1], global_step=step)
                        self.writer.add_scalar('valid-accuracy', self.tr_metrics["valid_accuracy"][-1], global_step=step)
                    step += 1
                itr += 1
            self.scheduler.step()
            if model_path and results_path and ((epoch + 1) % save_per_epoch == 0) and epoch != 0:
                self.save_model(epoch + 1, model_path, f'{model_name}_{epoch + 1}_epochs_train')
                self.save_results(results_path, f'{model_name}_{epoch + 1}_epochs_train', self.tr_metrics)
        if model_path and results_path:
            self.save_model(epoch + 1, model_path, f'{model_name}_{epoch + 1}_epochs_last_train')
            self.save_results(results_path, f'{model_name}_{epoch + 1}_epochs_last_train', self.tr_metrics)

    def load_trained_model(self, path):
        checkpoint = torch.load(path)
        self.model.load_state_dict(checkpoint['model_state_dict'])
        self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
        self.scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
        return checkpoint['epoch']

    def load_training_results(self, path):
        with open(path, 'rb') as results_file:
            training_results = pickle.load(results_file)
        self.tr_metrics = training_results

    def continue_train(
            self, train_loader, valid_loader,
            model_path, results_path,
            num_epochs, device, eval_interval,
            clip=None, save_per_epoch=None, model_name=''
    ):
        last_epoch = self.load_trained_model(model_path)
        self.load_training_results(results_path)
        self.train(
            train_loader, valid_loader, num_epochs,
            device, eval_interval,
            model_path='/'.join([str(x) for x in model_path.split('/')[:-1]] ) +'/',
            save_per_epoch=save_per_epoch,
            results_path='/'.join([str(x) for x in results_path.split('/')[:-1]] ) +'/',
            clip=clip,
            model_name=model_name
        )

    def set_optimizer(self, optimizer, **kwargs):
        if optimizer == 'Adam':
            from torch.optim import Adam
            self.optimizer = Adam(self.model.parameters(), **kwargs)
        elif optimizer == 'SGD':
            from torch.optim import SGD
            self.optimizer = SGD(self.model.parameters(), **kwargs)
        else:
            self.optimizer = optimizer(self.model.parameters(), **kwargs)

    def set_scheduler(self, scheduler, **kwargs):
        if scheduler == 'LambdaLR':
            from torch.optim.lr_scheduler import LambdaLR
            self.scheduler = LambdaLR(self.optimizer, **kwargs)
        if scheduler == 'StepLR':
            from torch.optim.lr_scheduler import StepLR
            self.scheduler = StepLR(self.optimizer, **kwargs)
        else:
            self.scheduler = scheduler(self.optimizer, **kwargs)

    # this method should be inherited by the childerens
    def feed_forward(self, inputs, device):
        pass

    # this method might be inherited by the childerens
    def compute_loss(self, output, labels):
        return self.criterion(output, labels.view(-1))

    # this method might be inherited by the childerens
    @classmethod
    def cal_accuracy(cls, pred_labels, true_labels):
        _, pred_labels = pred_labels.max(dim=1)
        true_labels = true_labels.view(-1)
        return torch.sum(pred_labels == true_labels).item() / true_labels.size()[0]

    def save_model(self, epoch, model_path, name):
        model_dir = '/'.join(model_path.split('/')[:-1])
        if not os.path.exists(model_dir):
            os.makedirs(model_dir)
        torch.save(
            {
                'epoch': epoch,
                'model_state_dict': self.model.state_dict(),
                'optimizer_state_dict': self.optimizer.state_dict(),
                'scheduler_state_dict': self.scheduler.state_dict(),
                'loss': self.tr_metrics['valid_loss'][-1],
            }, os.path.join(model_dir, f'model_{name}.pt')
        )
        if self.logger:
            self.logger.info(f'Training: model saved to: {model_dir}/model_{name}.pt')

    def save_results(self, results_path, name, results):
        results_dir = '/'.join(results_path.split('/')[:-1])
        if not os.path.exists(results_dir):
            os.makedirs(results_dir)
        with open(os.path.join(results_dir, f'results_{name}.pkl'), 'wb') as save_file:
            pickle.dump(results, save_file)
        if self.logger:
            self.logger.info(f'Training: results saved to: {results_dir}/resutls_{name}.pkl')

    def freeze_layers(self, freezing_param_names):
        for name, param in self.model.named_parameters():
            if name in freezing_param_names:
                param.requires_grad = False

    def test(self, ts_loader, device, model_name='', label_names=None, results_path=None):
        ts_accuracy, ts_true, ts_pred = [], [], []
        ts_loss = 0
        self.model.eval()
        with torch.no_grad():
            for i, ts_inputs in enumerate(ts_loader):
                self.optimizer.zero_grad()
                ts_output, ts_labels = self.feed_forward(ts_inputs, device)
                ts_loss += self.compute_loss(ts_output, ts_labels)
                ts_accuracy.append(self.cal_accuracy(ts_output, ts_labels))
                ts_true.append(ts_labels.cpu())
                ts_pred.append(ts_output.cpu().max(dim=1)[1])
        ts_true = torch.cat(ts_true)
        ts_pred = torch.cat(ts_pred)
        ts_loss = ts_loss.cpu().item() / len(ts_loader)
        ts_accuracy = np.mean(ts_accuracy)
        prf = precision_recall_fscore_support(
            ts_true,
            ts_pred,
            labels=label_names,
            average='weighted'
        )
        confm = confusion_matrix(ts_true, ts_pred, labels=label_names)
        self.ts_metrics = {
            'loss': ts_loss,
            'accuracy': ts_accuracy,
            'precision': prf[0],
            'recall': prf[1],
            'f1_score': prf[2],
            'confusion_matrix': confm
        }
        if self.logger:
            print(
                f'tsing: ts_loss: {ts_loss:.3f} -- ts_accurcy: {ts_accuracy:.2f}')
        if results_path:
            self.save_results(results_path, f'{model_name}_ts', self.ts_metrics)


import re

# 1. 문자 클래스
# \d = [0-9]
# 문자 : [a-z] [A-Z]  => [A-z]
# \w : [a-zA-Z0-9]
# \s whitespace : [ \t\n\r]
# . : 모든문자(\n만 제외)

# 2. 반복
# + : 1 이상 => [0-9]+ : 숫자가 1자리 이상
# * : 0 이상 [0-9]+ : 숫자가 없거나 1자리 이상
# ? : 0 또는 1 : [0-9]? : 숫자가 1자리 없거나 있거나
#
# {x} : x번 반복
# {x, y} : x~y번 반복
# {x, } : x번 이상 반복

# + => {1, } : [0-9]{1,}
# * => {0, } : [0-9]{0,}
# ? => {0,1} :: [0-9]{0,1}

# 3. 검색
# match() : 문자열의 처음부터 정규식과 매치(일지)하는지 확인한다.
# search() : 문자열 전체를 검사하여 정규식과 일치하는지 확인한다.
# findall() : 정규식과 매치되는 모든 문자열(substring)을 리스트로 반환한다.
# finditer() : 정규식과 매치되는 모든 문자열(substring)을 iterator 객체로 반환한다.

# 4. match
# 검색결과를 리턴하는 오브젝트
# 검색결과를 group 메쏘드로 볼 수 있음
# search, finditer로 검색시 사용가능
# group(0) : 검색된 전체
# group(x) : 패턴에서 지정한 그룹 번호
# 그룹지정은 ()로
# ex) "hello\s+(world)" => group(0) 는 전체, group(1)은 world

content = "hello jungil"
p = re.compile("hello\s+(\w+)")
m = p.search(content)
if m:
    print(m.group())
    print(m.group(1))

content = "first line \n second 2 line"
p = re.compile("\w+\s+line", re.MULTILINE)
results = p.findall(content)
print(results)


from django.shortcuts import render, redirect
from .models import Post, Comment
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core.paginator import Paginator

# Create your views here.
def index(request):
    posts = Post.objects.order_by('-pk')
    page = request.GET.get('page', '1')
    per_page = 5
    paginator = Paginator(posts, per_page)
    page_obj = paginator.get_page(page)
    last = paginator.num_pages
    context = {
        'posts': page_obj,
        'last' : last,
    }
    return render(request, 'posts/index.html', context)

@login_required
def create(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            return redirect('posts:detail', post.pk)

    else:
        form = PostForm()

    context = {
        'form': form,
    }
    return render(request, 'posts/create.html', context)

def detail(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    last = Post.objects.last()
    comment_form = CommentForm()
    comments = post.comment_set.all()
    context = {
        'post': post,
        'last': last,
        'comment_form': comment_form,
        'comments': comments,
    }
    return render(request, 'posts/detail.html', context)

def delete(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    if request.user == post.user:
        post.delete()
    return redirect('posts:index')

def update(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    if request.user == post.user:
        if request.method == "POST":
            form = PostForm(request.POST, request.FILES, instance=post)
            if form.is_valid():
                form.save()
                return redirect('posts:detail', post.pk)
        else:
            form = PostForm(instance=post)
    else:
        return redirect('posts:index')
    context = {
        'post' : post,
        'form' : form,
    }
    return render(request, 'posts/update.html', context)

@login_required
def answer(request, post_pk, answer):
    # POST posts/<int:post_pk>/answer/<str:answer>/
    post = Post.objects.get(pk=post_pk)
    user = request.user
    if request.method == "POST":
        if user in post.select1_users.all() or user in post.select2_users.all():
            pass
        else:
            if answer == post.select1_content:
                post.select1_users.add(user)
                is_select = True
                context = {
                    'is_select' : is_select,
                    'select1_count': post.select1_users.count()
                }

            elif answer == post.select2_content:
                post.select2_users.add(user)
                is_select = True
                context = {
                    'is_select' : is_select,
                    'select2_count': post.select2_users.count()
                }
            return JsonResponse(context)
    return redirect('posts:detail', post_pk, context)

@login_required
def comment_create(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    comment_form = CommentForm(request.POST)

    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.user = request.user
        comment.post = post
        comment.save()

        return redirect('posts:detail', post.pk)

    context = {
        'post': post,
        'comment_form' : comment_form,
    }
    return render(request, 'posts/detail.html', context)

@login_required
def comment_delete(request, post_pk, comment_pk):
    comment = Comment.objects.get(pk=comment_pk)

    if request.user == comment.user:
        # 댓글 삭제
        comment.delete()
    return redirect('posts:detail', post_pk)

def likes(request, post_pk):
    post = Post.objects.get(pk=post_pk)
    if request.user in post.like_users.all():
        post.like_users.remove(request.user)
        is_liked = False
    else:
        post.like_users.add(request.user)
        is_liked = True
    context = {
        'is_liked': is_liked,
        'likes_count': post.like_users.count()
    }
    return JsonResponse(context)


from time import sleep

from lab3.lab_python_fp.cm_timer import cm_timer_1
from field import field
from gen_random import gen_random
from unique import Unique

def test_field():
    goods = [
        {'title': 'Ковер', 'price': 2000, 'color': 'green'},
        {'title': 'Диван для отдыха', 'price': 5300, 'color': 'black'}
    ]

    field(goods, 'title', 'price')

def test_gen_random():
    print(gen_random(5, 1, 4))

def test_uniq():
    uniq = Unique([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])
    print([x for x in uniq])

    uniq = Unique(['a', 'A', 'b', 'B', 'a', 'A', 'b', 'B'], ignore_case=True)
    print([x for x in uniq])

    uniq = Unique(['a', 'A', 'b', 'B', 'a', 'A', 'b', 'B'])
    print([x for x in uniq])

def test_timer():
    with cm_timer_1():
        sleep(5.5)

    with cm_timer_1():
        sleep(3.6)

def main():
    print("Задание 1:")
    test_field()
    print("Задание 2:")
    test_gen_random()
    print("Задание 3:")
    test_uniq()
    print("Задание 6:")
    test_timer()

if __name__ == "__main__":
    main()


"""
URL configuration for bug_manage project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from web.view import user_info_view, home_view, project_view, manage_view, wiki_view, file_view, setting_view, \
    issues_view, dashboard_view, statistics_view

urlpatterns = [
    path("admin/", admin.site.urls),
    path('register/', user_info_view.user_register, name='register'),
    path('send_sms/', user_info_view.send_sms, name='send_sms'),
    path('login/', user_info_view.user_login, name='login'),
    path('login/sms/', user_info_view.user_login_by_sms, name='login_sms'),
    path('image_code/', user_info_view.image_code, name='image_code'),
    path('logout/', user_info_view.logout, name='logout'),

    path('index/', home_view.index, name='index'),
    path('price/', home_view.price, name='price'),
    path('payment/<policy_id>/', home_view.payment, name='payment'),
    path('pay/', home_view.pay, name='pay'),
    path('pay/notify/', home_view.pay_notify, name='pay_notify'),
    path('pay/return/', home_view.pay_return, name='pay_return'),

    # 项目列表
    path('project_list/', project_view.project_list, name='project_list'),
    path('project_star/<project_type>/<project_id>', project_view.project_star, name='project_star'),
    path('project_unstar/<project_id>', project_view.project_unstar, name='project_unstar'),
    # path('project_add/', project_view.project_add, name='project_add'),
    # 项目管理
    # wiki管理
    path('manage/<project_id>/wiki/', wiki_view.wiki, name='wiki'),
    path('manage/<project_id>/wiki_add/', wiki_view.wiki_add, name='wiki_add'),
    path('manage/<project_id>/wiki_edit/<wiki_id>', wiki_view.wiki_edit, name='wiki_edit'),
    path('manage/<project_id>/wiki_delete/<wiki_id>', wiki_view.wiki_delete, name='wiki_delete'),
    path('manage/<project_id>/wiki_catalog/', wiki_view.wiki_catalog, name='wiki_catalog'),
    path('manage/<project_id>/wiki_upload/', wiki_view.wiki_upload, name='wiki_upload'),
    # 文件管理
    # path('manage/<project_id>/wiki_detail/<wiki_id>', wiki_view.wiki_detail, name='wiki_detail'),
    path('manage/<project_id>/file/', file_view.file, name='file'),
    path('manage/<project_id>/file_delete/', file_view.file_delete, name='file_delete'),
    path('manage/<project_id>/cos/credential', file_view.cos_credential, name='cos_credential'),
    path('manage/<project_id>/file/post', file_view.file_post, name='file_post'),
    path('manage/<project_id>/file/download/<file_id>', file_view.file_download, name='file_download'),
    # 设置管理
    path('manage/<project_id>/setting/', setting_view.setting, name='setting'),
    path('manage/<project_id>/setting/delete/', setting_view.setting_delete, name='setting_delete'),

    # 问题管理
    path('manage/<project_id>/issues/', issues_view.issues, name='issues'),
    path('manage/<project_id>/issues_detail/<issues_id>/', issues_view.issues_detail, name='issues_detail'),
    path('manage/<project_id>/issues_record/<issues_id>/', issues_view.issues_record, name='issues_record'),
    path('manage/<project_id>/issues_change/<issues_id>/', issues_view.issues_change, name='issues_change'),
    path('manage/<project_id>/invite/url/', issues_view.invite_url, name='invite_url'),
    path('invite/join/<code>/', issues_view.invite_join, name='invite_join'),

    path('manage/<project_id>/dashboard/', dashboard_view.dashboard, name='dashboard'),
    path('manage/<project_id>/issues/chart/', dashboard_view.issues_chart, name='issues_chart'),
    path('manage/<project_id>/statistics/', statistics_view.statistics, name='statistics'),
    path('manage/<project_id>/statistics_priority/', statistics_view.statistics_priority, name='statistics_priority'),
    path('manage/<project_id>/statistics_project_user/', statistics_view.statistics_project_user,
         name='statistics_project_user'),

]


from django.conf.urls import url, include
from . import views
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm

app_name = 'movieratings'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^toprated', views.TopRated.as_view(), name='toprated'),
    # url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^search/$', views.SearchView.as_view(), name='search'),
    url(r'^genre/$', views.GenreView.as_view(), name='genre'),
    url(r'^allmovies/', views.AllMovies.as_view(), name='all_movies'),
    url(r'^movie/(?P<pk>[0-9]+)/$', views.MovieDetail.as_view(), name='movie_detail'),
    url(r'^rater/(?P<pk>[0-9]+)/$', views.RaterDetail.as_view(), name='rater_detail'),
    url(r'^newrating/', views.NewRating.as_view(), name='new_rating'),
    url(r'^register/$', views.register, name='register'), # these 3: conflicting with prior auths urls?
    url(r'^login/$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    # url(r'^index/$', views.IndexView.as_view() name='index'),
    ]


from lsst.ctrl.evmon import *

from lsst.ctrl.evmon.input import LsstEventReader
from lsst.ctrl.evmon.engine import MessageEvent

chain = Chain()

cond1 = Condition("$msg:info", Relation.STARTS_WITH, "Starting Stage")
chain.addLink(cond1)

cond2 = Condition("$msg:info", Relation.STARTS_WITH, "Ending Stage")
chain.addLink(cond2)

reader = LsstEventReader("LSSTLogging", "lsst8.ncsa.uiuc.edu")
job = Job(reader, chain)

engine = EventMonitor(job)
engine.runJobs()


from __future__ import print_function
import functools
import fractions

def solution_printer(ans_func, args=(), kwargs={}):
    import importlib
    from datetime import datetime
    # Print problem statement in module docstring
    mod_name = ans_func.__module__
    ans_mod = importlib.import_module(mod_name)
    ans_doc = ans_mod.__doc__.strip()
    print('-'*80)
    print(ans_doc)
    print('-'*80)
    # Start timer
    start = datetime.now()
    # Get and print answer
    answer = ans_func(*args, **kwargs)
    print('Answer:', answer)
    # Print running time
    end = datetime.now()
    print('Running time:', end-start)

def memoize(obj):
    """ Memoizing decorator that works on functions, methods, or classes, and
    exposes cache publically.

    See: http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize"""
    cache = obj.cache = {}
    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

def nCr(N, r):
    """ Computes the number of combinations of N things taken r at a time. """
    N, r = int(N), int(r)
    if (r > N) or (N < 0) or (r < 0):
        return 0
    ans = fractions.Fraction(1, 1)
    for i in range(1, r+1):
        ans = ans * fractions.Fraction(N-(r-i), i)
    return int(ans)


import numpy as np

### a quick code to decide the initial state of our test locations
### C = Control, no sign is included
### T = Treatment, a sign saying "Sanitize Hands Here" is placed in proximity to bottle.

np.random.seed(5271009)
a = ['car-lobby', 'car-gym', 'con-3', 'con-5', 'con-10', 'con-12', 'con-16', 'yarn', 'eca']
for loc in a:
   print(loc, np.random.choice(['C', 'T']))

#results
#car-lobby C
#car-gym C
#con-3 T
#con-5 T
#con-10 C
#con-12 T
#con-16 C
#yarn C
#eca T


# Tags: 二分搜索

# 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
#
# 你可以假设数组中无重复元素。
#
# 示例 1:
#
# 输入: [1,3,5,6], 5
# 输出: 2
# 示例 2:
#
# 输入: [1,3,5,6], 2
# 输出: 1
# 示例 3:
#
# 输入: [1,3,5,6], 7
# 输出: 4
# 示例 4:
#
# 输入: [1,3,5,6], 0
# 输出: 0
#
# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/search-insert-position
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

# 基本的二分搜索

from typing import List

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                l = mid + 1
            else:
                r = mid - 1
        return l

print(Solution().searchInsert([1, 3, 5, 6], 5))
print(Solution().searchInsert([1, 3, 5, 6], 2))
print(Solution().searchInsert([1, 3, 5, 6], 7))
print(Solution().searchInsert([1, 3, 5, 6], 0))

35. 搜索插入位置.py


import argparse
from time import time
import torch
from model_simple import ModelSimple
from model_lstm import ModelLSTM

parser = argparse.ArgumentParser(description='Profiler')
parser.add_argument('--lstm', action='store_true', help='profile LSTM')
parser.add_argument('--cuda', action='store_true', help='run on GPU')

if __name__ == '__main__':

    args = parser.parse_args()

    num_inputs = 23

    if args.cuda:
        device = torch.device("cuda")
    else:
        device = torch.device("cpu")

    if args.lstm:
        model = ModelLSTM()
    else:
        model = ModelSimple(num_inputs)
    model = model.to(device)

    start_time = time()
    for i in range(1000):
        x = torch.randn(1, num_inputs).to(device)
        y = model(x)

    print("time is {:f}".format((time()-start_time)/1000.0))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import tinymce.models

class Migration(migrations.Migration):

    dependencies = [
        ('police_archive', '0024_auto_20161010_1400'),
    ]

    operations = [
        migrations.AddField(
            model_name='officer',
            name='description',
            field=tinymce.models.HTMLField(blank=True),
        ),
        migrations.AlterField(
            model_name='officer',
            name='model_pic',
            field=models.ImageField(default='noimage', upload_to='police_archive/officer_photos', blank=True),
        ),
    ]