import argparse
import sys
from Choruslib import bwa
from Choruslib import jellyfish
from Choruslib import prefilter, primer3_filter, spgenome
import os
from multiprocessing import Pool
from math import log
from pyfasta import Fasta

def main():

    args = check_options(get_options())

    genomesize = int(os.path.getsize(args.genome)/1e6)

    kmer = int(log(genomesize, 4)+1)

    if kmer < 17:

        kmer = 17

    #jellyfish par
    lowercount = 2

    #jellyfish par
    jfsize = '100M'

    # splite sequence longer than 10M
    spsize = 10000000

    step = args.step

    maxkmerscore = int(((args.length * args.homology / 100) - kmer) * args.ploidy/2 + 0.5 )

    jfpool = Pool(args.threads)

    # ?build kmerindex
    jfkmerfile = os.path.join(args.saved,(os.path.basename(args.genome)+'_'+str(kmer)+'mer.jf'))

    kmerbuild = True

    if os.path.isfile(jfkmerfile):

        if not args.docker:

            print("find:", jfkmerfile)

            kmmess = "Found kmerfile "+jfkmerfile+". Do you want rebuild it?  Press Y or N to continue:"

            print(kmmess)

            while True:

                char = getch()

                if char.lower() in ("y", "n"):

                    print(char)

                    if char == 'y':

                        kmerbuild = True

                    elif char == 'n':

                        kmerbuild = False

                    break

    # ?build bwa index
    bwaindexfile = os.path.basename(args.genome)

    bwatestindex = os.path.join(args.saved, bwaindexfile+'.sa')

    bwaindex = os.path.join(args.saved, bwaindexfile)

    bwabuild = True

    if os.path.isfile(bwatestindex):

        if not args.docker:

            print('find:', bwatestindex)

            bwamess = "Found bwa index file " + bwatestindex + ". Do you want rebuild it? Press Y or N to continue:"

            print(bwamess)

            while True:

                char = getch()

                if char.lower() in ("y", "n"):

                    print(char)

                    if char == 'y':

                        bwabuild = True

                    elif char == 'n':

                        bwabuild = False

                    break

    print("genomesize:",genomesize, "kmer:",kmer, "jfkmerfile:",
          jfkmerfile, "kmerbuild:", kmerbuild, "bwabuild:", bwabuild, "threads:", args.threads)

    # Build Jellyfish index
    if kmerbuild:

        jfcount = jellyfish.jfcount(jfpath=args.jellyfish, mer=kmer, infile=args.genome, output=jfkmerfile,
                                    threads=args.threads, lowercount=lowercount, size=jfsize)

        if jfcount:

            print("JellyFish Count finished ...")

        else:

            print("JellyFish Count Error!!!")

            sys.exit(1)

    else:

        print("Use ", jfkmerfile)
    # End build Jellyfish index

    if bwabuild:

        bwa.bwaindex(args.bwa, args.genome, args.saved)

        print("bwa index build finished ...")

    else:

        print("Use", bwatestindex)

    jffilteredprobe = list()

#####

    if genomesize < 1000:

        fastain = Fasta(args.input)

        jffpbrunerlist = list()

        for seqname in fastain.keys():

            chrlen = len(fastain[seqname])

            if chrlen < spsize:

                start = 0

                end = chrlen - 1

                jffpbruner = jellyfish.JFfpbruner(jfpath=args.jellyfish, jfkmerfile=jfkmerfile, mer=kmer,
                                                  pyfasta=fastain, seqname=seqname, pblength=args.length,
                                                  maxkmerscore=maxkmerscore, start=start,
                                                  end=end, step=step)

                jffpbrunerlist.append(jffpbruner)

            else:

                chrblock = int(chrlen/spsize) + 1

                for i in range(chrblock):

                    start = i * spsize

                    end = start + spsize - 1

                    if end >= chrlen:

                        end = chrlen - 1

                    jffpbruner = jellyfish.JFfpbruner(jfpath=args.jellyfish, jfkmerfile=jfkmerfile, mer=kmer,
                                                  pyfasta=fastain, seqname=seqname, pblength=args.length,
                                                  maxkmerscore=maxkmerscore, start=start,
                                                  end=end, step=step)

                    jffpbrunerlist.append(jffpbruner)

        jffinished = 0

        print(len(jffpbrunerlist))

        for curpblist in jfpool.imap_unordered(jellyfish.kmerfilterprobe, jffpbrunerlist):

            jffilteredprobe.extend(curpblist)

            jffinished += 1

            print("Jellyfish filter: ",jffinished,'/',len(jffpbrunerlist), sep='')

        jfpool.close()

        print('Jellyfish filter finished!!')

    else:

        ### split fa file when geome size greater than 1 Gb

        print("genome size > 1G")

        subFas = spgenome.spgenome(args.input, args.saved)

        for subFafile in subFas:
            print(subFafile)
            fastain = Fasta(subFafile)

            jffpbrunerlist = list()

            for seqname in fastain.keys():

                chrlen = len(fastain[seqname])

                if chrlen < spsize:

                    start = 0

                    end = chrlen - 1

                    jffpbruner = jellyfish.JFfpbruner(jfpath=args.jellyfish, jfkmerfile=jfkmerfile, mer=kmer,
                                                      pyfasta=fastain, seqname=seqname, pblength=args.length,
                                                      maxkmerscore=maxkmerscore, start=start,
                                                      end=end, step=step)

                    jffpbrunerlist.append(jffpbruner)

                else:

                    chrblock = int(chrlen / spsize) + 1

                    for i in range(chrblock):

                        start = i * spsize

                        end = start + spsize - 1

                        if end >= chrlen:
                            end = chrlen - 1

                        jffpbruner = jellyfish.JFfpbruner(jfpath=args.jellyfish, jfkmerfile=jfkmerfile, mer=kmer,
                                                          pyfasta=fastain, seqname=seqname, pblength=args.length,
                                                          maxkmerscore=maxkmerscore, start=start,
                                                          end=end, step=step)

                        jffpbrunerlist.append(jffpbruner)

            jffinished = 0

            print(len(jffpbrunerlist))

            for curpblist in jfpool.imap_unordered(jellyfish.kmerfilterprobe, jffpbrunerlist):
                jffilteredprobe.extend(curpblist)

                jffinished += 1

                print(subFafile + " Jellyfish filter: ", jffinished, '/', len(jffpbrunerlist), sep='')

        jfpool.close()

        print('Jellyfish filter finished!!')

    tmppbfa = os.path.join(args.saved, os.path.basename(args.input)+'_tmp_probe.fa')

    tmppbfaio = open(tmppbfa, 'w')

    seqnum = 0

    for tmppb in jffilteredprobe:

        print('>','seq',seqnum, sep='',file=tmppbfaio)

        print(tmppb,file=tmppbfaio)

        seqnum += 1

    tmppbfaio.close()

    del jffilteredprobe

    print("run bwafilter")
    print("maxxs:", int(args.length*args.homology/100))

    bwafiltedpb = bwa.bwafilter(bwabin=args.bwa, reffile=bwaindex, inputfile=tmppbfa, minas=args.length,
                                maxxs=int(args.length*args.homology/100), threadnumber=args.threads)

    print("bwafiltedpb len",len(bwafiltedpb))

    print(bwafiltedpb[0:10])

    tmpbwaftlist = os.path.join(args.saved, os.path.basename(args.input)+'.bed')

    alltmpbwaftlist = os.path.join(args.saved, os.path.basename(args.input)+'_all.bed')

    tmpbwaftlistio = open(tmpbwaftlist,'w')

    allbwaftlistio = open(alltmpbwaftlist,'w')

    seqlenfile = os.path.join(args.saved, os.path.basename(args.input)+'.len')

    seqlenio = open(seqlenfile,'w')

    seqlength = bwa.bwareflength(bwabin=args.bwa, reffile=bwaindex)

    for seqname in seqlength:

            print(seqname, seqlength[seqname], sep='\t', file=seqlenio)

    seqlenio.close()

    oligobefortmf = list()

    for pbtmp in bwafiltedpb:

        # print(pbtmp, file=tmpbwaftlistio)
        nowpbcounter = dict()

        nowpbcounter['seq'] = pbtmp

        nowpbcounter['dTm'] = args.dtm

        nowpbcounter['rprimer'] = args.primer

        oligobefortmf.append(nowpbcounter)

    keepedprobe = list()

    ctedpb = 0

    oligobefortmflen = len(oligobefortmf)

    print("oligobefortmflen:",oligobefortmflen)

    pbftpool = Pool()

    for (pb, keep) in pbftpool.imap_unordered(probefilter, oligobefortmf):

        if keep:

            keepedprobe.append(pb)
                # print(pb, file=tmpbwaftlistio)
        ctedpb += 1

        if ctedpb % 10000 == 0:

            print(ctedpb,'/',oligobefortmflen)

    pbdictbychr = dict()

    pbftpool.close()

    for pb in keepedprobe:

        seq, chro, start = pb.split('\t')

        start = int(start)

        if chro in pbdictbychr:

            pbdictbychr[chro][start] = seq

        else:

            pbdictbychr[chro] = dict()

            pbdictbychr[chro][start] = seq

    lenrprimer = len(args.primer)

    if lenrprimer == 0:

            lenrprimer = 5

    slidwindow = lenrprimer+args.length

    for chro in pbdictbychr:

        startn = 0

        for startnow in sorted(pbdictbychr[chro]):

            endnow = startnow + args.length - 1

            print(chro, startnow, endnow, pbdictbychr[chro][startnow],file=allbwaftlistio,sep='\t')

            if startnow > startn+slidwindow:
                    #startn = startnow+slidwindow
                startn = startnow

                print(chro, startnow, endnow, pbdictbychr[chro][startnow], file=tmpbwaftlistio, sep='\t')

    tmpbwaftlistio.close()

    allbwaftlistio.close()

    print("Job finshed!!")

def probefilter(nowpbcounter):

    sequence, seqname, start = nowpbcounter['seq'].split('\t')

    dTm = nowpbcounter['dTm']

    rPrimer = nowpbcounter['rprimer']

    keep = False

    if prefilter.atcg_filter(sequence, 5):

        # print(self.sequence, " not pass atcg")
        pass

    elif dTm == -1:

        keep = True

    else:
        if rPrimer:

            if primer3_filter.primer3_filter_withRprimer(sequence, rPrimer, dtm=dTm):

                pass

            else:

                keep = True
        else:

            if primer3_filter.primer3_filter(sequence, dtm=dTm):

                pass

            else:

                keep = True

    return (nowpbcounter['seq'], keep)

def check_options(parser):

    args = parser.parse_args()

    # Start check bwa
    if args.bwa:

        if not os.path.exists(args.bwa):

            print("Can not locate bwa, please input full path of bwa\n")

            parser.print_help()

            sys.exit(1)

        bwaversion = bwa.bwaversion(args.bwa)

        if bwaversion == 'None':

            print("Can not locate bwa, please input full path of bwa\n")

            parser.print_help()

            sys.exit(1)

    else:

        bwapath = which('bwa')

        if bwapath:

            bwaversion = bwa.bwaversion(bwapath[0])

            if bwaversion == 'None':

                print("Can not locate bwa, please input full path of bwa\n")

                parser.print_help()

                sys.exit(1)

            else:

                args.bwa = bwapath[0]

        else:

            print("Can not locate bwa, please input full path of bwa\n")

            parser.print_help()

            sys.exit(1)

    # End check bwa

    # Start check jellyfish
    if args.jellyfish:

        if not os.path.exists(args.jellyfish):

            print("Can not locate jellyfish, please input full path of jellyfish\n")

            parser.print_help()

            sys.exit(1)

        jellyfishversion = jellyfish.jfversion(args.jellyfish)

        if jellyfishversion == 'None':

            print("Can not locate jellyfish, please input full path of jellyfish\n")

            parser.print_help()

            sys.exit(1)

    else:

        jellyfishpath = which('jellyfish')

        if jellyfishpath:

            jellyfishversion = jellyfish.jfversion(jellyfishpath[0])

            if jellyfishversion == 'None':

                print("Can not locate jellyfish, please input full path of jellyfish\n")

                parser.print_help()

                sys.exit(1)

            else:

                args.jellyfish = jellyfishpath[0]

        else:

            print("Can not locate jellyfish, please input full path of jellyfish\n")

            parser.print_help()

            sys.exit(1)
    # End check jellyfish

    if not os.path.exists(args.genome):

        print("Can not locate genome file, please input genome file.\n")

        parser.print_help()

        sys.exit(1)

    if not os.path.exists(args.input):

        print("Can not locate input file, please input input file.\n")

        parser.print_help()

        sys.exit(1)

    if args.homology > 100 or args.homology < 50:

        print("Please set homology between 50 and 100.\n")

        parser.print_help()

        sys.exit(1)

    if args.dtm > 37 or args.dtm < -1:
    # dtm = -1 skip calculate dtm
        print("Please set dtm between 0 and 37.\n")

        parser.print_help()

        sys.exit(1)

    if args.skipdtm == True:

        args.dtm = -1

        print("skip calculate dtm")

    if args.length > 50:

        args.dtm = -1

        print("oligo length longer than 50nt, skip calculate dtm")

    if args.step < 1:

        print("step must >1.\n")

        parser.print_help()

        sys.exit(1)

    # Start check saved folder
    if os.path.exists(args.saved):

        if not args.docker:
            print("The output folder ",args.saved, " already exists.")
            print('''
                Press Y to use it for output files. Everything in this folder will be removed.
                Press N and set -s/--saved to a different folder:
                ''')

            while True:

                char = getch()

                if char.lower() in ("y", "n"):

                    print(char)

                    if char.lower() == 'n':

                        sys.exit(1)

                    break

    else:

        os.mkdir(args.saved)
    # End check saved folder

    # Print Checked information
    print("#"*40)

    print("bwa version:", args.bwa, bwaversion)

    print("jellyfish version:", args.jellyfish, jellyfishversion)

    print("genome file:", args.genome)

    print("input file:", args.input)

    print("5\' labeled R primer:", args.primer)

    print("result output folder:",  os.path.realpath(args.saved))

    print("threads number:", args.threads)

    print("homology:", args.homology)

    print("dtm:", args.dtm)

    if args.dtm == -1:

        print("Warning: skip calculate dtm.")

    print("#"*40)

    return args

def getch():
    """
    For yes/no choice
    """
    import sys, tty, termios
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

def which(filename):
    """docstring for which"""
    locations = os.environ.get("PATH").split(os.pathsep)
    candidates = []
    for location in locations:
        candidate = os.path.join(location, filename)
        if os.path.isfile(candidate):
            candidates.append(candidate)
    return candidates

def get_options():

    parser = argparse.ArgumentParser(description="Chorus2 Software for Oligo FISH probe design", prog='Chorus2',
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     epilog="Example:\n"
                                            "  Chorus2 -i TAIR10_chr_all.fas -g TAIR10_chr_all.fas -t 4 \\ \n"
                                            "          -j /opt/software/jellyfish/bin/jellyfish -b /opt/software/bwa/bwa -s sample"
                                     )

    parser.add_argument('--version', action='version', version='%(prog)s 2.1')

    parser.add_argument('-j', '--jellyfish', dest='jellyfish', help='The path where Jellyfish software installed')

    parser.add_argument('-b', '--bwa', dest='bwa', help='The path where BWA software installed')

    parser.add_argument('-g', '--genome', dest='genome', help='Fasta format genome file, should include all sequences from genome', required=True)

    parser.add_argument('-i', '--input', dest='input', help='Fasta format input file, can be whole genome, a chromosome or one region from genome', required=True)

    parser.add_argument('-s', '--save', dest='saved', help='The output folder for saving results', default='probes')

    parser.add_argument('-p', '--primer', dest='primer', help='A specific 5\' labeled R primer for PCR reaction. For example: CGTGGTCGCGTCTCA. (Default is none)', default='')

    parser.add_argument('-t', '--threads', dest='threads', help='Number of threads or CPUs to use. (Default: 1)',
                        default=1, type=int)

    parser.add_argument('-l', '--length', dest='length', help='The probe length. (Default: 45)', default=45, type=int)

    parser.add_argument('--homology', dest='homology', help='The maximum homology(%%) between target sequence and probe, range from 50 to 100. (Default: 75)', default=75, type=float)

    parser.add_argument('-d', '--dtm', dest='dtm', help='The minimum value of dTm (hybrid Tm - hairpin Tm), range from 0 to 37. (Default: 10)', default=10, type=float)

    parser.add_argument('--skipdtm', dest='skipdtm', help='skip calculate dtm, for oligo longer than 50.', default=False, type=bool)

    parser.add_argument('--step', dest='step', help='The step length for k-mer searching in a sliding window, step length>=1. (Default: 5)', default=5, type=int)

    parser.add_argument('--docker', help='Only used in Docker version of Chorus', default=False)

    parser.add_argument('--ploidy', dest='ploidy', default=2, type=int, help='The ploidy of the given genome (test version). (Default: 2)')
    # parser.parse_args(['--version'])
    # args = parser.parse_args()

    return parser

if __name__ == "__main__":

    try:

        main()

    except KeyboardInterrupt:

        sys.stderr.write("User interrupt\n")

        sys.exit(0)


import os
import pandas as pd
import re

business_path = "C:/Users/David/YELP_PROJECT/datasets/yelp_academic_dataset_business_cleaned.csv"  # Clean business path
path = "C:/Users/David/YELP_PROJECT/datasets/yelp_academic_dataset_review.csv"  # input path for chunked reviews
path2 = "C:/Users/David/YELP_PROJECT/datasets/review_cleaned.csv"  # output path for chunked reviews
business = pd.read_csv(business_path, error_bad_lines=False, encoding="ISO-8859-1").fillna(value='NA')
reviews_len = 0 # review length counter

# Init lastbusiness variables
lastbusiness1 = pd.DataFrame(columns=('user_id','review_id','text','business_id','stars','date','type'))
lastbusiness2 = pd.DataFrame(columns=('user_id','review_id','text','business_id','stars','date','type'))

review_1 = pd.read_csv(path, error_bad_lines=False, encoding="ISO-8859-1").fillna(value='NA')
# drop unneeded columns
review_1 = review_1.drop('funny', 1).drop('cool', 1).drop('useful', 1)
# only keep rows which match business_id from the business dataframe
review_1 = (review_1[review_1['business_id'].isin(business['business_id'])])
print(path, 'new length =', len(review_1))
review_1.to_csv(path2)


# Day_07_02_stock.py
import matplotlib.pyplot as plt
import pandas as pd
import nltk
import numpy as np
import tensorflow.keras as keras
from sklearn import preprocessing, model_selection

# 퀴즈
# stock_daily.csv 파일로부터 x, y를 반환하는 함수를 만드세요
# batch_size, seq_length, n_features = 32, 7, 5

# 퀴즈
# 80%의 데이터로 학습하고 20%의 데이터에 대해 결과를 예측하세요
def get_xy():
    stock = pd.read_csv('data/stock_daily.csv', skiprows=2, header=None)
    # print(stock)      # [732 rows x 5 columns]

    # values = preprocessing.scale(stock.values)
    # values = preprocessing.minmax_scale(stock.values)
    scaler = preprocessing.MinMaxScaler()
    values = scaler.fit_transform(stock.values)
    values = values[::-1]

    # print(scaler.scale_)
    # print(scaler.data_max_)
    # print(scaler.data_min_)

    grams = nltk.ngrams(values, 7+1)
    grams = np.float32(list(grams))
    # print(grams.shape)            # (725, 8, 5)

    x = np.float32([g[:-1] for g in grams])
    y = np.float32([g[-1, -1:] for g in grams])
    # print(x.shape, y.shape)       # (725, 7, 5) (725, 1)

    return x, y, scaler.data_min_[-1], scaler.data_max_[-1]

# 퀴즈
# 앞에서 만든 데이터에 대해 모델을 구축하세요
def model_stock():
    x, y, data_min, data_max = get_xy()

    data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)
    x_train, x_test, y_train, y_test = data

    model = keras.Sequential()
    model.add(keras.layers.InputLayer(input_shape=x.shape[1:]))
    model.add(keras.layers.SimpleRNN(32, return_sequences=False))
    model.add(keras.layers.Dense(1))
    model.summary()

    model.compile(optimizer=keras.optimizers.Adam(0.001),
                  loss=keras.losses.mse,
                  metrics='mae')

    model.fit(x_train, y_train, epochs=100, verbose=2)
    print(model.evaluate(x_test, y_test, verbose=0))

    # 퀴즈
    # 정답과 예측 결과를 시각화하세요
    p = model.predict(x_test)

    plt.subplot(1, 2, 1)
    plt.plot(y_test, 'r')
    plt.plot(p, 'g')

    # 퀴즈
    # 예측 결과를 원래 값으로 복구하세요
    plt.subplot(1, 2, 2)
    plt.plot(y_test, 'r')
    plt.plot(p, 'g')

    plt.show()

model_stock()


from datetime import timedelta

from django.test import TestCase
from django.utils.timezone import now
from django.core.urlresolvers import reverse

from request.models import Request
from request.tracking.models import Visit, Visitor

class VisitorModelTest(TestCase):
    def test_str(self):
        visitor = Visitor.objects.create(key='foo')
        visitor.__str__()

    def test_first_time(self):
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        first_time = visitor.first_time
        # 2nd request
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        self.assertEqual(first_time, visitor.first_time)

    def test_last_time(self):
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        last_time = visitor.last_time
        # 2nd request
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        self.assertLess(last_time, visitor.last_time)

    def test_recency(self):
        self.skipTest("Not implemented")

    def test_ips(self):
        self.client.get('/admin/login/')
        ips = Visitor.objects.first().ips
        self.assertIn('127.0.0.1', ips)
        # Change IP
        Request.objects.update(ip='127.0.0.2')
        self.client.get('/admin/login/')
        ips = Visitor.objects.first().ips
        self.assertIn('127.0.0.1', ips)
        self.assertIn('127.0.0.2', ips)
        self.assertEqual(2, len(ips))

    def test_in_progress(self):
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        self.assertTrue(visitor.in_progress())
        # Change request time and test
        Request.objects.update(time=now()-timedelta(days=1))
        self.assertFalse(visitor.in_progress())

    def test_get_absolute_url(self):
        self.client.get('/admin/login/')
        visitor = Visitor.objects.first()
        url = visitor.get_absolute_url()
        wanted_url = reverse('admin:tracking_visitor_change', args=(visitor.id,))
        self.assertEqual(url, wanted_url)

    def test_get_delete_url(self):
        self.client.get('/admin/login/')
        url = Visitor.objects.first().get_delete_url()
        self.assertEqual(url, '/admin/tracking/visitor/1/delete/')

class VisitModelTest(TestCase):
    def test_str(self):
        visit = Visit.objects.create(visitor=Visitor.objects.create(key='foo'))
        visit.__str__()

    def test_first_time(self):
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        first_time = visit.first_time
        # 2nd request
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        self.assertEqual(first_time, visit.first_time)

    def test_last_time(self):
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        last_time = visit.last_time
        # 2nd request
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        self.assertLess(last_time, visit.last_time)

    def test_in_progress(self):
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        self.assertTrue(visit.in_progress())
        # Change request time and test
        Request.objects.update(time=now()-timedelta(days=1))
        self.assertFalse(visit.in_progress())

    def test_get_absolute_url(self):
        self.client.get('/admin/login/')
        visit = Visit.objects.first()
        url = visit.get_absolute_url()
        wanted_url = reverse('admin:tracking_visit_change', args=(visit.id,))
        self.assertEqual(url, wanted_url)

    def test_get_delete_url(self):
        self.client.get('/admin/login/')
        url = Visit.objects.first().get_delete_url()
        self.assertEqual(url, '/admin/tracking/visit/1/delete/')

    def test_ip(self):
        self.client.get('/admin/login/')
        ip = Visit.objects.first().ip
        self.assertEqual(ip, '127.0.0.1')

    def test_user_agent(self):
        self.client.get('/admin/login/')
        user_agent = Visit.objects.first().browser
        self.assertEqual(user_agent, 'Other')


"""
Transform from string or AST representations of input, to AST, file, or str input_str.
"""
import ast
from ast import (
    Assign,
    Attribute,
    ClassDef,
    Expr,
    FunctionDef,
    Load,
    Module,
    Name,
    Return,
    Store,
    Tuple,
    arguments,
)
from collections import OrderedDict
from functools import partial
from itertools import chain

from black import Mode, format_str

from doctrans.ast_utils import (
    NoneStr,
    get_value,
    maybe_type_comment,
    param2argparse_param,
    param2ast,
    set_arg,
    set_value,
)
from doctrans.defaults_utils import set_default_doc
from doctrans.emitter_utils import (
    RewriteName,
    _make_call_meth,
    get_internal_body,
    to_docstring,
)
from doctrans.pure_utils import PY3_8, rpartial, simple_types, tab
from doctrans.source_transformer import to_code

def argparse_function(
    intermediate_repr,
    emit_default_doc=False,
    emit_default_doc_in_return=False,
    function_name="set_cli_args",
    function_type="static",
):
    """
    Convert to an argparse FunctionDef

    :param intermediate_repr: a dictionary of form
        {  "name": Optional[str],
           "type": Optional[str],
           "doc": Optional[str],
           "params": OrderedDict[str, {'typ': str, 'doc': Optional[str], 'default': Any}]
           "returns": Optional[OrderedDict[Literal['return_type'],
                                           {'typ': str, 'doc': Optional[str], 'default': Any}),)]] }
    :type intermediate_repr: ```dict```

    :param emit_default_doc: Whether help/docstring should include 'With default' text
    :type emit_default_doc: ```bool```

    :param emit_default_doc_in_return: Whether help/docstring in return should include 'With default' text
    :type emit_default_doc_in_return: ```bool```

    :param function_name: name of function_def
    :type function_name: ```str```

    :param function_type: Type of function, static is static or global method, others just become first arg
    :type function_type: ```Literal['self', 'cls', 'static']```

    :return:  AST node for function definition which constructs argparse
    :rtype: ```FunctionDef```
    """
    function_name = function_name or intermediate_repr["name"]
    function_type = function_type or intermediate_repr["type"]
    internal_body = get_internal_body(
        target_name=function_name,
        target_type=function_type,
        intermediate_repr=intermediate_repr,
    )

    return FunctionDef(
        args=arguments(
            args=[set_arg("argument_parser")],
            # None if function_type in frozenset((None, "static"))
            # else set_arg(function_type),
            defaults=[],
            kw_defaults=[],
            kwarg=None,
            kwonlyargs=[],
            posonlyargs=[],
            vararg=None,
            arg=None,
        ),
        body=list(
            chain.from_iterable(
                (
                    iter(
                        (
                            Expr(
                                set_value(
                                    "\n    Set CLI arguments\n\n    "
                                    ":param argument_parser: argument parser\n    "
                                    ":type argument_parser: ```ArgumentParser```\n\n    "
                                    "{return_params}".format(
                                        return_params=(
                                            lambda returns: ":return: argument_parser{return_doc}\n    "
                                            "{rtype}".format(
                                                return_doc=", {}".format(returns["doc"])
                                                if "doc" in returns
                                                else "",
                                                rtype=":rtype: ```ArgumentParser```\n    "
                                                if intermediate_repr["returns"][
                                                    "return_type"
                                                ].get("typ")
                                                in (None, "None", NoneStr)
                                                else ":rtype: ```Tuple[ArgumentParser, {returns[typ]}]```\n{tab}"
                                                "".format(returns=returns, tab=tab),
                                            )
                                        )(
                                            returns=set_default_doc(
                                                next(
                                                    iter(
                                                        intermediate_repr[
                                                            "returns"
                                                        ].items()
                                                    )
                                                ),
                                                emit_default_doc=emit_default_doc_in_return,
                                            )[1]
                                        )
                                        if "return_type"
                                        in (
                                            intermediate_repr.get("returns") or iter(())
                                        )
                                        else ":return: argument_parser\n    "
                                        ":rtype: ```ArgumentParser```\n    "
                                    )
                                )
                            ),
                            Assign(
                                targets=[
                                    Attribute(
                                        Name("argument_parser", Load()),
                                        "description",
                                        Store(),
                                    )
                                ],
                                value=set_value(intermediate_repr["doc"]),
                                lineno=None,
                                expr=None,
                                **maybe_type_comment
                            ),
                        )
                    ),
                    filter(
                        None,
                        (
                            *(
                                (
                                    map(
                                        partial(
                                            param2argparse_param,
                                            emit_default_doc=emit_default_doc,
                                        ),
                                        intermediate_repr["params"].items(),
                                    )
                                )
                                if "params" in intermediate_repr
                                else ()
                            ),
                            *(
                                internal_body[
                                    2
                                    if len(internal_body) > 1
                                    and isinstance(internal_body[1], Assign)
                                    and internal_body[1].targets[0].id
                                    == "argument_parser"
                                    else 1 :
                                ]
                                if internal_body
                                and isinstance(internal_body[0], Expr)
                                and isinstance(get_value(internal_body[0].value), str)
                                else internal_body
                            ),
                            None
                            if internal_body and isinstance(internal_body[-1], Return)
                            else (
                                Return(
                                    value=Tuple(
                                        ctx=Load(),
                                        elts=[
                                            Name("argument_parser", Load()),
                                            set_value(
                                                intermediate_repr["returns"][
                                                    "return_type"
                                                ]["default"]
                                            )
                                            if intermediate_repr["returns"][
                                                "return_type"
                                            ]["default"].startswith("```")
                                            and intermediate_repr["returns"][
                                                "return_type"
                                            ]["default"].endswith("```")
                                            else ast.parse(
                                                intermediate_repr["returns"][
                                                    "return_type"
                                                ]["default"]
                                            )
                                            .body[0]
                                            .value,
                                        ],
                                        expr=None,
                                    ),
                                    expr=None,
                                )
                                if "default"
                                in (
                                    intermediate_repr.get("returns")
                                    or {"return_type": iter(())}
                                )["return_type"]
                                else Return(
                                    value=Name("argument_parser", Load()), expr=None
                                )
                            ),
                        ),
                    ),
                )
            )
        ),
        decorator_list=[],
        name=function_name,
        returns=None,
        lineno=None,
        arguments_args=None,
        identifier_name=None,
        stmt=None,
        **maybe_type_comment
    )

def class_(
    intermediate_repr,
    emit_call=False,
    class_name="ConfigClass",
    class_bases=("object",),
    decorator_list=None,
    emit_default_doc=False,
):
    """
    Construct a class

    :param intermediate_repr: a dictionary of form
        {  "name": Optional[str],
           "type": Optional[str],
           "doc": Optional[str],
           "params": OrderedDict[str, {'typ': str, 'doc': Optional[str], 'default': Any}]
           "returns": Optional[OrderedDict[Literal['return_type'],
                                           {'typ': str, 'doc': Optional[str], 'default': Any}),)]] }
    :type intermediate_repr: ```dict```

    :param emit_call: Whether to emit a `__call__` method from the `_internal` IR subdict
    :type emit_call: ```bool```

    :param class_name: name of class
    :type class_name: ```str```

    :param class_bases: bases of class (the generated class will inherit these)
    :type class_bases: ```Iterable[str]```

    :param decorator_list: List of decorators
    :type decorator_list: ```Optional[Union[List[Str], List[]]]```

    :param emit_default_doc: Whether help/docstring should include 'With default' text
    :type emit_default_doc: ```bool```

    :return: Class AST of the docstring
    :rtype: ```ClassDef```
    """
    returns = (
        intermediate_repr["returns"]
        if "return_type" in intermediate_repr.get("returns", {})
        else OrderedDict()
    )

    param_names = frozenset(intermediate_repr["params"].keys())
    if returns:
        intermediate_repr["params"].update(returns)
        del intermediate_repr["returns"]

    internal_body = intermediate_repr.get("_internal", {}).get("body", [])
    # TODO: Add correct classmethod/staticmethod to decorate function using `annotate_ancestry` and first-field checks
    # Such that the `self.` or `cls.` rewrite only applies to non-staticmethods
    # assert internal_body, "Expected `internal_body` to have contents"
    if internal_body and param_names:
        internal_body = list(
            map(
                ast.fix_missing_locations,
                map(RewriteName(param_names).visit, internal_body),
            )
        )

    return ClassDef(
        bases=list(map(rpartial(Name, Load()), class_bases)),
        body=list(
            chain.from_iterable(
                (
                    (
                        Expr(
                            set_value(
                                to_docstring(
                                    intermediate_repr,
                                    indent_level=0,
                                    emit_separating_tab=False,
                                    emit_default_doc=emit_default_doc,
                                    emit_types=False,
                                )
                                .replace("\n:param ", "{tab}:cvar ".format(tab=tab))
                                .replace(
                                    "{tab}:cvar ".format(tab=tab),
                                    "\n{tab}:cvar ".format(tab=tab),
                                    1,
                                )
                                .rstrip()
                            )
                        ),
                    ),
                    map(param2ast, intermediate_repr["params"].items()),
                    iter(
                        (
                            _make_call_meth(
                                internal_body,
                                returns["return_type"]["default"]
                                if "default"
                                in (
                                    (returns or {"return_type": iter(())}).get(
                                        "return_type"
                                    )
                                    or iter(())
                                )
                                else None,
                                param_names,
                            ),
                        )
                        if emit_call and internal_body
                        else tuple()
                    ),
                )
            )
        ),
        decorator_list=list(map(rpartial(Name, Load()), decorator_list))
        if decorator_list
        else [],
        keywords=[],
        name=class_name,
        expr=None,
        identifier_name=None,
    )

def docstring(intermediate_repr, docstring_format="rest", emit_default_doc=True):
    """
    Converts an AST to a docstring

    :param intermediate_repr: a dictionary of form
        {  "name": Optional[str],
           "type": Optional[str],
           "doc": Optional[str],
           "params": OrderedDict[str, {'typ': str, 'doc': Optional[str], 'default': Any}]
           "returns": Optional[OrderedDict[Literal['return_type'],
                                           {'typ': str, 'doc': Optional[str], 'default': Any}),)]] }
    :type intermediate_repr: ```dict```

    :param docstring_format: Format of docstring
    :type docstring_format: ```Literal['rest', 'numpy', 'google']```

    :param emit_default_doc: Whether help/docstring should include 'With default' text
    :type emit_default_doc: ```bool```

    :return: docstring
    :rtype: ```str```
    """
    if docstring_format != "rest":
        raise NotImplementedError(docstring_format)

    return "\n{doc}\n\n{params}\n{returns}\n".format(
        doc=intermediate_repr["doc"],
        params="\n".join(
            ":param {name}: {param[doc]}\n{type_param}".format(
                name=name,
                param=set_default_doc((name, param), emit_default_doc=emit_default_doc)[
                    1
                ],
                type_param=":type {name}: ```{typ}```\n".format(
                    name=name,
                    typ=param["typ"],
                )
                if param.get("typ")
                else "",
            )
            for name, param in intermediate_repr["params"].items()
        ),
        returns="\n".join(
            (
                lambda param: filter(
                    None,
                    (
                        ":return: {param[doc]}".format(param=param)
                        if "doc" in param
                        else None,
                        None
                        if param.get("typ") is None
                        else ":rtype: ```{param[typ]}```".format(param=param),
                    ),
                )
                if param
                else param
            )(
                set_default_doc(
                    next(iter(intermediate_repr["returns"].items())),
                    emit_default_doc=emit_default_doc,
                )[1]
                if "return_type" in (intermediate_repr.get("returns") or iter(()))
                else ""
            )
        ),
    )

def file(node, filename, mode="a", skip_black=False):
    """
    Convert AST to a file

    :param node: AST node
    :type node: ```Union[Module, ClassDef, FunctionDef]```

    :param filename: emit to this file
    :type filename: ```str```

    :param mode: Mode to open the file in, defaults to append
    :type mode: ```str```

    :param skip_black: Skip formatting with black
    :type skip_black: ```bool```

    :return: None
    :rtype: ```NoneType```
    """
    if isinstance(node, (ClassDef, FunctionDef)):
        node = Module(body=[node], type_ignores=[], stmt=None)
    src = to_code(node)
    if not skip_black:
        src = format_str(
            src,
            mode=Mode(
                target_versions=set(),
                line_length=119,
                is_pyi=False,
                string_normalization=False,
            ),
        )
    with open(filename, mode) as f:
        f.write(src)

def function(
    intermediate_repr,
    function_name,
    function_type,
    emit_default_doc=False,
    docstring_format="rest",
    indent_level=2,
    emit_separating_tab=PY3_8,
    inline_types=True,
    emit_as_kwonlyargs=True,
):
    """
    Construct a function from our IR

    :param intermediate_repr: a dictionary of form
        {  "name": Optional[str],
           "type": Optional[str],
           "doc": Optional[str],
           "params": OrderedDict[str, {'typ': str, 'doc': Optional[str], 'default': Any}]
           "returns": Optional[OrderedDict[Literal['return_type'],
                                           {'typ': str, 'doc': Optional[str], 'default': Any}),)]] }
    :type intermediate_repr: ```dict```

    :param function_name: name of function_def
    :type function_name: ```Optional[str]```

    :param function_type: Type of function, static is static or global method, others just become first arg
    :type function_type: ```Optional[Literal['self', 'cls', 'static']]```

    :param docstring_format: Format of docstring
    :type docstring_format: ```Literal['rest', 'numpy', 'google']```

    :param emit_default_doc: Whether help/docstring should include 'With default' text
    :type emit_default_doc: ```bool```

    :param indent_level: docstring indentation level whence: 0=no_tabs, 1=one tab; 2=two tabs
    :type indent_level: ```int```

    :param emit_separating_tab: docstring decider for whether to put a tab between :param and return and desc
    :type emit_separating_tab: ```bool```

    :param inline_types: Whether the type should be inline or in docstring
    :type inline_types: ```bool```

    :param emit_as_kwonlyargs: Whether argument(s) emitted must be keyword only
    :type emit_as_kwonlyargs: ```bool```

    :return: AST node for function definition
    :rtype: ```FunctionDef```
    """
    params_no_kwargs = tuple(
        filter(
            lambda param: not param[0].endswith("kwargs"),
            intermediate_repr["params"].items(),
        )
    )

    function_name = function_name or intermediate_repr["name"]
    function_type = function_type or intermediate_repr["type"]

    args = (
        [] if function_type in frozenset((None, "static")) else [set_arg(function_type)]
    )
    from doctrans.emitter_utils import ast_parse_fix

    args_from_params = list(
        map(
            lambda param: set_arg(
                annotation=(
                    Name(param[1]["typ"], Load())
                    if param[1]["typ"] in simple_types
                    else ast_parse_fix(param[1]["typ"])
                )
                if inline_types and "typ" in param[1]
                else None,
                arg=param[0],
            ),
            params_no_kwargs,
        ),
    )
    defaults_from_params = list(
        map(
            lambda param: set_value(None)
            if param[1].get("default") in (None, "None", NoneStr)
            else set_value(param[1].get("default")),
            params_no_kwargs,
        )
    )
    if emit_as_kwonlyargs:
        kwonlyargs, kw_defaults, defaults = args_from_params, defaults_from_params, []
    else:
        kwonlyargs, kw_defaults, defaults = [], [], defaults_from_params
        args += args_from_params

    internal_body = get_internal_body(
        target_name=function_name,
        target_type=function_type,
        intermediate_repr=intermediate_repr,
    )
    return_val = (
        Return(
            value=ast.parse(
                intermediate_repr["returns"]["return_type"]["default"].strip("`")
            )
            .body[0]
            .value,
            expr=None,
        )
        if (intermediate_repr.get("returns") or {"return_type": {}})["return_type"].get(
            "default"
        )
        else None
    )

    return FunctionDef(
        args=arguments(
            args=args,
            defaults=defaults,
            kw_defaults=kw_defaults,
            kwarg=next(
                map(
                    lambda param: set_arg(param[0]),
                    filter(
                        lambda param: param[0].endswith("kwargs"),
                        intermediate_repr["params"].items(),
                    ),
                ),
                None,
            ),
            kwonlyargs=kwonlyargs,
            posonlyargs=[],
            vararg=None,
            arg=None,
        ),
        body=list(
            filter(
                None,
                (
                    Expr(
                        set_value(
                            to_docstring(
                                intermediate_repr,
                                emit_default_doc=emit_default_doc,
                                docstring_format=docstring_format,
                                emit_types=not inline_types,
                                indent_level=indent_level,
                                emit_separating_tab=emit_separating_tab,
                            )
                        )
                    ),
                    *(
                        internal_body[:-1]
                        if internal_body
                        and isinstance(internal_body[-1], Return)
                        and return_val
                        else internal_body
                    ),
                    return_val,
                ),
            )
        ),
        decorator_list=[],
        name=function_name,
        returns=(
            ast.parse(intermediate_repr["returns"]["return_type"]["typ"]).body[0].value
            if inline_types
            and (intermediate_repr.get("returns") or {"return_type": {}})[
                "return_type"
            ].get("typ")
            else None
        ),
        lineno=None,
        arguments_args=None,
        identifier_name=None,
        stmt=None,
        **maybe_type_comment
    )

__all__ = ["argparse_function", "class_", "docstring", "file", "function"]


import pandas as pd
from readSto import readStoFile
import numpy as np
from interpDFrame import interpDFrame
import matplotlib.pyplot as plt

# Plot simulated muscle activation vs. EMG signal

# Right Foot Strike (RFS) times
RFS1 = 0.863
RFS2 = 1.546

# ------------------------------------------------------
# Import CMC states file
cmc_results_dir = '../CMC/run/results'
cmc = readStoFile(cmc_results_dir + '/cmc_states.sto')

# Load emg activity
emg = pd.read_csv('emg_run.txt', sep='\t')

min_time = np.amax([np.amin(cmc['time']),
                    np.amin(emg['time'])])

# recalc values as a function of the gait cycle percent
cmc_interp = interpDFrame(cmc, RFS1, RFS2, min_time)
emg_interp = interpDFrame(emg, RFS1, RFS2, min_time)

cmc_pct = cmc_interp['percentgaitcycle']
emg_pct = emg_interp['percentgaitcycle']

# ------------------------------------------------------
# Plot EMG (cyan) vs. CMC (blue) muscle activity
# magic to open plots in new window
#  %matplotlib
fig = plt.figure()
# ---------------------------------
# 1 GMAX
emgData = emg_interp['GMAX']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp[['glmax1_r/activation', 'glmax2_r/activation', 'glmax3_r/activation']].mean(axis=1)
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 1)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('gmax')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 2 GMED
emgData = emg_interp['GMED']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp[['glmed1_r/activation', 'glmed2_r/activation', 'glmed3_r/activation']].mean(axis=1)
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 2)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('gmed')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 3 RECFEM
emgData = emg_interp['RF']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['recfem_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 3)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('recfem')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 4 VASLAT
emgData = emg_interp['VL']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['vaslat_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 4)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('vaslat')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 5 BFLH
emgData = emg_interp['BFLH']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['bflh_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 5)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('bflh')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 6 GASLAT
emgData = emg_interp['GASLAT']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['gaslat_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 6)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('gaslat')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 7 TIBANT
emgData = emg_interp['TA']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['tibant_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 7)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('tibant')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

# ---------------------------------
# 8 SOLEUS
emgData = emg_interp['SOL']
emgPlot = emgData/emgData.max()
cmcData = cmc_interp['soleus_r/activation']
cmcPlot = cmcData/cmcData.max()
ax = plt.subplot(4, 2, 8)
ax.plot(emg_pct, emgPlot, 'c')
ax.plot(cmc_pct, cmcPlot, 'b')
t = ax.set_title('soleus')
l = ax.set_xlim(0, 100)
l = ax.set_ylim(0, 1)

plt.show()


from sys import argv, exit
import csv
import re

if len(argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit(1)

txt_file = open(argv[2], "r")
dna = txt_file.read()
txt_file.close()
name = None

with open(argv[1], mode = 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    line_count = 0
    STRs = []
    STR_count = []
    for row in reader:
        if line_count == 0:
            for k, v in row.items():
                if k == 'name':
                    pass
                else:
                    STRs.append(k)
                    pattern = k
                    pattern_count = 0
                    while re.search(pattern, dna):
                        pattern += k
                        pattern_count += 1
                    STR_count.append(pattern_count)
                    #print(pattern_count)

        line_count += 1
        num_seq = 0
        for i in range(len(STRs)):
            if STR_count[i] == int(row[STRs[i]]):
                num_seq += 1
        if num_seq == len(STRs):
            name = row["name"]

if name == None:
    print("No match")
else:
    print(name)


from sikuli import *
def trade(X, chest_flag):
    page1 = "page1.png"
    page2 = "page2.png"
    pages = [page1, page2]

    mat_box = "1579049773957.png"
    trade_icon1 = "trade_icon1.png"
    trade_icon2 = "trade_icon2.png"
    click("1578775575481.png")
    wait(0.25)
    click("1578775585587.png")
    wait(0.25)
    click(trade_icon1)
    game = "1578775307925.png"
    hover(game)
    wait(2)
    click(Location(158, 244)) # windows of mat_container
    while(len(X) != 0 ):
        goal = X[0]
        if goal == "1578239824046.png":
            mat_box = "sugar_img.png"
        try:
            results = findAll(mat_box)
        except:
            # Close all windows
            running = 1
            while ( running ):
                if exists("icon_-.png"):
                    click("icon_-.png")
                else:
                    running = 0
            # Open backpack
            print("Open Backpacks")
            wait(0.25)
            keyDown(Key.CTRL)
            keyDown("e")
            wait(1.0)
            keyUp(Key.CTRL)
            keyUp("e")
            # Open Chest
            doubleClick("chest_icon.png")
            wait(0.5)
            # Get mat_box from Chest
            flag = 0
            for p in pages:
                click(p)
                wait(2)
                if exists (mat_box):
                    candicates = findAll(mat_box)
                    for c in candicates:
                        hover(c)
                        wait(0.25)
                        if exists(goal, 0.5):
                            doubleClick(c)
                            print("x_sort:", X)
                            print("success", goal)
                            click("chest_ok.png")
                            flag = 1
                            break
                    if flag == 1:
                        break
                else:
                    continue
            hover(game)
            wait(2)
            click(Location(177, 105)) # windows of Producter
            click("1578775575481.png")
            wait(0.25)
            click("1578775585587.png")
            wait(0.25)
            click(trade_icon1)
            game = "1578775307925.png"
            hover(game)
            wait(2)
            click(Location(158, 244)) # windows of mat_container
            continue
        for j in results:
            hover(j)
            if exists(goal, 0.5):
                doubleClick(j)
                del X[0]
                wait(1)
                break
    wait(0.3)
    click(trade_icon1)
    wait(0.3)
    click(trade_icon2)
    hover(game)
    wait(2)
    click(Location(177, 105)) # windows of Producter
    wait(0.3)
    click(trade_icon2)
    hover("1578776614600.png")
    type("/re" + Key.ENTER)
    return()


# Assignment 1 - Managing Students!
#
# CSC148 Fall 2014, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
# STUDENT INFORMATION
#
# List your group members below, one per line, in format
# <George Peter Miltiades Burchell Gianacopoulos>, <gianacop>
# <Lewis Yu>, <yulewis>
#
#
# ---------------------------------------------
"""The back-end data model for the program.

School (class):
This is the container class which

Course (class):
This is the class used to keep track of student enrollment, it has methods for adding
and removing student names to and from its class list.

Student (class):
This is the student class, used to keep track of a student's name, and which courses
the student is enrolled in.
"""

class School:
    """Keeps track of and manages student and course data.

    Attributes:
     - students: A dictionary whose keys are student names and whose values are the corresponding student objects.
     - courses: A dictionary whose keys are course names and whose values are the corresponding course objects.
    """
    def __init__(self):

        self.students = {}
        self.courses = {}

    def create_student(self, name):
        """(School, str) -> NoneType
        Creates a new student object and adds it to the self.students dictionary.
        The key is the student's name, the value is the student object.
        Prints an error message if a student already exists with the given name.
        """
        if name not in self.students:
            student = Student(name)
            self.students[student.name] = student

        else:
            raise RegistrationError(1001)

    def delete_student(self, name):

        if name in self.students:
            del self.students[name]

    def create_course(self, name):
        """(School, str) -> NoneType
        Creates a new course object and adds it to the self.courses dictionary.
        The key is the course's name, the value is the course object.
        """
        course = Course(name)
        self.courses[course.name] = course

    def enrol(self, student_name, course_name):
        """(School, str, str) -> NoneType
        Adds the specified student's name to the specified course's class_list and the specified
        course's name to the student's courses list.
        Returns False if no student exists with the given name.
        Implicitly creates a course object if the specified course does not exist.
        """
        student_exists = student_name in self.students
        course_exists = course_name in self.courses

        if student_exists and course_exists:
            self.enrol_helper(student_name, course_name)

        elif student_exists and not course_exists:
            self.create_course(course_name)
            self.enrol_helper(student_name, course_name)

        elif not student_exists:
            raise RegistrationError(1000)

    def enrol_helper(self, student_name, course_name):
        """(str, str) -> NoneType
        Helper method for School.enrol()
        """

        student = self.students[student_name]
        course = self.courses[course_name]

        course.register(student)

    def get_all_enrolled(self, course_name):
        """(School, str) -> list of strings
        Takes the name of a course as an argument and returns the class list of the course with
        the given name.
        Raises an error if nobody is enrolled in the course named.
        """

        if course_name in self.courses and self.courses[course_name].class_list:
            return self.courses[course_name].class_list

        else:
            raise RegistrationError(1004)

    def get_course_list(self, student_name):

        if student_name in self.students:
            course_list = self.students[student_name].courses

            if course_list:
                return course_list

            else:
                raise RegistrationError(1003)

        else:
            raise RegistrationError(1000)

    def common_courses(self, student_1_name, student_2_name):
        """(School, str, str) -> list of strings
        Takes the names of two students and returns a list of the they are commonly enrolled in.
        Returns an empty list if the students named do not have any courses in common.
        Raises errors if one or both of the students named do not exist.
        """
        s1_exists = student_1_name in self.students
        s2_exists = student_2_name in self.students

        if s1_exists and s2_exists:
            s1_courses = self.students[student_1_name].courses
            s2_courses = set(self.students[student_2_name].courses)

            return [c for c in s1_courses if c in s2_courses]

        else:
            if not (s1_exists and s2_exists):
                raise RegistrationError(2003)

            elif not s1_exists:
                raise RegistrationError(2001)

            elif not s2_exists:
                raise RegistrationError(2002)

    def drop_course(self, student_name, course_name):
        """(School, str, str) -> NoneType
        Drops a student from a course.
        Raises an error if a student doesn't exist.
        """
        student_exists = student_name in self.students
        course_exists = course_name in self.courses

        if student_exists and course_exists:
            student = self.students[student_name]
            course = self.courses[course_name]
            course.drop(student)

        elif not student_exists:
            raise RegistrationError(1000)

class Course:

    def __init__(self, name):

        self.name = name
        self.class_list = []

    def register(self, student):
        """(Student) -> NoneType
        Adds student.name to class_list, sorts class_list alphabetically, and adds itself to the student's courses.
        Does nothing if the student is already registered.
        Raises an error of the course is full.
        """
        if student.name not in self.class_list and self.count_class() < 30:
            self.class_list.append(student.name)
            self.class_list.sort()
            student.add_course(self.name)

        elif self.count_class() >= 30:
            raise RegistrationError(1002)

    def drop(self, student):
        """(Student) -> NoneType
        Removes student.name from self.class_list.
        Does nothing if student.name is not on the class list.
        """
        if student.name in self.class_list:
            self.class_list.remove(student.name)
            student.drop_course(self.name)

    def count_class(self):
        return len(self.class_list)

class Student:

    def __init__(self, name):

        self.name = name
        self.courses = []

    def add_course(self, course_name):
        """(str) -> NoneType
        Adds course_name to self.courses then sorts self.courses alphabetically.
        """
        self.courses.append(course_name)
        self.courses.sort()

    def drop_course(self, course_name):
        """(str) -> NoneType
        Removes course_name from self.courses.
        """
        self.courses.remove(course_name)

class RegistrationError(Exception):
    """A custom error class for all errors involving the back-end data model.
    Specific error cases have messages and corresponding codes in the RegistrationError.codes dictionary.

    This class acts as the bridge between the front and back ends of the Student Management System for error handling.
    """

    codes = {
        1000: 'ERROR: Student %s does not exist.',
        1001: 'ERROR: Student %s already exists.',
        1002: 'ERROR: Course %s is full.',
        1003: '%s is not taking any courses.',
        1004: 'No one is taking %s.',
        2001: 'ERROR: %s does not exist.',  # School.common_courses error: 1st Student does not exist
        2002: 'ERROR: %s does not exist.',  # School.common_courses error: 2nd Student does not exist
        2003: 'ERROR: %s does not exist.',  # School.common_courses error: Both students do not exist
    }

    def __init__(self, code):
        self.code = code

    def print_err_msg(self, name):
        """(str, str) -> NoneType
        This method accesses the error message that corresponds to self.code in the RegistrationError.codes dictionary
        and prints the error message using name1 or name1 and name2 in place of the placeholder(s) in the error message.
        """

        msg = RegistrationError.codes[self.code]
        print(msg % name)


# -*- coding: utf-8 -*-
__metaclass__ = type

print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" % "9.5.2 静态方法和类成员方法")
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 手动包装和替换方法")
class MyClass():
    def smath():
        print('repeated static math')
    smath = staticmethod(smath)
    def cmath(cls):
        print('repeated class math', cls)
    cmath = classmethod(cmath)
MyClass.smath()
MyClass.cmath()

print("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 装饰器实现")
class MyClass2():

    @staticmethod
    def smath():
        print('repeated static math')

    @classmethod
    def cmath(cls):
        print('repeated class math', cls)

MyClass2.smath()
MyClass2.cmath()


'''Arsenal client PhysicalRacks class.'''
import logging
from arsenalclient.interface.arsenal_interface import ArsenalInterface
from arsenalclient.exceptions import NoResultFound

LOG = logging.getLogger(__name__)

class PhysicalRacks(ArsenalInterface):
    '''The arsenal client PhysicalRacks class.'''

    def __init__(self, **kwargs):
        super(PhysicalRacks, self).__init__(**kwargs)
        self.uri = '/api/physical_racks'

    # Overridden methods
    def search(self, params=None):
        '''Search for physical_racks.

        Usage:

        >>> params = {
        ...   'name': 'R500',
        ...   'exact_get': True,
        ... }
        >>> PhysicalRacks.search(params)

        Args:

            params (dict): a dictionary of url parameters for the request.

        Returns:
            A json response from ArsenalInterface.check_response_codes().
        '''

        return super(PhysicalRacks, self).search(params)

    def create(self, params):
        '''Create a new physical_rack.

        Args:

        params (dict): A dictionary with the following attributes:

        name : The name of the physical_rack you wish to create.
        physical_location : The name of the physical_location the
            physical_rack you wish to create will be in.

        Usage:

        >>> params = {
        ...     'name': 'R500',
        ...     'physical_location': 'TEST DC SCIF 1',
        ... }
        >>> PhysicalRacks.create(params)
        <Response [200]>
        '''

        return super(PhysicalRacks, self).create(params)

    def update(self, params):
        '''Update a physical_rack.

        Args:
            params (dict): A dictionary of url parameters for the request.

        Usage:
            Only the params in the example are updatable from this action.

        >>> params = {
        ...     'name': 'R500',
        ...     'physical_location': 'TEST DC SCIF 2',
        ... }
        >>> PhysicalRacks.update(params)

        Returns:
            A json response from ArsenalInterface.check_response_codes().
        '''

        return super(PhysicalRacks, self).update(params)

    def delete(self, params):
        '''Delete a physical_rack object from the server.

        Args:

            params: A physical_rack dictionary to delete. Must contain the
                physical_rack id, and name.

        Usage:

        >>> params = {
        ...     'id': 1,
        ...     'name': 'R500',
        ... }
        >>> PhysicalRacks.delete(params)
        '''

        return super(PhysicalRacks, self).delete(params)

    def get_audit_history(self, results):
        '''Get the audit history for physical_racks.'''
        return super(PhysicalRacks, self).get_audit_history(results)

    def get_by_name(self, name):
        '''Get a single physical_rack by it's name. This is not possible as
        physical_racks are not unique by name alone. Use PhysicalRacks.get_by_name_location()
        instead.
        '''
        pass

    # Custom methods
    def get_by_name_location(self, name, location):
        '''Get a single physical_rack by it's name and location.'''

        LOG.debug('Searching for physical_rack by name: {0} location: {1}'.format(name,
                                                                                location))
        data = {
            'name': name,
            'physical_location.name': location,
        }

        resp = self.api_conn('/api/physical_racks', data, log_success=False)
        LOG.debug('Results are: {0}'.format(resp))

        try:
            resource = resp['results'][0]
        except IndexError:
            msg = 'Physical Rack not found, name: {0} location: {1}'.format(name,
                                                                            location)
            LOG.info(msg)
            raise NoResultFound(msg)
        if len(resp['results']) > 1:
            msg = 'More than one result found, name: {0} location: {1}'.format(name,
                                                                               location)
            LOG.error(msg)
            raise RuntimeError(msg)

        return resource


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

def createDataSet(dataset, fileName):
    f = open(fileName, 'r')
    dataset = []
    specialset = []
    line = f.readline()
    # 用 while 逐行讀取檔案內容，直至檔案結尾
    while line:
        if line.find('?') == -1:
            attribute = line[:len(line)-1].split(",")
            # 10 attribute
            data = [int(attribute[1]), int(attribute[2]), int(attribute[3]), int(attribute[4]), int(attribute[5]),
                    int(attribute[6]), int(attribute[7]), int(attribute[8]), int(attribute[9]), int(attribute[10])]
            dataset.append(data)
        else:
            attribute = line[:len(line)-1].split(",")
            # 10 attribute
            for i in range(10):
                if attribute[i+1] == "?":
                    attribute[i+1] = -1
            data = [int(attribute[1]), int(attribute[2]), int(attribute[3]), int(attribute[4]), int(attribute[5]),
                    int(attribute[6]), int(attribute[7]), int(attribute[8]), int(attribute[9]), int(attribute[10])]
            specialset.append(data)
        line = f.readline()
    f.close()
    return dataset, specialset

def Handle_question_mark(s, attribute):
    s[:, 5] = attribute.mean()
    return s

def chose_seventity(dataset):
    # 489筆訓練資料 210筆test資料
    testNumber = len(dataset)-int(len(dataset)*0.7)
    trainset = dataset.copy()
    testset = []
    for i in range(testNumber):
        tem = random.randint(0, len(trainset)-1)
        testset.append(trainset[tem])  # 選出來其中一筆
        del trainset[tem]

    return trainset, testset

# 算出所有可能的機率

def count_probability(dataset):
    p2 = 0
    p4 = 0
    attribute11 = dataset[:, 9]
    for i in range(len(dataset)):
        if attribute11[i] == 2:
            p2 = p2+1
        else:
            p4 = p4+1

    p_attribute = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    pa2ofconditional2 = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    pa2ofconditional4 = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(9):
        p_attribute[i] = count_attributes(dataset, i)
        pa2ofconditional2[i], pa2ofconditional4[i] = count_attributes2or4(
            dataset, i, p2, p4)

    p2 = p2/len(dataset)
    p4 = p4/len(dataset)
    return p2, p4, p_attribute, pa2ofconditional2, pa2ofconditional4

def count_attributes(dataset, i):
    attribute = dataset[:, i]
    p_attribute = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for k in range(len(dataset)):
        p_attribute[attribute[k] -
                    1] = p_attribute[attribute[k]-1]+1/len(dataset)
    return p_attribute

def count_attributes2or4(dataset, i, p2, p4):
    attribute = dataset[:, i]
    tem = dataset[:, 9]
    p_attribute112 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    p_attribute114 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for k in range(len(dataset)):
        if tem[k] == 2:
            p_attribute112[attribute[k] -
                           1] = p_attribute112[attribute[k]-1]+1
        if tem[k] == 4:
            p_attribute114[attribute[k] -
                           1] = p_attribute114[attribute[k]-1]+1

    for j in range(10):
        total = p_attribute112[j]+p_attribute114[j]
        if total != 0:
            p_attribute112[j] = p_attribute112[j]/total
            p_attribute114[j] = p_attribute114[j]/total
    return p_attribute112, p_attribute114

if __name__ == '__main__':
    start = datetime.datetime.now()
    dataset = []
    specialset = []

    # 處理問號完後 重新加入資料集
    dataset, specialset = createDataSet(
        dataset, "breast-cancer-wisconsin.data")
    dataset = np.array(dataset)
    specialset = np.array(specialset)
    Handle_question_mark(specialset, dataset[:, 5])
    dataset = np.vstack((dataset, specialset))

    dataset = dataset.tolist()
    accacylist = []

    for h in range(10):
        trainset, testset = chose_seventity(dataset)
        trainset = np.array(trainset)
        testset = np.array(testset)
        p2, p4, p_attribute, pa2ofconditional2, pa2ofconditional4 = count_probability(
            trainset)
        accacy = 0

        for i in testset:
            final2 = 1
            final4 = 1
            for attribute in range(9):
                if pa2ofconditional2[attribute][i[attribute]-1] != 0:
                    final2 *= pa2ofconditional2[attribute][i[attribute]-1]
                else:
                    final2 *= 1
                if pa2ofconditional4[attribute][i[attribute]-1] != 0:
                    final4 *= pa2ofconditional4[attribute][i[attribute]-1]
                else:
                    final4 *= 1
            if final2 >= final4:
                decide = 2
            else:
                decide = 4
            if decide == i[9]:
                accacy = accacy+1
        accacylist.append(accacy/len(testset))
        print(accacy/len(testset))
    end = datetime.datetime.now()
    print(end - start)

    plt.xlabel('times')
    plt.ylabel("accurcy")
    plt.plot(range(1, 11), accacylist)
    plt.show()


"""
Test suite for monitor
"""
from unittest import TestCase

import asyncio
import json
import random
import websockets

from qcodes.monitor import monitor
from qcodes.instrument.base import Parameter
from qcodes.tests.instrument_mocks import DummyInstrument

monitor.WEBSOCKET_PORT = random.randint(50000, 60000)

class TestMonitor(TestCase):
    """
    Test cases for the qcodes monitor
    """
    def test_setup_teardown(self):
        """
        Check that monitor starts up and closes correctly
        """
        m = monitor.Monitor()
        self.assertTrue(m.is_alive())
        self.assertTrue(m.loop.is_running())
        self.assertEqual(monitor.Monitor.running, m)
        m.stop()
        self.assertFalse(m.loop.is_running())
        self.assertTrue(m.loop.is_closed())
        self.assertFalse(m.is_alive())
        self.assertIsNone(monitor.Monitor.running)

    def test_monitor_replace(self):
        """
        Check that monitors get correctly replaced
        """
        m = monitor.Monitor()
        self.assertEqual(monitor.Monitor.running, m)
        m2 = monitor.Monitor()
        self.assertEqual(monitor.Monitor.running, m2)
        self.assertTrue(m.loop.is_closed())
        self.assertFalse(m.is_alive())
        self.assertTrue(m2.is_alive())
        m2.stop()

    def test_double_join(self):
        """
        Check that a double join doesn't cause a hang
        """
        m = monitor.Monitor()
        self.assertEqual(monitor.Monitor.running, m)
        m.stop()
        m.stop()

    def test_connection(self):
        """
        Test that we can connect to a monitor instance
        """
        m = monitor.Monitor()

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        @asyncio.coroutine
        def async_test_connection():
            websocket = yield from websockets.connect(f"ws://localhost:{monitor.WEBSOCKET_PORT}")
            yield from websocket.close()
        loop.run_until_complete(async_test_connection())

        m.stop()

class TestMonitorWithInstr(TestCase):
    """
    Test monitor values from instruments
    """
    def setUp(self):
        """
        Create a dummy instrument for use in monitor tests, and hook it into
        a monitor
        """
        self.instr = DummyInstrument("MonitorDummy")
        self.param = Parameter("DummyParam",
                               unit="V",
                               get_cmd=None,
                               set_cmd=None)
        self.param(1)
        self.monitor_parameters = tuple(self.instr.parameters.values())[1:]
        self.monitor = monitor.Monitor(*self.monitor_parameters, self.param, interval=0.1)

    def tearDown(self):
        """
        Close the dummy instrument
        """
        self.monitor.stop()
        self.instr.close()

    def test_parameter(self):
        """
        Test instrument updates
        """
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        @asyncio.coroutine
        def async_test_monitor():
            websocket = yield from websockets.connect(f"ws://localhost:{monitor.WEBSOCKET_PORT}")

            # Recieve data from monitor
            data = yield from websocket.recv()
            data = json.loads(data)
            # Check fields
            self.assertIn("ts", data)
            self.assertIn("parameters", data)
            # Check one instrument and "No Instrument" is being sent
            self.assertEqual(len(data["parameters"]), 2)
            self.assertEqual(data["parameters"][1]["instrument"], "Unbound Parameter")
            metadata = data["parameters"][0]
            self.assertEqual(metadata["instrument"], str(self.instr))

            # Check parameter values
            old_timestamps = {}
            for local, mon in zip(self.monitor_parameters, metadata["parameters"]):
                self.assertEqual(str(local.get_latest()), mon["value"])
                self.assertEqual(local.label, mon["name"])
                old_timestamps[local.label] = float(mon["ts"])
                local(random.random())

            # Check parameter updates
            data = yield from websocket.recv()
            data = yield from websocket.recv()
            data = json.loads(data)
            metadata = data["parameters"][0]
            for local, mon in zip(self.monitor_parameters, metadata["parameters"]):
                self.assertEqual(str(local.get_latest()), mon["value"])
                self.assertEqual(local.label, mon["name"])
                self.assertGreater(float(mon["ts"]), old_timestamps[local.label])

            # Check unbound parameter
            metadata = data["parameters"][1]["parameters"]
            self.assertEqual(len(metadata), 1)
            self.assertEqual(self.param.label, metadata[0]["name"])

        loop.run_until_complete(async_test_monitor())


from ftw.upgrade import UpgradeStep
from opengever.base.behaviors.base import IOpenGeverBase
from opengever.base.behaviors.translated_title import ITranslatedTitle
from plone import api

class ActivateTranslatedTitle(UpgradeStep):
    """Add ITranslatedTitle behavior to Templatedossier and migrate titles to
    title_de. It removes the IOpenGeverBase behavior as well.
    """

    def __call__(self):
        self.setup_install_profile('profile-opengever.dossier.upgrades:4600')

        query = {'portal_type': 'opengever.dossier.templatedossier'}
        msg = 'Migrate title of templatedossiers'
        for templatedossier in self.objects(query, msg):
            self.migrate_titles(templatedossier)

        self.remove_base_behavior()

    def migrate_titles(self, obj):
        ITranslatedTitle(obj).title_de = IOpenGeverBase(obj).title
        obj.reindexObject()

    def remove_base_behavior(self):
        fti = api.portal.get_tool('portal_types').get(
            'opengever.dossier.templatedossier')
        fti.behaviors = filter(
            lambda b: b != IOpenGeverBase.__identifier__, fti.behaviors)


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

os.makedirs("./graficas")
x=np.linspace(0,100,1000)
datos= np.loadtxt("datos.dat")
print(len(x))
print(len(datos[0,:]))
for i in range(len(datos[:,0])):
    plt.figure(figsize=(10,10))
    plt.plot(x,datos[i,:])
    plt.xlim((0,100))
    plt.ylim((-2,2))
    plt.savefig("./graficas/"+str(i)+".jpg")
    plt.close()

os.system("sudo apt-get install imagemagick")
os.chdir("./graficas")
os.system("convert -delay 20 -loop 0 *.jpg cuerda.gif")
os.system("mv cuerda.gif ..")
os.chdir("..")
os.system("rm -rf graficas")


import unittest
from unittest import mock
from unittest.mock import patch

from ddt import data, ddt, unpack
from indi import message
from indi.routing import Device, Router

@ddt
class TestRouter(unittest.TestCase):
    messages = [
        ("SOME_DEVICE", ((True, True), (False, False))),
        (None, ((None, True), (None, True))),
    ]

    @data(*messages)
    @unpack
    def test_message_from_client(self, message_device, device_specs):
        devices = [
            {"mock": mock.Mock(), "accepts": ds[0], "processes": ds[1],}
            for ds in device_specs
        ]

        msg = message.GetProperties(version="2.0", device=message_device)
        router = Router()

        for device in devices:
            device["mock"].accepts.return_value = device["accepts"]
            router.register_device(device["mock"])

        router.process_message(message=msg)

        for device in devices:
            if device["accepts"] is not None:
                device["mock"].accepts.assert_called_once_with(msg.device)
            if device["processes"]:
                device["mock"].message_from_client.assert_called_once_with(msg)

    class fake_threading:
        class Thread:
            def __init__(self, target, *args, **kwargs):
                self.target = target

            def start(self):
                self.target()

    @patch("indi.routing.router.threading", new_callable=fake_threading)
    def test_message_from_device(self, mocked_threading):
        router = Router()

        client = mock.Mock()

        router.register_client(client)

        msg = message.DelProperty(device="SOME_DEVICE")

        router.process_message(msg)

        client.message_from_device.assert_called_once_with(msg)


def gc_con(seq):
    """Count G's and C's"""
    gc = 0
    gc=(seq.count('G')+seq.count('C'))/len(seq)
    return gc

def readfna(file):
    """Reads a fasta file and outputs the sequence string only without gaps"""
    seq = ''
    seq_list = ''
    with open(file,'r') as f:
        seq_list = f.readlines()
        i=1
        while i < len(seq_list):
            seq += seq_list[i].rstrip()
            i+=1
    return seq

def gc_blocks(seq, block_size):
    seq_gc = []
    seq_list = []
    for i in range(len(seq)//block_size):
        seq_gc.append(gc_con(seq[i*block_size:(i+1)*block_size]))
        seq_list.append(seq[i*block_size:(i+1)*block_size])
    return (seq_gc, seq_list)

def gc_map(seq, block_size, threshold):
    seq_gc = []
    seq_list = []
    seqfinal = ''
    for i in range(len(seq)//block_size):
        seq_gc.append(gc_con(seq[i*block_size:(i+1)*block_size]))
        seq_list.append(seq[i*block_size:(i+1)*block_size])

    for l in range(len(seq_list)):
        seqlist[l]=seq_list[l].upper()

    for j in range(len(seq_list)):
        if seq_gc[j] < threshold:
            seq_list[j]=seq_list[j].lower()

    k=0
    while k < len(seq_list):
        seqfinal += seq_list[k]
        k += 1

    return seqfinal


import sqlite3,time
import subprocess as sp

"""
Codigo fuente de la BD para interactuar con ella
"""

def create_table():
    # Conexion a sqlite3
    conn = getConexion()

    # Asigno cursor de la conexion a una variable local
    cursor = conn.cursor()

    # Defino la consulta de SQL para crear la tabla estudiantes
    query = '''
        CREATE TABLE IF NOT EXISTS student(
        id INTEGER PRIMARY KEY,
        roll INTEGER,
        name TEXT,
        phone TEXT
        );'''

    cursor.execute(query)
    #cursor.execute("-SQL QUERYS")

    # Consignar ala BD las instrucciones que se acaban de ejecutar
    conn.commit()

    # Cerrar conexion
    conn.close()

def add_student(id_,roll, name, phone):
    # Abrir la conexion
    conn = getConexion()
    # Asigna cursor de la bd a una variable local
    cursor = conn.cursor()

    # Query a ejecutar

    query = '''
        INSERT INTO student(id,roll,name,phone)
        VALUES(?,?,?,?)
        '''

    # Ejecuto la conexion en el cursor devuelto por la BD
    cursor.execute(query,(id_,roll,name,phone))

    # Consignar a la Bd la instruccion SQL ejecutada.
    conn.commit()

    # Cerrar conexion
    conn.close()

def get_students():
    # Abrir conexion a BD
    conn = getConexion()

    # Asigno el cursor
    cursor = conn.cursor()

    # Query para ejecutar
    query = '''
        SELECT id,roll, name, phone FROM student
        '''
    # Ejecutar el query
    cursor.execute(query)

    # Obtener el resultado del cursor de los registros y los
    # asigno a una variable
    all_rows = cursor.fetchall()

    # Consigno la consulta a la conexion a la BD
    conn.commit()

    # Cerrar la conexion
    conn.close()

    # Regreso el conjunto de datos devueltos por la consulta
    return all_rows

def get_student_by_id(id_):
    # Traer la conexion desde el metodo GetConexion
    conn = getConexion()

    # Asignar el cursor a una variable local
    cursor = conn.cursor()

    # Query a ejecutar
    query = '''
        SELECT id,roll, name,phone FROM student
        WHERE id = {}
        '''.format(id_)

    # Ejecutar el QUERY
    cursor.execute(query)

    # Obtener el resultado del cursor de los registros y los
    # asigno a una variable
    all_rows = cursor.fetchall()

    # Consigno la consulta a la conexion a la BD
    conn.commit()

    # Cerrar la conexion
    conn.close()

    # Regreso el conjunto de datos devueltos por la consulta
    return all_rows

def update_student(roll, name, phone):
    # Traer la conexion desde el metodo GetConexion
    conn = getConexion()

    # Asignar el cursor a una variable local
    cursor = conn.cursor()

    # Query a ejecutar
    query = '''
        UPDATE student SET name = ?, phone = ? WHERE roll = ?
        '''

    # Ejecutar el QUERY
    cursor.execute(query, (name, phone, roll))

    # Obtener el resultado del cursor de los registros y los
    # asigno a una variable
    #all_rows = cursor.fetchall()

    # Consigno la consulta a la conexion a la BD
    conn.commit()

    # Cerrar la conexion
    conn.close()

    # Regreso el conjunto de datos devueltos por la consulta
    # return all_rows

def delete_student(id__):
    # Traer la conexion desde el metodo GetConexion
    conn = getConexion()

    # Asignar el cursor a una variable local
    cursor = conn.cursor()

    # Query a ejecutar
    query = '''
        DELETE FROM student WHERE id = {}
        '''.format(id__)

    # Ejecutar el QUERY
    cursor.execute(query)

    # Obtener el resultado del cursor de los registros y los
    # asigno a una variable
    #all_rows = cursor.fetchall()

    # Consigno la consulta a la conexion a la BD
    conn.commit()

    # Cerrar la conexion
    conn.close()

    # Regreso el conjunto de datos devueltos por la consulta
    # return all_rows

def getConexion():
    conn = sqlite3.connect("testdb2.sqlite")
    return conn

def add_data(id_,roll, name, phone):
    add_student(id_,roll, name, phone)

def get_data():
    return get_students()

def show_data():
    students = get_data()
    for students in students:
        print(students)

def show_data_by_id(id_):
    students = get_student_by_id(id_)
    if not students:
        print("No hay registros para el id %r" % id_)
        time.sleep(2)
    else:
        print(students)
        time.sleep(2)

def select():
    create_table()
    sp.call('cls', shell=True)
    sel = input("1. Add\n2. Show\n3. Search\n4. Update\n5. Delete\n6. Exit\n>: ")

    if sel == '1':
        sp.call('cls', shell=True)
        id__ = int(input("Id: "))
        roll = input("Roll: ")
        name = input("Name: ")
        phone = input("Phone: ")
        add_data(id__, roll, name, phone)

        #input("\n\nPress enter to back: ")

    elif sel == '2':
        sp.call('cls', shell=True)
        show_data()
        input("\n\nPress enter to back: ")

    elif sel == '3':
        sp.call('cls', shell=True)
        id_ = int(input("Enter ID: "))
        show_data_by_id(id_)

        print("\n\nPress enter to back: ")

    elif sel == '4':
        sp.call('cls', shell=True)
        id__ = int(input("Enter ID: "))
        show_data_by_id(id__)

        print("\n")

        name = input("Name: ")
        phone = input("Phone: ")
        update_student(id__, name, phone)

        input("\n\nYour data has been updated\nPress enter to back: ")

    elif sel == '5':
        sp.call('cls', shell=True)
        id__ = int(input("Enter ID: "))
        show_data_by_id(id__)
        delete_student(id__)

        print("\n")
        input("\n\nYour data has been deleted\nPress enter to back: ")
    else:
        return 0
    return 1

while select():
    pass


# Evaluate if a binary tree is a binary search tree Problem from Ryan Hopkins #

# Given the root node of a binary three, check if the binary tree is a binary
# search tree.

### SOLUTION ###
# The solution below uses in-order traversal to loop through all the nodes in the tree (as
# if looping through an ordered list) and makes sure the previous node is not greater than
# the current. If it is, then return false because that makes the tree not a binary search
# tree.
def is_bst(root, prev_node=None):
    if root is None:
        return True
    left = is_bst(root.left, prev_node)
    if prev_node is not None:
        if prev_node.value > root.value:
            return False
    prev_node = root
    right = is_bst(root.right, prev_node)
    return left and right

### TESTING ###
class Node():
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

root = Node(10)
node8 = Node(8)
node12 = Node(12)
root.left = node8
root.right = node12

# Left side of tree
node11 = Node(11)
node13 = Node(13)
node12.left = node11
node12.right = node13

# Right side of tree
node7 = Node(7)
node9 = Node(9)
node8.left = node7
node8.right = node9

if __name__ == '__main__':
    print(is_bst(root)) # True


DESPL = 3
BASE = 65
FIN = 122 + 1

def encriptacion(texto):
	despl = DESPL
	nuevoTexto = ""
	for letra in texto:
		nuevoTexto += chr((ord(letra) + despl) % FIN)

	return nuevoTexto

def desencriptacion(texto):
	despl = DESPL
	nuevoTexto = ""
	for letra in texto:
		nuevoTexto += chr((ord(letra) - DESPL) % FIN)

	return nuevoTexto

if __name__ == '__main__':
	cadena = input("Ingresa una cadena: ")

	cadenaEnc = encriptacion(cadena)
	print("Encriptada: " + cadenaEnc)

	cadenaDes = desencriptacion(cadenaEnc)
	print("Desencriptada: " + cadenaDes)


import os,sys
import numpy as np
import os.path
import matplotlib.pyplot as plt
import re
def run(command):
	p1 = os.popen(command)
	temp = p1.readlines()
	p1.close()
	return temp
#f1 = open("ourMethod.txt","w+")
#f2 = open("mpest.txt","w+")

if __name__=="__main__":
    lines1 = run("cat 1")
    lines2 = run("cat 2")
    score = 0
    for line1 in lines1:
        for line2 in lines2:
            cnt1 = len(line1)
            cnt2 = len(line2)
            t1 = line1[:cnt1-2].rstrip()
            t2 = line2[:cnt2-2].rstrip()
            if t1 == t2:
                res1 = line1[ cnt1-2 : cnt1-1]
                res2 = line2[ cnt2-2 : cnt2-1]
    #            print(res1, res2)
                #print(res)
                score += int(res1) * int(res2)
                #print(t1,t2)
                #print(line.rstrip()[:13])
    print(score)


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

import json
import pandas as pd
from pprint import pprint

with open('../../Datasets/Original/att_data.json', 'r') as fp:
    obj = json.load(fp)

# obj['attendanceData'][3]

# removes keys from dataset - attempt to save space when saving file
rm_list = ['DiffGrp','captureMethod','StudentStatus','room','updatedBy','source','logintime','UpdatedDateTime','acYear']
for idx, x in enumerate(obj['attendanceData']):
    del x[rm_list[0]],x[rm_list[1]],x[rm_list[2]],x[rm_list[3]],x[rm_list[4]],x[rm_list[5]],x[rm_list[6]],x[rm_list[7]],x[rm_list[8]]

# obj['attendanceData'][0]
# obj

with open('att_data_condensed.json', 'w') as outfile:
    json.dump(obj['attendanceData'], outfile)


import unittest

from mdbg_entry import MdbgEntry

class MdbgEntryTestCase(unittest.TestCase):
    """Unit test for MdbgEntry class.
    """
    def setUp(self):
        self.MDBG_PATH = '/home/casey/zhongwen/cedict_1_0_ts_utf-8_mdbg.txt'
        with open(self.MDBG_PATH, 'r') as reader:
            self.raw = reader.readlines()
        self.mdbg = []
        for num, entry in enumerate(self.raw[1500:1600]):
            mdbg_entry = MdbgEntry(entry)
            entry = mdbg_entry.entry.update({'index' : num})
            self.mdbg.append(mdbg_entry)

    def test_tone_is_numerical(self):
        for entry in self.mdbg[1500:1600]:
            self.assertIsInstance(entry.pinyin['tone'], int)

#    def test_num_chars_pinyin(self):
#        for entry in self.mdbg:

if __name__ == '__main__':
    unittest.main()


# Iterable : for-in 구문에서 사용할 수 있는 타입들
#  -> list, tuple, set, dict, numpy.ndarray, pandas.dataframe,...
#   for x in Iterable: ...

a = [1,3,0,9,-1]
result = sorted(a, key=lambda x: -abs(x))
print(f'a={a}, result={result}')
a.sort(key=lambda x: -abs(x))
print(f'a={a}, result={result}')

b = ['cat', 'bb', 'dogs', 'apple']
result = sorted(b, key=lambda x: len(x))
print(f'b={b}, result={result}')

c = {'cat':1, 'bb':-1, 'dogs':3, 'apple':5}
result = sorted(c, key=lambda x : len(x))
print(f'c={c}, result={result}')

result = sorted(c.values(), key=lambda x : abs(x))
print(f'c={c}, result={result}')

key, val = sorted(c.items(), key=lambda x:x[1], reverse=True)[0]
print(f'c={c}, key={key}, val={val}')

max = max(c.items(), key=lambda x:x[1])
print(max)
print('========================================================================')

class person:
    def __init__(self, name:str, age:int):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'Person(이름: {self.name}, 나이: {self.age})'

p1 = person('이지수', 10)
p2 = person('심진섭', 20)
p3 = person('조성우', 30)

persons = [p1,p2,p3]
result = sorted(persons, key=lambda x:x.name)
print(f'persons:{persons}, \nresult:{result}')

result = sorted(persons, key=lambda x:x.age)
print(f'persons:{persons}, \nresult:{result}')

# field, property, member variable --> 다 동일한 의미   :  class가 가지고 있는 변수들


from .py_sirius import Hamiltonian, Wave_functions
from .coefficient_array import PwCoeffs
import numpy as np

class S_operator:
    """
    Description: compute S|Psi>
    """
    def __init__(self, hamiltonian, kpointset):
        """

        """
        self.hamiltonian = hamiltonian
        self.kpointset = kpointset

    def apply(self, cn):
        """
        """
        ctx = self.hamiltonian.ctx()
        num_sc = ctx.num_spins()
        self.hamiltonian._apply_ref_inner_prepare()
        assert isinstance(cn, PwCoeffs)
        out = PwCoeffs(dtype=cn.dtype)
        for k, ispn_coeffs in cn.by_k().items():
            kpoint = self.kpointset[k]
            # spins might have different number of bands ...
            num_wf = max(ispn_coeffs, key=lambda x: x[1].shape[1])[1].shape[1]
            Psi_x = Wave_functions(kpoint.gkvec_partition(), num_wf,
                                   ctx.preferred_memory_t(), num_sc)
            Psi_y = Wave_functions(kpoint.gkvec_partition(), num_wf,
                                   ctx.preferred_memory_t(), num_sc)
            for i, val in ispn_coeffs:
                Psi_x.pw_coeffs(i)[:, :val.shape[1]] = val
            self.hamiltonian._apply_overlap_inner(self.kpointset[k], Psi_y, Psi_x)
            for i, _ in ispn_coeffs:
                out[(k, i)] = np.array(
                    Psi_y.pw_coeffs(i), copy=False)[:, :num_wf]
        self.hamiltonian._apply_ref_inner_dismiss()
        return out

    def __matmul__(self, cn):
        return self.apply(cn)


# -*- coding: utf-8 -*-
"""
Created on Sun May 31 09:51:28 2020

@author: prani
"""

def maxcontsum(nums):
    sum_now = nums[0]
    sum_max = nums[0]
    start = 0
    end = 0
    count = 0
    for i in range(1, len(nums)):
        if sum_now < nums[i]:
            count += 1
            sum_now = max(nums[i], sum_now+nums[i] )
        sum_max = max(sum_now, sum_max)

        if sum_max > sum_now:
            start = count
            end = i

    print(start)
    print(end)
    return sum_max

l1 = [-13, -3, -25, -20, -2, -16, -23, -12, -5, -22, -15, -4, -7]
print(maxcontsum(l1))


"""empty message

Revision ID: 2cc88a062410
Revises: cc1b09b3b777
Create Date: 2018-08-10 01:16:05.877485

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '2cc88a062410'
down_revision = 'cc1b09b3b777'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('cab', sa.Column('rating', sa.DECIMAL(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('cab', 'rating')
    # ### end Alembic commands ###