from typing import List
import time
real = 'day11.txt'
test = 'day11test.txt'

# ['L.LL.LL.LL',
#  'LLLLLLL.LL',
#  'L.L.L..L..',
#  'LLLL.LL.LL',
#  'L.LL.LL.LL',
#  'L.LLLLL.LL',
#  '..L.L.....',
#  'LLLLLLLLLL',
#  'L.LLLLLL.L',
#  'L.LLLLL.LL']

# direction dictionary with {Direction: (y-shift, x-shift)}
dir_dict = {'N': (0, -1), 'NE': (1, -1), 'E': (1, 0), 'SE': (1, 1),
            'S': (0, 1), 'SW': (-1, 1), 'W': (-1, 0), 'NW': (-1, -1)}

with open(real) as file:
    given_data = [x.rstrip() for x in file.readlines()]
max_x = len(given_data[0])
max_y = len(given_data)
print(max_x, max_y)

def check_around(data, x, y) -> int:
    num_occupied = 0
    for direc in dir_dict:
        dx = x + dir_dict[direc][0]
        dy = y + dir_dict[direc][1]
        # print(direc, dx, dy)
        try:
            if dx >= 0 and dy >= 0 and data[dy][dx] == '#':
                num_occupied += 1
        except IndexError:
            pass
    return num_occupied

def check_cardinal(data, x, y) -> int:
    num_occupied = 0
    for direc in dir_dict:
        dx, dy = dir_dict[direc][0], dir_dict[direc][1]
        cur_x, cur_y = x + dx, y + dy
        keep_going = True
        while (0 <= cur_x < max_x) and (0 <= cur_y < max_y) and keep_going:
            try:
                cur_seat = data[cur_y][cur_x]
                if cur_seat == '#':
                    num_occupied += 1
                    keep_going = False
                elif cur_seat == 'L':
                    keep_going = False
            except IndexError:
                keep_going = False
            cur_x, cur_y = cur_x + dx, cur_y + dy
    return num_occupied

def transform(check_type, data: List[str], max_occupied: int) -> List[str]:
    new_data = []
    for y in range(max_y):
        line = data[y]
        new_line = ''
        for x in range(max_x):
            if line[x] == '.':
                new_line += '.'
            elif line[x] == 'L':
                if check_type(data, x, y) == 0:
                    new_line += '#'
                else:
                    new_line += 'L'
            elif line[x] == '#':
                if check_type(data, x, y) >= max_occupied:
                    new_line += 'L'
                else:
                    new_line += '#'
        new_data.append(new_line)
    return new_data

def get_stationary_matrix(part: str, data: List[str], max_occupied: int) -> List[str]:
    keep_going = True
    if part == 'a':
        check_type = check_around
    elif part == 'b':
        check_type = check_cardinal
    while keep_going:
        new_data = transform(check_type, data, max_occupied)
        # print('\n')
        if new_data == data:
            return new_data
        else:
            data = new_data

def solve():
    start = time.time()
    count_a = 0
    count_b = 0
    joined_data_a = ''.join(get_stationary_matrix('a', given_data, 4))
    for i in range(len(joined_data_a)):
        if joined_data_a[i] == '#':
            count_a += 1
    joined_data_b = ''.join(get_stationary_matrix('b', given_data, 5))
    for i in range(len(joined_data_b)):
        if joined_data_b[i] == '#':
            count_b += 1
    print('(a): {} occupied seats\n(b): {} occupied seats\nSolved in {} seconds'.format(count_a, count_b, time.time() - start))
    return count_a, count_b, time.time() - start

solve()


#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:brick
# datetime:2019/12/9 12:26
from __future__ import print_function

from collections import Counter

from keras.utils import to_categorical
import pickle
from six.moves import range

import keras.backend as K
from keras.initializers import Constant
from keras.layers import Input, Dense, Reshape, Flatten, Embedding, merge, Dropout, LSTM, Bidirectional, concatenate,Multiply, Dot, multiply
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras.utils.generic_utils import Progbar
from keras.layers.core import Lambda
import numpy as np
from keras.preprocessing import sequence
from keras import layers
from keras.models import Sequential, load_model, save_model
import data
from data import cal_F1_measure,cal_macro_micro_F1, scoreF
from keras.optimizers import SGD
from keras.utils import plot_model

np.random.seed(2019)

class GAN:
    def __init__(self):
        self.epochs = 1
        self.batch = 100
        self.num_words = 4396
        self.maxlen = [22, 27, 26]  # sip, rs, cue 路径最大长度
        self.lr = 0.01
        self.dropout = 0.5
        self.train_set = []
        self.valid_set = []
        self.test_set = []
        self.embdding = None
        self.index = 9
        self.lenth = 20
        self.generator =None
        self.discriminator = None
        self.combine = None
        self.disfile = None
        self.genfile = None
        self.comfile = None

    def load_data(self, index):
        self.maxlen = data.produce('sample.pkl', 'mydata.pkl', index)
        self.train_set, self.valid_set,self.test_set = data.load('mydata.pkl')
        self.embdding = np.array(data.load('word_emb.pkl'))
        return

    def load_test_data(self, filename):
        self.test_set = data.read_file(filename)
        self.embdding = np.array(data.load('word_emb.pkl'))
        return

    def lstm_layer(self, x, maxlen):
        lstm = Sequential()
        lstm.add(Embedding(self.num_words, 100, input_length=maxlen))
        lstm.add(Dropout(self.dropout))
        lstm.add(Dense(maxlen))
        lstm.add(LSTM(100, return_sequences=True, dropout=self.dropout, activation='sigmoid'))
        lstm.add(Dense(100, activation='softmax', dtype='float32'))
        return lstm(x)

    def build_generator(self):
        # this is the noise space commonly refered to in GAN
        z0 = Input(shape=(self.maxlen[0],), dtype='float32')
        z1 = Input(shape=(self.maxlen[1],), dtype='float32')
        z2 = Input(shape=(self.maxlen[2],), dtype='float32')
        # this will be our label
        lau = Input(shape=(1,), dtype='float32')
        lacue = Input(shape=(1,), dtype='float32')

        temp = multiply([lau, lacue])
        x0 = multiply([z0, temp])
        x1 = multiply([z1, temp])
        x2 = multiply([z2, temp])
        fake0 = self.lstm_layer(x0, self.maxlen[0])
        fake1 = self.lstm_layer(x1, self.maxlen[1])
        fake2 = self.lstm_layer(x2, self.maxlen[2])

        return Model(inputs=[z0, z1, z2, lau, lacue], outputs=[fake0, fake1, fake2])

    def bilstm_layer(self, x, maxlen):
        bilstm = Sequential()
        bilstm.add(Bidirectional(LSTM(50, input_shape=(maxlen, 100), return_sequences=True, dropout=self.dropout)))
        bilstm.add(Dense(maxlen))
        p = bilstm(x)
        m = Dense(1, activation='tanh')(p)
        a = Dense(1, activation='softmax')(m)
        h = multiply([p, a])
        o = Dense(1, activation='tanh')(h)
        out = Reshape((maxlen,))(o)

        return out

    def build_discriminator(self):
        sip_path = Input(shape=(self.maxlen[0], 100,), dtype='float32')
        rs_path = Input(shape=(self.maxlen[1], 100,), dtype='float32')
        cue_path = Input(shape=(self.maxlen[2], 100,), dtype='float32')
        i = Input(shape=(100, ), dtype='float32')
        t = Input(shape=(100, ), dtype='float32')
        hs = self.bilstm_layer(sip_path, self.maxlen[0])
        hr = self.bilstm_layer(rs_path, self.maxlen[1])
        hc = self.bilstm_layer(cue_path, self.maxlen[2])

        fu = concatenate([hs, hr])
        fcue = concatenate([i, t, hc])
        outu = Dense(3, activation='softmax')(fu)
        outc = Dense(1, activation='sigmoid')(fcue)
        fakes = Dense(1, activation='softmax')(hs)
        faker = Dense(1, activation='softmax')(hr)
        fakec = Dense(1, activation='softmax')(hc)
        fakes = concatenate([fakes, faker, fakec])
        rfake = Dense(1, activation='sigmoid')(fakes)

        return Model(inputs=[sip_path, rs_path, cue_path, i, t], outputs=[rfake, outu, outc])

    def build_combine(self):
        # build discriminator
        self.discriminator = self.build_discriminator()
        sgd1 = SGD(lr=0.3)
        self.discriminator.compile(optimizer=Adam(lr=self.lr, beta_1=0.5),
                              loss=['binary_crossentropy', 'sparse_categorical_crossentropy',
                                    'binary_crossentropy'],
                              metrics=['accuracy'])

        # build generator
        self.generator = self.build_generator()
        sgd2 = SGD(lr=0.3)
        self.generator.compile(optimizer=Adam(lr=self.lr, beta_1=0.5),
                          loss=['sparse_categorical_crossentropy', 'sparse_categorical_crossentropy',
                                'sparse_categorical_crossentropy'],
                          metrics=['accuracy'])

        # this is the z space commonly refered to in GAN
        n0 = Input(shape=(self.maxlen[0],), dtype='float32', name='n0')
        n1 = Input(shape=(self.maxlen[1],), dtype='float32', name='n1')
        n2 = Input(shape=(self.maxlen[2],), dtype='float32', name='n2')

        # this will be our label
        labu = Input(shape=(1,), dtype='float32', name='labu')
        labcue = Input(shape=(1,), dtype='float32', name='labcue')
        pos = Input(shape=(100,), dtype='float32', name='pos')
        ct = Input(shape=(100,), dtype='float32', name='ct')

        self.discriminator.trainable = False
        fs, fr, fc = self.generator([n0, n1, n2, labu, labcue])
        fv, uv, cv = self.discriminator([fs, fr, fc, pos, ct])
        self.combine = Model(inputs=[n0, n1, n2, labu, labcue, pos, ct], outputs=[fv, uv, cv])

        sgd3 = SGD(lr=0.3)
        self.combine.compile(optimizer=Adam(lr=self.lr, beta_1=0.5),
                        loss=['binary_crossentropy', 'sparse_categorical_crossentropy',
                              'binary_crossentropy'],
                        metrics=['accuracy'])

    def train_gan(self, key):
        print('file:', str(key+1))
        # get data
        self.load_data(key)
        self.build_combine()
        tr_x0, tr_x1, tr_x2, tr_x3, tr_x4, tr_x5, tr_x6, tr_x7, tr_x8, tr_y0, tr_y1, tr_y_one = self.train_set
        va_x0, va_x1, va_x2, va_x3, va_x4, va_x5, va_x6, va_x7, va_x8, va_y0, va_y1, va_y_one = self.valid_set
        te_x0, te_x1, te_x2, te_x3, te_x4, te_x5, te_x6, te_x7, te_x8, te_y0, te_y1, te_y_one = self.test_set
        f = 0
        g_loss = [0]
        d_loss = [0]

        for epoch in range(self.epochs):
            print('Epoch {} of {}'.format(epoch + 1, self.epochs))

            batch = int(len(self.train_set[0]) / self.batch)
            # progress_bar = Progbar(target=batch)

            for i in range(batch):
                # progress_bar.update(i)
                # generate a new batch of noise
                begin = i * self.batch
                end = (i + 1) * self.batch if (i + 1) * self.batch < len(self.train_set[0]) else len(self.train_set[0])
                lenth = end - begin
                # get a batch of real daata
                t = np.array(tr_x4)
                temp_sip = np.array(tr_x4[begin: end])
                temp_rs = np.array(tr_x5[begin: end])
                temp_cue = np.array(tr_x6[begin: end])
                idx = np.array(tr_x7[begin: end])
                ty = np.array(tr_x8[begin: end])

                real_sip = emb(self.embdding, temp_sip)
                real_rs = emb(self.embdding, temp_rs)
                real_cue = emb(self.embdding, temp_cue)
                index = emby(self.embdding, idx)
                cue_type = emby(self.embdding, ty)

                tr_yu = np.array(tr_y0[begin: end]).reshape((lenth, 1))
                tr_ycue = np.array(tr_y1[begin: end]).reshape((lenth, 1))
                tr_yf = np.array(tr_y_one[begin: end])

                rng = np.random.RandomState(9998)
                noise0 = rng.normal(scale=0.01, size=(lenth, self.maxlen[0])).astype('float32')
                noise1 = rng.normal(scale=0.01, size=(lenth, self.maxlen[1])).astype('float32')
                noise2 = rng.normal(scale=0.01, size=(lenth, self.maxlen[2])).astype('float32')

                fake_sip, fake_rs, fake_cue = self.generator.predict([noise0, noise1, noise2, tr_yu, tr_ycue])
                fake_yf = np.zeros((lenth,1), dtype=float)
                fake_yu = np.random.randint(0, 3, (lenth, 1)).astype('int32')
                fake_ycue = np.random.randint(0, 2, (lenth, 1)).astype('int32')
                sips = np.concatenate([real_sip, fake_sip], axis=0)
                rss = np.concatenate([real_rs, fake_rs], axis=0)
                cues = np.concatenate([real_cue, fake_cue], axis=0)
                indexs = np.concatenate([index, index], axis=0)
                types = np.concatenate([cue_type, cue_type], axis=0)
                tr_f = np.concatenate([tr_yf, np.zeros((lenth,),dtype=float)]).reshape((-1, 1))
                tr_u = np.concatenate([tr_yu, fake_yu]).reshape((-1, 1))
                tr_cue = np.concatenate([tr_ycue, fake_ycue]).reshape((-1, 1))

                if d_loss[0] < g_loss[0] *0.8:
                    g_loss = self.combine.train_on_batch([noise0, noise1, noise2, tr_yu, tr_ycue, index, cue_type],
                                                         [fake_yf, fake_yu, fake_ycue], class_weight=[None, 'auto', 'auto'])
                elif g_loss[0] < d_loss[0]*0.8:
                    d_loss = self.discriminator.train_on_batch([sips, rss, cues, indexs, types], [tr_f, tr_u, tr_cue], class_weight=[None, 'auto', 'auto'])
                else:
                    d_loss = self.discriminator.train_on_batch([sips, rss, cues, indexs, types], [tr_f, tr_u, tr_cue], class_weight=[None, 'auto', 'auto'])
                    g_loss = self.combine.train_on_batch([noise0, noise1, noise2, tr_yu, tr_ycue, index, cue_type], [fake_yf, fake_yu, fake_ycue],  class_weight=[None, 'auto', 'auto'])
                print("%d [D loss: %f, G loss: %f]" % (i, d_loss[0], g_loss[0]))

            print('\nTesting for epoch {}:'.format(epoch + 1))

            # get valid data
            temp_sip = np.array(va_x4)
            temp_rs = np.array(va_x5)
            temp_cue = np.array(va_x6)
            real_sip = emb(self.embdding, temp_sip)
            real_rs = emb(self.embdding, temp_rs)
            real_cue = emb(self.embdding, temp_cue)
            idx = np.array(va_x7)
            ty = np.array(va_x8)
            index = emby(self.embdding, idx)
            tp = emby(self.embdding, ty)

            va_yu = np.array(va_y0).reshape((-1, 1))
            va_ycue = np.array(va_y1).reshape((-1, 1))
            va_yf = np.array(va_y_one).reshape((-1, 1))
            self.discriminator.train_on_batch([real_sip, real_rs, real_cue, index, tp], [va_yf, va_yu, va_ycue])

            # get test data
            temp_sip = np.array(te_x4)
            temp_rs = np.array(te_x5)
            temp_cue = np.array(te_x6)
            real_sip = emb(self.embdding, temp_sip)
            real_rs = emb(self.embdding, temp_rs)
            real_cue = emb(self.embdding, temp_cue)
            idx = np.array(te_x7)
            ty = np.array(te_x8)
            index = emby(self.embdding, idx)
            tp = emby(self.embdding, ty)

            te_ycue = np.array(te_y1).reshape((-1, 1))
            size = te_ycue.shape[0]
            yf, yu, ycue = self.discriminator.predict([real_sip, real_rs, real_cue, index, tp])
            preu = yu.argmax(axis=-1).reshape((1, size))[0]
            precue = ycue
            gold, pre, au_gold, au_pre, in_gold, in_pre = get_pre(preu, precue,key)
            P, R, F = score(gold, pre, False)
            if F > f:
                f = F
                tpreu = yu.argmax(axis=-1).reshape((1, size))[0]
                tprecue = ycue
                filepre = "data/model/gan/"
                num = str(key) + '_' + str(epoch) + '.h5'
                self.disfile = filepre+'dis'+num
                self.genfile = filepre+'gen'+num
                self.comfile = filepre+'com'+num
                self.discriminator.save(self.disfile)
                self.generator.save(self.genfile)
                self.combine.save(self.comfile)

        gold, pre, au_gold, au_pre, in_gold, in_pre = get_pre(tpreu, tprecue, key)
        print('best F1:\n all:')
        all_result = scoreF(gold, pre, False)
        print('author:')
        au_result = scoreF(au_gold, au_pre, False)
        print('in source:')
        in_result = scoreF(in_gold, in_pre, False)

        return all_result, au_result, in_result

    def test_gan(self):
        dis = load_model(self.disfile)
        self.build_combine()
        te_x0, te_x1, te_x2, te_x3, te_x4, te_x5, te_x6, te_x7, te_x8, te_y0, te_y1, te_y_one = self.test_set
        # get test data
        temp_sip = np.array(te_x4)
        temp_rs = np.array(te_x5)
        temp_cue = np.array(te_x6)
        real_sip = emb(self.embdding, temp_sip)
        real_rs = emb(self.embdding, temp_rs)
        real_cue = emb(self.embdding, temp_cue)
        idx = np.array(te_x7)
        ty = np.array(te_x8)
        index = emby(self.embdding, idx)
        tp = emby(self.embdding, ty)

        te_ycue = np.array(te_y1).reshape((-1, 1))
        size = te_ycue.shape[0]
        yf, yu, ycue = dis.predict([real_sip, real_rs, real_cue, index, tp])
        preu = yu.argmax(axis=-1).reshape((1, size))[0]
        precue = ycue
        gold, pre, au_gold, au_pre, in_gold, in_pre = get_pre(preu, precue, key)
        P, R, F = score(gold, pre, False)
        print('best F1:\n all:')
        all_result = scoreF(gold, pre, False)
        print('author:')
        au_result = scoreF(au_gold, au_pre, False)
        print('in source:')
        in_result = scoreF(in_gold, in_pre, False)

        return all_result, au_result, in_result

def emb(emb, x):
    y = np.zeros((x.shape[0],x.shape[1], 100))
    for k in range(len(x)):
        for i in range(len(x[k])):
            y[k][i] = emb[x[k][i]]
    return y

def emby(emb, x):
    # embeding label
    y = np.zeros((x.shape[0], 100))
    for k in range(len(x)):
        y[k] = emb[x[k]]
    return y.astype(np.float32)

def change(x, num):
    y = np.zeros((x.shape[0], num))
    for i in range(len(x)):
        y[i] = to_categorical(x[i], num)
    return y

def judge_label(u_label, cue_label, cue):
    dic = {0:'Uu', 1:'PS+', 2:'PR+',3:'CT+', -1:'PS-', -2:'PR-',-3:'CT-'}
    i = 0
    apply = []
    if '2' in u_label:
        return 'other'
    if len(set(u_label)) == 1 and 0 in set(u_label):
        return 'Uu'
    for lu, lc in zip(u_label, cue_label):
        if lu == 0:
            res = 0
        else:
            if lc >= 0.1:
                apply.append(i)
        i += 1
    pre = 1
    v = 0
    va = 3
    if apply:
        # ps:1  pr:2    neg:3   ps_neg:4    pr_neg:5
        for j in apply:
            if cue[j] == '4' or cue[j] == '5':
                pre = -1
                if cue_label[j] > v:
                    v = cue_label[j]
                    va = int(cue[j])-3

            elif cue[j] == '3':
                pre = -1
            elif cue[j] == '1' or cue[j]=='2':
                if cue_label[j] > v:
                    v = cue_label[j]
                    va = int(cue[j])
        res = pre * va
    else:
        res = 3

    return dic[res]

def get_pre(resu, reacue, index):
    #[sen_id, event, source, value, c]
    with open('find.pkl', 'rb') as file:
        file_feature = pickle.load(file)
    feature = file_feature[index]
    result_pre = []
    result_gold = []
    author_pre = []
    author_gold = []
    in_pre = []
    in_gold = []
    i = 0
    for feat in feature:
        prefeature = feat[:3]
        value = feat[-2]
        cue = feat[-1]
        sou = feat[2]
        result_gold.append(value)
        lenth = len(cue)
        pre = judge_label(resu[i:i+lenth], reacue[i:i+lenth], cue)
        i = i + lenth
        result_pre.append(pre)
        if sou == 'AUTHOR':
            author_gold.append(value)
            author_pre.append(pre)
        else:
            in_gold.append(value)
            in_pre.append(pre)
    return result_gold, result_pre, author_gold, author_pre, in_gold, in_pre

def score(golds, pres, flag=True):
    TP = 0
    TN = 0
    FP = 0
    FN = 0
    for gold, pre in zip(golds, pres):
        if gold != 'CT+':
            if pre == gold:
                TP += 1
            else:
                FN += 1
        else:
            if pre != 'CT+':
                FP += 1
            else:
                TN += 1
    acc = (TP + TN)*1.0 /(TP+TN+FP+FN)

    if TP+FP == 0:
        P = 0.0
    else:
        P = TP*1.0/(TP+FP)
    if TP+FN == 0:
        R = 0
    else:
        R = TP*1.0/(TP+FN)
    if P == 0.0 or R == 0.0:
        F = 0.0
    else:
        F = 2 * P*R/(P+R)
    if flag:
        print('acc:', acc)
        print('TP:', TP, '\tTN:', TN, '\tFP', FP,'\tFN', FN)
    print('acc:', acc, 'P:', P, "\tR:", R, '\tF',F)
    return P, R, F

if __name__ == '__main__':
    resall = {'Uu': 0, 'PR+': 0, 'PS+': 0, 'CT-': 0, 'PS-': 0, 'PR-': 0, 'CT+':0, 'micro':0,'macro':0}
    resau = {'Uu': 0, 'PR+': 0, 'PS+': 0, 'CT-': 0, 'PS-': 0, 'PR-': 0, 'CT+':0, 'micro':0,'macro':0}
    resin = {'Uu': 0, 'PR+': 0, 'PS+': 0, 'CT-': 0, 'PS-': 0, 'PR-': 0, 'CT+':0, 'micro':0,'macro':0}
    ac = GAN()
    flag = 'train'
    for i in range(10):
        if flag == 'train':
            all, author, inr = ac.train_gan(i)
        else:
            all, author, inr = ac.test_gan(i)
        for key in resall.keys():
            if key in all.keys():
                resall[key] += all[key]
            if key in author.keys():
                resau[key] += author[key]
            if key in inr.keys():
                resin[key] += inr[key]

    print('Uu:'+str(resall['Uu']/10)+'\tPR+:'+str(resall['PR+']/10)+'\tPS+'+str(resall['PS+']/10)+'\tCT-'
          +str(resall['CT-']/10)+ '\tPS-'+str(resall['PS-']/10)+ '\tPR-'+str(resall['PR-']/10)+ '\tCT+'
          +str(resall['CT+']/10)+'\tmicro'+str(resall['micro']/10)+'\tmacro'+str(resall['macro']/10))
    print('Uu:' + str(resau['Uu'] / 10) + '\tPR+:' + str(resau['PR+'] / 10) + '\tPS+' + str(resau['PS+'] / 10) + '\tCT-'
          + str(resau['CT-'] / 10) + '\tPS-' + str(resau['PS-'] / 10) + '\tPR-' + str(resau['PR-'] / 10) + '\tCT+'
          + str(resau['CT+'] / 10) + '\tmicro' + str(resau['micro'] / 10) + '\tmacro' + str(resau['macro'] / 10))
    print('Uu:' + str(resin['Uu'] / 10) + '\tPR+:' + str(resin['PR+'] / 10) + '\tPS+' + str(resin['PS+'] / 10) +
          '\tCT-'+ str(resin['CT-'] / 10) + '\tPS-' + str(resin['PS-'] / 10) + '\tPR-' + str(resin['PR-'] / 10)
          + '\tCT+'+ str(resin['CT+'] / 10) + '\tmicro' + str(resin['micro'] / 10) + '\tmacro' + str(resin['macro'] / 10))


import sqlalchemy
from sqlalchemy import create_engine, inspect, MetaData
from sqlalchemy.orm import Session
import os, sys
import oracledb

from pathlib import Path

running_at = Path(__file__)
project_dir = running_at.parent.parent.parent
sys.path.append(str(project_dir))
os.chdir(str(project_dir))  # so admin app can find images, code

import database.models as models

# *******************************************
# Use this to inspect SQLAlchemy2 connection
# *******************************************

def print_meta(meta):
    print("\n\nmeta.sorted_tables (meta = models.metadata.sorted_tables)\n")
    for each_table in meta.sorted_tables:
        print(f'\n{each_table.key}')
        for each_column in each_table.columns:
            print(f'\t{each_column.name}')

db_loc = str(project_dir.joinpath('database/db.sqlite'))
db_url = "sqlite:////Users/val/dev/servers/ApiLogicProject/database/db.sqlite"
db_url = f"sqlite:///{db_loc}"
# db_url = "sqlite:////Users/val/dev/servers/ApiLogicProject/database/nw-gold.sqlite"
from config import Config
db_url = Config.SQLALCHEMY_DATABASE_URI

if 'oracle' in db_url:
    oracle_thick = False
    if oracle_thick:
        import oracledb
        oracledb.init_oracle_client()

print(f'\n Attempting connect with:\n{db_url}\n')

e = sqlalchemy.create_engine(db_url)
inspector = inspect(e)
conn = e.connect()

with Session(e) as session:
    print(f'session: {session}')
    # metadata = MetaData(bind=e)
    metadata = MetaData()  # SQLAlchemy2
    meta = models.metadata  # tables should show list of db tables
    print_meta(meta)
    print("\n\n")

    is_northwind = False
    if is_northwind:
        """
        Caution - disable / delete this code if your database is not Northwind

        Caution - use of debugger may result in "no app context"
        https://stackoverflow.com/questions/34122949/working-outside-of-application-context-flask
        """
        order_id = 10643
        order : models.Order = session.query(models.Order).filter(models.Order.Id == order_id).one()
        # hover to view code completion...
        print(f'Order: {order.Id}, AmountTotal: {order.AmountTotal}, ready: {order.Ready}, Required: {order.RequiredDate}, Customer: {order.CustomerId}, Balance: {order.Customer.Balance}\n\n')
        order.AmountTotal

        departments = session.query(models.Department).all()
        for each_dept in departments:
            print(f'\nDept: {each_dept}')
            for each_works_for_emp in each_dept.EmployeeList1:
                print(f'...each_works_for_emp: {each_works_for_emp}')
            print("")
            for each_on_loan_emp in each_dept.EmployeeList:
                print(f'...each_on_loan_emp: {each_on_loan_emp}')
            print("")
            for each_sub_dept in each_dept.DepartmentList:
                print(f'...each_sub_dept: {each_sub_dept}')


from cas.common.models import BuildResult, BuildSubsystem
from pathlib import Path

import sys
import shutil
import importlib.util
import contextlib

class FGDBuildSubsystem(BuildSubsystem):
    """
    Subsystem that builds FGDs and Hammer assets from HammerAddons
    """

    def build(self, force: bool = False) -> BuildResult:
        project = self.env.config.options.project

        srcpath = Path(self.env.root).joinpath(self.config.source).resolve()
        destpath = Path(self.env.root).joinpath(self.config.dest).resolve()

        spec = importlib.util.spec_from_file_location(
            "hammeraddons.unifyfgd", srcpath.joinpath("unify_fgd.py")
        )
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)

        build_dest = srcpath.joinpath("build")
        if not build_dest.exists():
            build_dest.mkdir()

        outfile = build_dest.joinpath(f"{project}.fgd")

        # redirect our output so logs aren't spammed on non-verbose mode
        log_dev = sys.stdout if self.env.verbose else None
        with contextlib.redirect_stdout(log_dev):
            mod.action_export(
                srcpath.joinpath("fgd"),
                None,
                frozenset({"SRCTOOLS", self.config.branch}),
                outfile,
                False,
                False,
            )

        hammer_dir = destpath.joinpath("hammer")

        shutil.copy(outfile, hammer_dir.joinpath("cfg", f"{project}.fgd"))

        self.override_folder(
            srcpath.joinpath("hammer", "materials"), hammer_dir.joinpath("materials")
        )
        self.override_folder(
            srcpath.joinpath("hammer", "models"), hammer_dir.joinpath("models")
        )
        self.override_folder(
            srcpath.joinpath("hammer", "scripts"), hammer_dir.joinpath("scripts")
        )

        return BuildResult(True)

    def clean(self) -> bool:
        return True

    def override_folder(self, src, dest):
        if dest.exists():
            shutil.rmtree(dest)
        shutil.copytree(src, dest)

_subsystem = FGDBuildSubsystem


#Bible https://developers.google.com/protocol-buffers/docs/pythontutorial

import first_msg_with_pkg_pb2 as fmwpkg_pb2

sample_message = fmwpkg_pb2.Person()

sample_message.age = 10
sample_message.first_name = "Gui"
sample_message.last_name = "Rod"
sample_message.is_verified = True
sample_message.height = 7.2

#REPEATED examples
sample_message.phone_numbers.append("(11) 95973-1135")
sample_message.phone_numbers.extend(["(11) 95973-143134", "WHAT THE HECK"])
my_list = sample_message.phone_numbers
my_list.append("WOW")

#ENUM example
sample_message.certification = sample_message.practitioner

#Nested Message example
"""This example refers to the birthday attribute, that relies on a Message declared outside first-msg-with-pkg.proto, date.proto"""
sample_message.birthday.year = 2021
sample_message.birthday.month = 1
sample_message.birthday.day = 21

#Repeated Nested Message examples
"""This example refers to the addresses attribute(s), that relies on a Message declared inside first-msg-with-pkg.proto"""
sample_message.addresses.add(address_line_1="idk", address_line_2="idek")
second_address = sample_message.addresses.add()
second_address.address_line_1="idk either"
second_address.address_line_2="neither me!"
"""And now explicity show that address is underlying Person"""
third_address = fmwpkg_pb2.Person.Address()
third_address.address_line_1="am I going nuts?"
third_address.address_line_2="Yes, I am"
sample_message.addresses.extend([third_address])

with open("ptb.bin", 'wb') as f:
    ptb = sample_message.SerializeToString()
    f.write(ptb)
    f.close()

with open("ptb.bin", 'rb') as f:
    simple_message_read = fmwpkg_pb2.Person.FromString(f.read())
    print("DEU?")

print(simple_message_read)


#상하좌우
#공간 조건 : 시작지점(1,1), 가장 오른쪽 아래 좌표(N,N)
# (1,1) (1,2) (1,3)
# (2,1) (2,2) (2,3)
# (3,1) (3,2) (3,3)
#N을 입력받기
n = int(input())
x,y =1,1
plans = input().split()

#L,R,U,D에 따른 이동 방향
dx = [0,0,-1,1]
dy = [-1,1,0,0]
move_types = ['L','R','U','D']

#이동 계획 확인
for plan in plans:
    #이동 후 좌표 구하기
    for i in range(len(move_types)):
        if plan == move_types[i]:
            nx=x+dx[i]
            ny=y+dy[i]
    #공간을 벗어나는 경우 무시
    if nx < 1 or ny <1 or nx>n or ny>n:
        continue
    #이동수행
    x, y = nx, ny

print(x,y)


#给定一个数字 N，当它满足以下条件的时候返回 true：
#原数字旋转 180° 以后可以得到新的数字。
#如 0, 1, 6, 8, 9 旋转 180° 以后，得到了新的数字 0, 1, 9, 8, 6 。
#2, 3, 4, 5, 7 旋转 180° 后，得到的不是数字。
#易混淆数 (confusing number) 在旋转180°以后，可以得到和原来不同的数，且新数字的每一位都是有效的。
#来源：力扣（LeetCode）
#链接：https://leetcode-cn.com/problems/confusing-number
#著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

class Solution:
    def confusingNumber(self, N: int) -> bool:
        temp=N
        a=list(str(temp))
        b=[]
        l=len(a)-1
        for i in range(len(a)):
            if(a[l-i]=="2" or a[l-i]=="3" or a[l-i]=="4" or a[l-i]=="5" or a[l-i]=="7"):
                return False
            elif(a[l-i]=="6"):
                b.append("9")
            elif(a[l-i]=="9"):
                b.append("6")
            else:
                b.append(a[l-i])
        temp=int("".join(b))
        if(temp!=N):
            return True
        else:
            return False


# Sets can only have one value in a list
# s

days = set(["Monday", "Tuesday", "Wednesday", "Wednesday"])

days.add("Friday")
days.add("Saturday")
# days.remove("Wednesday")

# days.discard("Friday")
print(days)


import os
import shutil
import sys
from pathlib import Path

""" Find and sort a list of timestamps in a reports directory.
"""
def get_timestamps(dir):
    timestamps = os.listdir(dir)
    timestamps.sort(reverse=True)
    return timestamps

""" Return true if file string is a results html file (so no index).
"""
def is_results_html(file):
    return file.endswith(".html") and not file.endswith("index.html")

""" Return true if there is an index.html for this timestamp, otherwise it contains no results.
"""
def is_valid_timestamp_dir(dir):
    return os.path.isdir(dir) and "index.html" in os.listdir(dir)

""" Return true if the reactor reactive mutator was active for this result file.
"""
def mutator_active_in_file(file):
    return "
REACTOR_REACTIVE_MUTATOR
" in file.read()

def iterate_files(project_root, dest):
    for dir, _, _ in os.walk(project_root):
        if dir.endswith("target/pit-reports"):
            report_mutator_active = None
            timestamps = get_timestamps(dir)

            # Iterate timestamps to find the latest mutator active report.
            for timestamp in timestamps:
                if not report_mutator_active:
                    if is_valid_timestamp_dir(dir + "/" + timestamp):
                        # Find the first html file that is not index.html to check if the mutator was active.
                        for dir2, _, files in os.walk(dir + "/" + timestamp):
                            for file in files:
                                if is_results_html(file):
                                    f = open(dir2 + "/" + file, "r")
                                    if mutator_active_in_file(f):
                                        if not report_mutator_active:
                                            report_mutator_active = timestamp
                                    break
                else:
                    break

            if len(timestamps) > 0:
                # Check if there are reports for active and inactive after iterating reports.
                if report_mutator_active is None:
                    exit("Missing a report for REACTIVE_MUTATOR active.\nin " + dir)

                # Copy reports to reactive and non-reactive subfolders of destination.
                # print("Report for", dir, "is", report_mutator_active)
                shutil.copytree(dir + "/" + report_mutator_active, dest + "/" + project_root.split("/")[-1] + dir.split(project_root)[1])

if __name__ == "__main__":
    if len(sys.argv) > 2:
        project_root = sys.argv[1]
        result_dest = sys.argv[2]
        filepaths = iterate_files(project_root, result_dest)
    else:
        exit("Usage: python collect.py <project_root> <result_dest>")


"""
CIS 122 Assignment 08
Name: Ohm Sabpisal
Credit: N/A
Class: CIS 122
Date: December 6, 2019
Description: --------------------------------
"""

run = True
#global user_input_group_name # Initialize key_list in order for this list to be used as the value of the user_input_group_name dictionary which is inside the dictionary_for_groups dictionary.

# Part 1: Required Function:
def create_group(user_input_group_name):  # Creates a new group and group properties.
    global the_group_name
    the_group_name = user_input_group_name
    if len(user_input_group_name) == 0:
        exit
    elif user_input_group_name != 0:
        """
        Name of the key inside the dictionary_for_groups
        dictionary.
        """
        dictionary_for_groups[user_input_group_name] = {}
        """
        Create a new dictionary in the dictionary_for_groups.
        The key of this dictionary will be called the value of
        the user_input_group_name_variable.
        """
        keys_list = []
        dictionary_for_groups[user_input_group_name]['_data_'] = {}
        while True:
            user_input_field_name = input("Enter field name (empty to stop): ").strip()
            if len(user_input_field_name) == 0:
                break
            elif len(user_input_field_name) != 0:
                keys_list.append(user_input_field_name)
                dictionary_for_groups[user_input_group_name]['_data_'][user_input_field_name] = ''

                """
                Add the field name into the list which is a value
                of the user_input_group_name dictionary which is
                inside the dictionary_for_groups dictionary.
                """
        dictionary_for_groups[user_input_group_name]['_keys_'] = keys_list
        """
        Set a value of the key named '_keys_' which
        inside of the user_input_group_name dictionary.
        """
        print(dictionary_for_groups)

# Part 7: List Groups
def list_groups():  # List group names and numbers of properties.
    print("** List of Groups **")
    for key, value in dictionary_for_groups.items():
        current_key = key
        print(key.title() + " : " + str(len(value['_keys_'])) + " properties " + str(value['_keys_']))

# Part 8: Add Group Data
def add_group_data(): # Add data to a group to a group for each group property.
    print("** Add group data **")
    print("** List of Groups **")
    for key, value in dictionary_for_groups.items():
        current_key = key
        print(key.title() + " : " + str(len(value['_keys_'])) + " properties " + str(value['_keys_']))
    group_to_add_data = input("Enter group (empty to cancel): ")
    for properties in dictionary_for_groups[group_to_add_data]['_keys_']:
        user_property_replacement = input("Enter " + properties + ": ")

# Part 9: List Data for Group
def list_group_data(): # List all data for a group.
    print("** List of group data**")
    print("** List of Groups **")
    #user_list_group_data = input("Enter group name (empty to cancel): ")
    user_0 = dictionary_for_groups["Songs"]["_data_"][0]
    print(user_0)
    #for key, value in user_0.items():
     #   print(key)

# Part 2: Group Variable
dictionary_for_groups = {

}

# Part 3: Primary Input Loop
print(">> Welcome to Group Manager <<")
print("This program creates groups with dynamic properties\n")

while run:
    user_prompt = input("Command (empty or X to quit, ? for help): ").strip()
    user_prompt = user_prompt.strip()
    user_prompt = user_prompt.upper()
    if len(user_prompt) == 0:
        run = False
    elif (user_prompt == 'X'):
        run = False
    elif user_prompt == '?':
    # Part 4: Help Command
        print('?: list commands\n' +
              'C: Create a new group\n' +
              'G: List groups\n' +
              'A: Add data to a group\n' +
              'L: List data for a group\n' +
              'X: Exit\n')

    # Part 6: Create New Group
    if (user_prompt == 'C'):
        user_input_group_name = input("Enter group name (empty to cancel): ").strip()
        create_group(user_input_group_name)
    # Part 7: List Group
    if (user_prompt == 'G'):
        list_groups()
    # Part 8: Add Group Data
    if (user_prompt == 'A'):
        add_group_data()
    # Part 9: List Data for Group
    if (user_prompt == 'L'):
        list_group_data()

print(dictionary_for_groups)


'''MobileNetV2 in PyTorch.

See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F

from .deconv import *

class Block(nn.Module):
    '''expand + depthwise + pointwise'''
    def __init__(self, in_planes, out_planes, expansion, stride, deconv=None):
        super(Block, self).__init__()
        self.stride = stride

        planes = expansion * in_planes
        if deconv:
            self.deconv=True
            self.conv1 = deconv(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=True)
            self.conv2 = deconv(planes, planes, kernel_size=3, stride=stride, padding=1, groups=planes, bias=True,n_iter=1)
            self.conv3 = deconv(planes, out_planes, kernel_size=1, stride=1, padding=0, bias=True,block=in_planes,n_iter=1)

            self.shortcut = nn.Sequential()
            if stride == 1 and in_planes != out_planes:
                self.shortcut = nn.Sequential(
                    deconv(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=True)
                )

        else:
            self.deconv=False
            self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=False)
            self.bn1 = nn.BatchNorm2d(planes)
            self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, groups=planes, bias=False)
            self.bn2 = nn.BatchNorm2d(planes)
            self.conv3 = nn.Conv2d(planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
            self.bn3 = nn.BatchNorm2d(out_planes)

            self.shortcut = nn.Sequential()
            if stride == 1 and in_planes != out_planes:
                self.shortcut = nn.Sequential(
                    nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False),
                    nn.BatchNorm2d(out_planes),
                )

    def forward(self, x):
        if self.deconv:
            out = F.relu(self.conv1(x))
            out = F.relu(self.conv2(out))
            out = self.conv3(out)
        else:
            out = F.relu(self.bn1(self.conv1(x)))
            out = F.relu(self.bn2(self.conv2(out)))
            out = self.bn3(self.conv3(out))
        out = out + self.shortcut(x) if self.stride==1 else out
        return out

class MobileNetV2(nn.Module):
    # (expansion, out_planes, num_blocks, stride)
    cfg = [(1,  16, 1, 1),
           (6,  24, 2, 1),  # NOTE: change stride 2 -> 1 for CIFAR10
           (6,  32, 3, 2),
           (6,  64, 4, 2),
           (6,  96, 3, 1),
           (6, 160, 3, 2),
           (6, 320, 1, 1)]

    def __init__(self, num_classes=10, deconv=None,delinear=None,channel_deconv=None):
        super(MobileNetV2, self).__init__()
        # NOTE: change conv1 stride 2 -> 1 for CIFAR10
        if deconv:
            self.deconv=True
            self.conv1 = deconv(3, 32, kernel_size=3, stride=1, padding=1, bias=True,freeze=True,n_iter=10)
            self.conv2 = deconv(320, 1280, kernel_size=1, stride=1, padding=0, bias=True)

        else:
            self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False)
            self.bn1 = nn.BatchNorm2d(32)
            self.conv2 = nn.Conv2d(320, 1280, kernel_size=1, stride=1, padding=0, bias=False)
            self.bn2 = nn.BatchNorm2d(1280)

        self.layers = self._make_layers(in_planes=32, deconv=deconv)

        if delinear:
            self.linear = delinear(1280, num_classes)
        else:
            self.linear = nn.Linear(1280, num_classes)

        if channel_deconv:
            self.deconv1=channel_deconv()
    def _make_layers(self, in_planes, deconv=None):
        layers = []
        for expansion, out_planes, num_blocks, stride in self.cfg:
            strides = [stride] + [1]*(num_blocks-1)
            for stride in strides:
                layers.append(Block(in_planes, out_planes, expansion, stride, deconv=deconv))
                in_planes = out_planes
        return nn.Sequential(*layers)

    def forward(self, x):
        if hasattr(self,'bn1'):
            out = F.relu(self.bn1(self.conv1(x)))
        else:
            out = F.relu(self.conv1(x))

        out = self.layers(out)
        if hasattr(self,'bn2'):
            out = F.relu(self.bn2(self.conv2(out)))
        else:
            out = F.relu(self.conv2(out))
        # NOTE: change pooling kernel_size 7 -> 4 for CIFAR10
        if hasattr(self, 'deconv1'):
            out = self.deconv1(out)
        out = F.avg_pool2d(out, 4)
        out = out.view(out.size(0), -1)
        out = self.linear(out)
        return out

def test():
    net = MobileNetV2()
    x = torch.randn(2,3,32,32)
    y = net(x)
    print(y.size())

# test()


patternCount = 0
def pantip(k, n, arr, path):
    global patternCount
    if n>=len(arr):
        if k==0:
            print(*path)
            patternCount+=1
        return

    if k-arr[n]>=0:
        path.append(arr[n])
        pantip(k-arr[n],n+1,arr,path)
        path.pop()
        pantip(k,n+1,arr,path)
    else:
        pantip(k,n+1,arr,path)

    return patternCount

inp = input('Enter Input (Money, Product) : ').split('/')
arr = [int(i) for i in inp[1].split()]
pattern = pantip(int(inp[0]), 0, arr, [])
print("Krisada can purchase Product: {0} with: {1} Baht | {2} Pattern".format(arr, inp[0], pattern))

Semester 2D-1/Object Oriented Data Structures/Recusion/04 ไปเที่ยวแบบชาว Pantip.py

04 ไปเที่ยวแบบชาว Pantip.py


from unittest import result
import requests
from MyModel import ResultModelLastRecord

class StatsService:
    @staticmethod
    def get_stats(country):
        result = requests.get(f"https://api.covid19api.com/total/dayone/country/{country}").json()

        rs = ResultModelLastRecord(country,
        result[-1]['Confirmed'],
        result[-1]['Deaths'],
        result[-1]['Date'][0:10],
        result[-1]['Active'],
        )

        return rs

    @staticmethod
    def get_deaths_for_all_countries(countriesList):
        tab=[]

        for c in countriesList:
            stats = StatsService.get_stats(c)
            tab.append(stats.mystats['deaths'])

        return tab


#!/usr/bin/python3

import sys
from pyquery import PyQuery as pq

if len(sys.argv) == 2:

    contest_url  = sys.argv[1]
    print("Scrapping contest from %s\n" % contest_url)
    dom = pq(url = contest_url)
    contest_name = dom('table.rtable > tbody > tr > th').text()
    n = dom('table.problems > tr').length

    with open('.contest_metadata', 'w') as out:

        out.write("Contest: %s\n"  % contest_name)
        out.write("URL: %s\n"      % contest_url)
        out.write("Problems: %d\n" % n)

        for problem in range(1, n):
            id   = dom('table.problems > tr').eq(problem).filter('tr > td').eq(0).text()
            name = dom('table.problems > tr').eq(problem).filter('tr > td').eq(1).filter('td > div > div > a').text()
            out.write("    %s - %s\n"% (id, name))
else:
    print("USAGE: %s <CONTEST_URL>" % sys.argv[0])


import sys

# Node object
class Node():
    def __init__(self, val):
        self.val = val
        self.neighbors = []
        self.edges = dict() # map neighbors -> distances

    def add_neighbors(self, listVal):
        for val in listVal:
            self.neighbors.append(val)

def DFS(hm):
    visited = set()
    def recur_DFS(node):
        print(node.val)
        visited.add(node.val)
        for neighbor in node.neighbors:
            if neighbor.val not in visited:
                recur_DFS(neighbor)
    for node in list(hm.values()):
        if node.val not in visited:
            recur_DFS(node)

def test_dfs():
    hm = dict()
    hm[0] = Node(0)
    hm[1] = Node(1)
    hm[2] = Node(2)
    hm[3] = Node(3)
    hm[4] = Node(4)
    hm[5] = Node(5)
    hm[6] = Node(6)

    hm[0].neighbors = [hm[1],hm[3]]
    hm[1].neighbors = [hm[2],hm[3]]
    hm[3].neighbors = [hm[0],hm[2],hm[4]]
    hm[5].neighbors = [hm[6]]
    hm[6].neighbors = [hm[3]]
    DFS(hm)
# test_dfs()

def DFS_test_edges(hm, root):
    start = dict()
    end = dict()
    back_edge = []
    cross_edge = []
    forward_edge = []
    tree_edge = []
    time = 1
    def recur_DFS(node, time):
        start[node.val] = time
        for neighbor in node.neighbors:
            print(neighbor.val, start, end)
            if neighbor.val in start and neighbor.val not in end:
                back_edge.append([node.val, neighbor.val])
            elif neighbor.val in end:
                if start[neighbor.val] > start[node.val]: # neighbor started after the node, which implies forward
                    forward_edge.append([node.val, neighbor.val])
                else:
                    cross_edge.append([node.val, neighbor.val])
            else:
                tree_edge.append([node.val, neighbor.val])
                time = recur_DFS(neighbor, time + 1)

        end[node.val] = time
        return time + 1
    recur_DFS(root, time)
    print(start, end)
    print("back", back_edge)
    print("forward",forward_edge)
    print("cross",cross_edge)
    print("tree",tree_edge)

def testDFSTestEdge():
    # image: https://cs.stackexchange.com/questions/11116/difference-between-cross-edges-and-forward-edges-in-a-dft
    hm = dict()
    hm[1] = Node(1)
    hm[2] = Node(2)
    hm[3] = Node(3)
    hm[4] = Node(4)
    hm[5] = Node(5)
    hm[6] = Node(6)
    hm[7] = Node(7)
    hm[8] = Node(8)

    hm[1].neighbors = [hm[2],hm[5],hm[8]]
    hm[2].neighbors = [hm[3]]
    hm[3].neighbors = [hm[4]]
    hm[4].neighbors = [hm[2]]
    hm[5].neighbors = [hm[6]]
    hm[6].neighbors = [hm[3], hm[7], hm[8]]
    DFS_test_edges(hm, hm[1])

testDFSTestEdge()


from django.conf.urls import url

from . import views

urlpatterns=[ url(r'^$',views.index,name='index'),
			url(r'^(?P<question_id>[0-9]+)/$',views.detail,name='detail'),
			url(r'^stats/(?P<question_id>[0-9]+)$',views.stats,name='stats'),
			url(r'^addstats/(?P<player_id>[0-9]+)$',views.addstats,name='addstats'),
			url(r'^addplayer/$',views.addplayer,name='addplayer')
			]


#!/usr/bin/env python3

import computer_wordle
import random
import webbrowser

def main():

    # Create a new game for today's challenge
    game = computer_wordle.Game()

    # The game.current_hint() will be None once the game is over
    while game.current_hint() is not None:

        # all words in the word list that are of the correct length (this challenge uses both 5 and 6 letter words)
        possible_words = [word for word in computer_wordle.wordlist if len(word) == len(game.current_hint())]

        # Keep guessing until the current word is solved (no guess limit per word)
        while True:

            # Pick a random word from the list of possible words
            guess_word = random.choice(possible_words)

            response = game.guess(guess_word)
            guess_response = response['guess_response']
            print(f"{guess_word} -> {guess_response}")
            if 'next_hint' in response.keys():
                # Solved the word, on to the next one!
                print(f"SOLVED! Target word = {guess_word}")
                break
            for idx in range(len(guess_response)):
                if guess_response[idx] != computer_wordle.GRAY:
                    possible_words = [
                        word for word in possible_words
                        if guess_word[idx] in word and word != guess_word
                    ]
    print(f"Done. Results at {game.url()}")
    webbrowser.open(game.url())

if __name__ == '__main__':
    main()


import httpx
from bs4 import BeautifulSoup
from click import secho as echo
import time

def scrape_teams(url: str) -> None:
    max_pages = 2
    current_page = 1

    headers = {
            'user-agent': "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0",
            'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            'accept-language': "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3",
            'referer': "http://hydraclubbioknikokex7njhwuahc2l67lfiz7z36md2jvopda7nchid.onion/catalog/1",
            'connection': "keep-alive",
            'upgrade-insecure-requests': "1",
            'sec-fetch-dest': "document",
            'sec-fetch-mode': "navigate",
            'sec-fetch-site': "same-origin",
            'sec-fetch-user': "?1",
            'cache-control': "max-age=0"
            }

    cookies = {
            'pregate': "1646068570.39e0d0c6765fc4e8c009a0f5dbe862bc.2e0f25f14562f061dd7fd2c2a33fc1e4",
            'gate': "1646068591.253c8d72ea0bedf45400473203b45c8e.880653c8c540b21f503efa0d974c50f2",
            '_session': "eyJpdiI6IjQ0U0RPSFg4M0owdUJTNG5hSEcrb0E9PSIsInZhbHVlIjoiZDhrSCtoZnFVRkEzdnRsM3JzdUZ6eTVPMnh6TTZaR2VMY0o0eDA3U1Q2N09JUFpOYWJQVkpIa3dZR2MyN1dtTCIsIm1hYyI6IjNkZWVmZGQwNDBmMTBjYjAxZDI5NDUyZDg1NzA3M2Y4YjQ4ZGU1NjE0YmFmYjRhZjkwZTQ2OTQ2MDJiNWM0ZGEifQ%3D%3D",
            'upc': "eyJpdiI6IlNLS1dRM0UyVDhmSU1aMmpcLzdRcFdRPT0iLCJ2YWx1ZSI6IitzdFFNM2hCTlhJclNDYXhoZFdaa3Z3d0JXU3RFQWRiSXlQVTNjZFkxZGs9IiwibWFjIjoiOTBiZTAzZjNkMTQxZDE5MTUzOWQxODI1NDRlMGNmOWQ2ZGQ2ZTE5NDk0YjhiZGNiYzBmZjRiYWU1ZjEzNzUyNSJ9",
            'r1': "1646068653800"
            }

    timeout = httpx.Timeout(10.0, connect=60.0)

    with httpx.Client(proxies='socks5://127.0.0.1:9050') as hs:

        while current_page <= max_pages:
            current_url = f'{url}?query=&sort_direction=desc&sort=rate&page={current_page}'
            print(current_url)

            raw_html = hs.get(current_url, headers=headers, cookies=cookies, timeout=timeout)

            soup = BeautifulSoup(raw_html.content, 'lxml')
            items = soup.find_all('div', class_='catalog_item')

            # itemsReegion = soup.find('li', class_='over').text
            # echo(f'{itemsReegion}',bg='blue')

            for n, i in enumerate(items, start=1):
                itemName = i.find('div', class_='title').text.strip()
                itemPrice = i.find('span').text.strip()
                print(f'{n}: {itemName} {itemPrice} ')

            # print(raw_html.status_code)

        # time.sleep(10)
            current_page += 1

def main() -> int:
    url = 'http://hydraclubbioknikokex7njhwuahc2l67lfiz7z36md2jvopda7nchid.onion/catalog/2'
    scrape_teams(url)
    return 0

if __name__ == '__main__':
    exit(main())


import warnings

from django_prbac.exceptions import PermissionDenied
from django_prbac.models import Role, UserRole

def has_privilege(request, slug, **assignment):
    """
    Returns true if the request has the privilege specified by slug,
    otherwise false
    """
    privilege = Role.get_privilege(slug, assignment)
    if privilege is None:
        return False

    if hasattr(request, 'role'):
        if request.role.has_privilege(privilege):
            return True

    if hasattr(request, 'user') and hasattr(request.user, 'prbac_role'):
        try:
            request.user.prbac_role
        except UserRole.DoesNotExist:
            return False
        return request.user.prbac_role.has_privilege(privilege)

    return False

def ensure_request_has_privilege(request, slug, **assignment):
    """
    DEPRECATED
    """
    warnings.warn(
        '`ensure_request_has_privilege` is deprecated. You likely want '
        '`has_permission` or one of the `requires_privilege` decorators',
        DeprecationWarning
    )
    if not has_privilege(request, slug, **assignment):
        raise PermissionDenied()


#for parsing contacts from a csv file (macos) (remove the first line of the csv file if you get an error)
#done by selecting all contacts and dropping them into a Numbers spreadsheet, and then exporting to csv.
#eventually will be replaced by automatic importing of icloud contacts
locationDefault = ["Portland", "OR"] #because that's where I'm from
import csv
from os import stat
with open('../contacts.csv', newline='') as f:
	reader = csv.DictReader(f)
	locations = []
	for row in reader:
		if row["Address : home : Street"] == "":
			continue
		name = row["First name"].strip() + " " + row["Last name"].strip()
		street = row["Address : home : Street"].strip()
		city = row["Address : home : City"].strip()
		state = row["Address : home : State"].strip()
		if city == "":
			city = locationDefault[0]
		if state == "":
			state = locationDefault[1]
		address = street + ", " + city +", " + state
		locations.append({"name": name, "address": address, "importance": 2, "radius": "150m"})
	print(locations)#you'll have to replace "'" with '"' after putting it into the json file, and that's pretty much it.


import time
import requests.auth

from .utils import check_connection

class API(object):
    def __init__(self, cfg_cls):
        self.cfg_cls = cfg_cls
        self.config = self.cfg_cls.config
        self.refresh_token = self.config.get('refresh_token') or False
        self.token_expires = self.config.get("token_expires") or False
        self.headers = self.cfg_cls.get_headers(self.config.get('access_token'))

    @check_connection
    def get_new_token(self):
        """
        Get new token using refresh token.
        """
        client_auth = requests.auth.HTTPBasicAuth(self.cfg_cls.CLIENT_ID, "")
        response = requests.post(
            'https://www.reddit.com/api/v1/access_token',
            auth=client_auth,
            data={
                'grant_type': 'refresh_token',
                'refresh_token': self.refresh_token
            },
            headers={
                "User-Agent": self.cfg_cls.USER_AGENT
            }
        )

        if response.json().get('error'):
            return False

        access_token = response.json()['access_token']
        self.token_expires = time.time() + 3600
        self.cfg_cls.set_key('token_expires', self.token_expires)
        self.cfg_cls.set_key('access_token', access_token)
        self.set_token(access_token)
        print("Token refreshed with %s, until %s" % (response.json()['access_token'], time.time() + 3600))

    def check_token(self):
        """
        Check if current token expired
        and get new one if it is.
        """
        if time.time() >= self.token_expires:
            self.get_new_token()

    def set_token(self, token):
        """
        Set token config value and update headers.
        """
        self.cfg_cls.set_key('access_token', token)
        self.headers = self.cfg_cls.get_headers(token)

    @check_connection
    def get_user_info(self):
        """
        Get current user info.
        """
        self.check_token()
        response = requests.get('https://oauth.reddit.com/api/v1/me', headers=self.headers)
        return response.json()

    @check_connection
    def get_subreddit(self, subreddit, posts_type, posts_limit='5'):
        """
        Get subreddit info.
        """
        self.check_token()
        posts_list = []

        response = requests.get(
            'https://oauth.reddit.com/r/%s/%s' % (subreddit, posts_type),
            headers=self.headers,
            params={'limit': posts_limit}
        )
        posts = response.json()['data']['children']

        for post in posts:
            posts_list.append({
                'link': post['data']['url'],
                'title': post['data']['title'],
                'upvotes': post['data']['ups'],
                'permalink': post['data']['permalink'],
                'gilded': post['data']['gilded']
            })

        return posts_list

    @check_connection
    def get_last_message(self):
        """
        Get contents of the last unread message.
        Should run only if notifications setting is 1.
        """
        response = requests.get(
            'https://oauth.reddit.com/message/unread',
            headers=self.headers,
            params={'limit': 1}
        )

        post_data = response.json()['data']['children'][0]['data']

        return {
            'body': post_data['body'],
            'author': post_data['author']
        }


import logging
from typing import List, Dict

from explorerscript.ssb_converting.ssb_data_types import SsbOperation
from explorerscript.ssb_converting.ssb_special_ops import process_op_for_jump, SsbLabel
logger = logging.getLogger(__name__)

class OpsLabelJumpToResolver:
    def __init__(self, routines: list[list[SsbOperation]]):
        logger.debug("Constructing labels and jumps...")
        # A mapping of labels: {mem_location: label_name}
        self.labels: dict[int, SsbLabel] = {}
        self.routines = []
        for routine_id, rtn in enumerate(routines):
            new_rtn_ops = []
            self.routines.append(new_rtn_ops)
            for op in rtn:
                new_rtn_ops.append(process_op_for_jump(op, self.labels, routine_id))

    def __iter__(self):
        rtn_iterator = iter(self.routines)
        try:
            while True:
                # This will eventually raise StopIteration.
                yield list(self._iter_routine(next(rtn_iterator)))
        except StopIteration:
            return

    def _iter_routine(self, rtn):
        op_iterator = iter(rtn)
        try:
            while True:
                # This will eventually raise StopIteration.
                next_item = next(op_iterator)
                if next_item.offset in self.labels:
                    yield self.labels[next_item.offset]
                yield next_item
        except StopIteration:
            return


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

# Creating objects of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Calling methods on objects
person1.say_hello()
person2.say_hello()


#%%
import scipy.io
import scipy.io
import numpy as np
import pandas as pd

##load matlab and make datafram to save label and file_id
path= '/Users/jessica/CMT309/MLCoursework2/lists/file_list.mat'
data = scipy.io.loadmat(path)
#%%
#data.keys()
#data.get("__header__") #null
#data.get("__version__") #null
#data.get("__globals__") #null
#data.get("file_list")
#data.get("annotation_list")
#data.get("label") #null
#%%
df = pd.DataFrame()
for i in data:
  if '__' not in i and 'readme' not in i:
    data_array = data[i]
    if df.empty:
      df = pd.DataFrame(data_array)
print(df.head())

#%%
full_list = pd.DataFrame(columns=['id','label'])
for i in range(len(df)):
    full_list.loc[i,'label']=str(str(df.loc[i,0]).split('/')[0]).split('-')[1] #label
    full_list.loc[i, 'id'] = str(str(df.loc[i, 0]).split("/")[1]).split("'")[0] # file name
#%%
full_list.head()

##create path and save all images
#%%
import os
import shutil
original_dataset_dir="/Users/jessica/CMT309/MLCoursework2/Images"
base_dir="/Users/jessica/CMT309/MLCoursework2/Images_New_Path"

#create train directory, validation_directory, test_directory

train_dir=os.path.join(base_dir,"train")
validation_dir=os.path.join(base_dir,"validation")
test_dir=os.path.join(base_dir,"test")
if not os.path.exists(base_dir):
    os.mkdir(base_dir)
if not os.path.exists(train_dir):
    os.mkdir(train_dir)
if not os.path.exists(validation_dir):
    os.mkdir(validation_dir)
if not os.path.exists(test_dir):
    os.mkdir(test_dir)

#%%
#copy 80% images of all folders to train directory and change names
#copy 10% images of all folders to validation...
#copy 10% images of all folders to test....
for i in os.listdir(original_dataset_dir):
    ori_path=os.path.join(original_dataset_dir,i)
    trainpath=os.path.join(train_dir,i)
    if not os.path.exists(trainpath):
        os.mkdir(trainpath)
    validpath = os.path.join(validation_dir, i)
    if not os.path.exists(validpath):
        os.mkdir(validpath)
    testpath=os.path.join(test_dir,i)
    if not os.path.exists(testpath):
        os.mkdir(testpath)
    #print(i)
    type=i.split("-")[0]
    #print(type)
    name=i.split("-")[1]
    #print(int(len(ori_path)*0.8),int(len(ori_path)*0.9),len(ori_path))
    #train_data
    for fname in os.listdir((ori_path))[:int(len(ori_path)*0.8)]:
        #print(fname)
        id=fname.split("_")[-1]
        #print(id)
        src=os.path.join(ori_path,fname)
        new_name=os.path.join(ori_path,name+'_'+id)
        dst = os.path.join(trainpath, name+'_'+id)
        #print(src)
        if os.path.exists(src):
            print("copy1")
            os.rename(src,new_name)
            shutil.copyfile(new_name,dst)
    #validation_data
    for fname in os.listdir((ori_path))[int(len(ori_path)*0.8):int(len(ori_path)*0.9)]:
        #print(fname)
        id=fname.split("_")[-1]
        #print(id)
        src=os.path.join(ori_path,fname)
        new_name=os.path.join(ori_path,name+'_'+id)
        dst = os.path.join(validpath, name+'_'+id)
        #print(src)
        if os.path.exists(src):
            print("copy2")
            os.rename(src,new_name)
            shutil.copyfile(new_name,dst)
    #test_data
    for fname in os.listdir((ori_path))[int(len(ori_path)*0.9):]:
        #print(fname)
        id=fname.split("_")[-1]
        #print(id)
        src=os.path.join(ori_path,fname)
        new_name=os.path.join(ori_path,name+'_'+id)
        dst = os.path.join(testpath, name+'_'+id)
        #print(src)
        if os.path.exists(src):
            print("copy3")
            os.rename(src,new_name)
            shutil.copyfile(new_name,dst)

#%%
#proprecessing of images
from keras.preprocessing.image import ImageDataGenerator
train_datagen=ImageDataGenerator(rescale=1./255)
test_datagen=ImageDataGenerator(rescale=1./255)
train_generator=train_datagen.flow_from_directory(train_dir,target_size=(150,150),batch_size=20,class_mode="categorical")
validation_generator=test_datagen.flow_from_directory(validation_dir,target_size=(150,150),batch_size=20,class_mode="categorical")

#%%
from keras import layers
from keras import models
import PIL
#%%

#create model
model=models.Sequential()
model.add(layers.Conv2D(32,(3,3),activation="relu",input_shape=(150,150,3))) #(148,148,32)
model.add(layers.MaxPool2D((2,2))) #(148/2=74,74,32)
model.add(layers.Conv2D(64,(3,3),activation="relu")) #(72,72,64)
model.add(layers.MaxPool2D(2,2)) #(36,36,64)
model.add(layers.Conv2D(128,(3,3),activation="relu")) #(34,34,128)
model.add(layers.MaxPool2D(2,2)) #(17,17,128)
model.add(layers.Conv2D(128,(3,3),activation="relu")) #(15,15,128)
model.add(layers.MaxPool2D(2,2)) #(7,7,128)
model.add(layers.Flatten()) #7*7*128=6272
model.add(layers.Dense(512,activation="relu"))
model.add(layers.Dense(120,activation="sigmoid"))
model.summary()
#%%
#fit model
from keras import optimizers
model.compile(loss="categorical_crossentropy",optimizer=optimizers.RMSprop(lr=1e-4),metrics=["acc"])
history=model.fit_generator(train_generator,steps_per_epoch=100,epochs=30,validation_data=validation_generator,validation_steps=50)


#!/usr/bin/env python
import numpy as np
import struct
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

import rospy
import rospkg
from std_msgs.msg import Int32MultiArray
from sensor_msgs.msg import PointCloud2
import tf2_ros
import tf2_geometry_msgs
import geometry_msgs
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from darknet_rospy_msgs.msg import DarkBoxArray

class DarkPixelTo3DPointNode:

    def __init__(self):
        rospy.init_node('DarkPixelTo3DPointNode', anonymous=True)
        self.pointcloud_sub = rospy.Subscriber("/kinect_head/qhd/points", PointCloud2, self.pointcloud_callback, queue_size=1, buff_size=2**24)
        self.dark2d_sub = rospy.Subscriber("/darknet/recognition_result", DarkBoxArray, self.dark_callback, queue_size=1, buff_size=2**24)
        self.tf_buffer = tf2_ros.Buffer()
        self.tf_listner = tf2_ros.TransformListener(self.tf_buffer)
        self.pointcloud = None
        self.run_once_flg = False
        rospy.loginfo("Initialized DarkPixelTo3DPointNode.")

    def pixelTo3DPoint(self, u, v, pointcloud):
        point_step = pointcloud.point_step
        row_step = pointcloud.row_step
        array_pos = v*row_step + u*point_step

        bytesX = [ord(x) for x in pointcloud.data[array_pos:array_pos+4]]
        bytesY = [ord(x) for x in pointcloud.data[array_pos+4: array_pos+8]]
        bytesZ = [ord(x) for x in pointcloud.data[array_pos+8:array_pos+12]]

        byte_format=struct.pack('4B', *bytesX)
        X_sensor = struct.unpack('f', byte_format)[0]

        byte_format=struct.pack('4B', *bytesY)
        Y_sensor = struct.unpack('f', byte_format)[0]

        byte_format=struct.pack('4B', *bytesZ)
        Z_sensor = struct.unpack('f', byte_format)[0]

        nan_flg = False
        if math.isnan(X_sensor) or \
           math.isnan(Y_sensor) or \
           math.isnan(Z_sensor):
            nan_flg = True

        return [X_sensor, Y_sensor, Z_sensor], nan_flg

    def transform_3D_point_to_world_frame(self, xyz_point_from_sensor, sensor_frame_id):
        pose_stamped = geometry_msgs.msg.PoseStamped()
        pose_stamped.header.frame_id = sensor_frame_id
        pose_stamped.pose.orientation.w = 1.0
        pose_stamped.pose.position.x = xyz_point_from_sensor[0]
        pose_stamped.pose.position.y = xyz_point_from_sensor[1]
        pose_stamped.pose.position.z = xyz_point_from_sensor[2]

        transform = self.tf_buffer.lookup_transform("world",
                                                    pose_stamped.header.frame_id,
                                                    rospy.Time(0),
                                                    rospy.Duration(1.0))
        pose_transformed = tf2_geometry_msgs.do_transform_pose(pose_stamped, transform)

        X_world = pose_transformed.pose.position.x
        Y_world = pose_transformed.pose.position.y
        Z_world = pose_transformed.pose.position.z

        return [X_world, Y_world, Z_world]

    def extract_3d_points(self, dark_box):
        X = []
        Y = []
        Z = []
        for u in range(dark_box.xmin, dark_box.xmax+1):
            for v in range(dark_box.ymin, dark_box.ymax+1):
                xyz_point_from_sensor, nan_flg = self.pixelTo3DPoint(u,v,self.pointcloud)

                if nan_flg is not True:
                    xyz_point_from_world = self.transform_3D_point_to_world_frame(xyz_point_from_sensor,
                                                                                self.pointcloud.header.frame_id)
                    X.append(xyz_point_from_world[0])
                    Y.append(xyz_point_from_world[1])
                    Z.append(xyz_point_from_world[2])

        return X, Y, Z

    def plot_boxel(self, x, y, z, label, index):
        fig = plt.figure(1)
        ax = fig.gca(projection='3d')
        ax.set_xlabel(r'$x$ [m]',fontsize=14)
        ax.set_ylabel(r'$y$ [m]',fontsize=14)
        ax.set_zlabel(r'$z$ [m]',fontsize=14)
        # ax.set_xlim(0, 0.5)
        # ax.set_ylim(-0.25, 0.25)
        ax.set_zlim(-0.1, 0)

        ax.plot([0], [0], [0], 'o', color='y', ms=6 , label='world origin')
        ax.plot(x, y, z, "o", color='c', ms=3, mew=0.5, label='extracted pointcloud')
        ax.legend()

        fig.suptitle('detected object: '+label+' ['+str(index)+']' )
        plt.tight_layout()

    def pointcloud_callback(self, data):
        self.pointcloud = data

    def dark_callback(self, data):

        if self.pointcloud is None:
            return

        if self.run_once_flg is True:
            plt.pause(0.01)
            return
        else:
            self.run_once_flg = True
            index = 0
            dark_box = data.dark_array[index]
            X, Y, Z = self.extract_3d_points(dark_box)
            self.plot_boxel(X,Y,Z, dark_box.label, index)
            plt.pause(0.01)

if __name__ == '__main__':
    DarkPixelTo3DPointNode()
    try:
        rospy.spin()
    except KeyboardInterrupt:
        rospy.loginfo("Shutting Down.")


"""Test Suite for Yandex search."""
import pytest
import time

from pages.yandex.search import Search
from pages.yandex.search import SearchResult
from pages.yandex.search import Suggestions

def test_global_search_on_yandex(browser):
    """Test case of global search."""
    # Check whether the search field is available
    # Enter a Tensor in the search
    search = Search(browser)
    search_text = 'Тензор'
    search.set_search(search_text)
    # Check that the table with suggestions has appeared (suggest)
    suggestions = Suggestions(browser).get_suggestions()
    suggestions_len = len(suggestions)
    assert suggestions_len > 0, 'The suggestions list is empty.'
    search_text = search_text.lower()
    for i in range(min(suggestions_len, 5)):
        assert search_text in suggestions[i], \
            f"""The phrase "Tensor" was not found \
in the "{suggestions[i]}" suggest."""
    # When you press Enter, a table of search results appears
    # The first 5 results have a link to tensor.ru
    search.push_enter()
    header_links = SearchResult(browser).get_header_links()
    header_links_len = len(header_links)
    for i in range(min(header_links_len, 5)):
        assert 'tensor.ru' in header_links[i], \
            f"""The tensor.ru is not found \
in the {header_links[i]} search result header link"""


from icecream import ic
from mofid.run_mofid import cif2mofid
import os
import pandas as pd
from pathlib import Path
import sys

# Defining global parameters
root_repo_folder = Path(os.path.realpath(__file__)).parents[2]
dataset_name = 'train'
dataset = pd.read_csv(os.path.join(root_repo_folder, 'data', '{}.csv'.format(dataset_name)))
mofid_table_presort = []

def collect_result(mofid):
    # Callback function (for parallelization later)
    mofid_table_presort.append(mofid)

def one_mof(MOFname):
    # Adjust the mof information to correspond to the round_idx given, and direct round_idx to the CIF file
    mof_name = "{}.cif".format(MOFname)
    ic(mof_name)
    mof_cif = os.path.join(root_repo_folder, 'data', 'mof_cif_{}'.format(dataset_name), mof_name)
    # Call the cif2mofid function as described in github.com/snurr-group/mofid
    mofid = cif2mofid(mof_cif, output_path=os.path.join(root_repo_folder, 'data', 'mofid'))
    return mofid

def main():
    # Load mofid_train_missing.csv
    missing_MOFs = pd.read_csv(os.path.join(root_repo_folder, 'output_cleaned', 'mofid_train_missing.csv'),
                               index_col=0, header=0, names=['MOFname'])
    ic(missing_MOFs)
    missing_MOFs.info()

    # Implement the extraction function
    for MOFname in missing_MOFs['MOFname']:
        collect_result(one_mof(MOFname))

    mofid_table_final = pd.DataFrame(mofid_table_presort).sort_values(by='cifname', ignore_index=True)
    mofid_table_final.to_csv(os.path.join(root_repo_folder, 'data', 'mofid_train_correction.csv'))

if __name__ == '__main__':
    main()


from gym.wrappers.monitoring.video_recorder import VideoRecorder
from stable_baselines3 import PPO

from maze_envirement import MazeEnvironment
from model import train_agent

env = MazeEnvironment()
trained_agent = train_agent(env, total_timesteps=100)

trained_agent.save("trained_maze_agent")
loaded_agent = PPO.load("trained_maze_agent")

obs = env.reset()
done = False

video_recorder = VideoRecorder(env, "video_output.mp4")

if __name__ == "__main__":
    while not done:
        action, _ = loaded_agent.predict(obs)
        obs, reward, done, info = env.step(action)
        env.render()
        video_recorder.capture_frame()

video_recorder.close()
env.close()


# -*- coding: UTF-8 -*-
"""
title: 数组中数字出现的次数
一个整型数组 nums 里除两个数字之外，其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n)，空间复杂度是O(1)。

示例 1：
输入：nums = [4,1,4,6]
输出：[1,6] 或 [6,1]

示例 2：
输入：nums = [1,2,10,4,1,4,3,3]
输出：[2,10] 或 [10,2]

限制：
2 <= nums.length <= 10000
"""
from typing import List

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        """位运算"""
        xor = 0
        for num in nums:
            xor ^= num
        last_1 = xor & -xor
        num_1 = 0
        for num in nums:
            if num & last_1:
                num_1 ^= num
        return [num_1, num_1 ^ xor]

if __name__ == '__main__':
    print(Solution().singleNumbers([4, 1, 4, 6]))


n = int(input())
arr = list(map(int,input().split()))
s = sum(arr)
ch = [0 for i in range(s+1)]

def dfs(i,w):
    ch[w] = 1
    if i >= n:
        return
    dfs(i+1,w)
    dfs(i+1,w+arr[i])
    dfs(i+1,abs(w-arr[i]))

dfs(0,0)
print(ch.count(0))


#
#  Project: MXCuBE
#  https://github.com/mxcube
#
#  This file is part of MXCuBE software.
#
#  MXCuBE is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  MXCuBE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with MXCuBE.  If not, see <http://www.gnu.org/licenses/>.

"""
BeamAlignBrick
"""

from mxcubeqt.utils import icons, qt_import
from mxcubeqt.base_components import BaseWidget

__credits__ = ["MXCuBE collaboration"]
__license__ = "LGPLv3+"
__category__ = "General"

class BeamAlignBrick(BaseWidget):
    def __init__(self, *args):

        BaseWidget.__init__(self, *args)

        # Hardware objects ----------------------------------------------------
        self.beam_align_hwobj = None

        # Internal values -----------------------------------------------------

        # Properties ----------------------------------------------------------
        self.add_property("mnemonic", "string", "")

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        self.group_box = qt_import.QGroupBox("Beam align", self)
        self.align_button = qt_import.QPushButton("Align", self.group_box)

        # Layout --------------------------------------------------------------
        _group_box_vlayout = qt_import.QVBoxLayout(self.group_box)
        _group_box_vlayout.addWidget(self.align_button)
        _group_box_vlayout.addStretch()
        _group_box_vlayout.setSpacing(0)
        _group_box_vlayout.setContentsMargins(0, 0, 0, 0)

        _main_vlayout = qt_import.QVBoxLayout(self)
        _main_vlayout.addWidget(self.group_box)
        _main_vlayout.setSpacing(0)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.align_button.clicked.connect(self.align_beam_clicked)

        # Other ---------------------------------------------------------------

    def property_changed(self, property_name, old_value, new_value):
        if property_name == "mnemonic":
            self.beam_align_hwobj = self.get_hardware_object(new_value)
        else:
            BaseWidget.property_changed(self, property_name, old_value, new_value)

    def align_beam_clicked(self):
        self.beam_align_hwobj.align_beam_test()


class Solution(object):
    def findMinStep(self, board, hand):

        self.res = float("inf")
        self.length = len(hand)
        count = collections.Counter(hand)

        def helper(board, n, count):
            if not board:
                self.res = min(self.res, self.length - n)
                return
            for i, char in enumerate(board):
                if i > 0 and char == board[i - 1]:
                    continue
                j = i
                while j < len(board) and board[j] == char:
                    j += 1
                if j - i >= 3:
                    helper(board[:i] + board[j:], n, count)
                elif j - i == 2 and count[char] > 0:
                    count[char] -= 1
                    helper(board[:i] + board[j:], n - 1, count)
                    count[char] += 1
                elif count[char] > 0:
                    count[char] -= 1
                    helper(board[:i] + char + board[i:], n - 1, count)
                    count[char] += 1

        helper(board, len(hand), count)
        if self.res != float("inf"):
            return self.res
        else:
            return -1

#Runtime: 480 ms
#Your runtime beats 13.64 % of python submissions.


# This is the union runtime testcase. It ensures that values within a
# union embedded within a struct can be set and read correctly.

import unions
import string

# Create new instances of SmallStruct and BigStruct for later use
small = unions.SmallStruct()
small.jill = 200

big = unions.BigStruct()
big.smallstruct = small
big.jack = 300

# Use SmallStruct then BigStruct to setup EmbeddedUnionTest.
# Ensure values in EmbeddedUnionTest are set correctly for each.
eut = unions.EmbeddedUnionTest()

# First check the SmallStruct in EmbeddedUnionTest
eut.number = 1
eut.uni.small = small
Jill1 = eut.uni.small.jill
if (Jill1 != 200):
    raise RuntimeError("Runtime test1 failed. eut.uni.small.jill={}".format(Jill1))

Num1 = eut.number
if (Num1 != 1):
    raise RuntimeError("Runtime test2 failed. eut.number=".format(Num1))

# Secondly check the BigStruct in EmbeddedUnionTest
eut.number = 2
eut.uni.big = big
Jack1 = eut.uni.big.jack
if (Jack1 != 300):
    raise RuntimeError("Runtime test3 failed. eut.uni.big.jack={}".format(Jack1))

Jill2 = eut.uni.big.smallstruct.jill
if (Jill2 != 200):
    raise RuntimeError("Runtime test4 failed. eut.uni.big.smallstruct.jill={}".format(Jill2))

Num2 = eut.number
if (Num2 != 2):
    raise RuntimeError("Runtime test5 failed. eut.number={}".format(Num2))


import os
import numpy as np

import torch

# 데이터 로더를 구현하기
class Dataset(torch.utils.data.Dataset):
    def __init__(self, data_dir, transform=None):
        self.data_dir = data_dir
        self.transform = transform

        lst_data = os.listdir(self.data_dir)

        lst_label = [f for f in lst_data if f.startswith('label')]
        lst_input = [f for f in lst_data if f.startswith('input')]

        lst_label.sort()
        lst_input.sort()

        self.lst_label = lst_label
        self.lst_input = lst_input

    def __len__(self):
        return len(self.lst_label)

    def __getitem__(self, index):
        label = np.load(os.path.join(self.data_dir, self.lst_label[index]))
        input = np.load(os.path.join(self.data_dir, self.lst_input[index]))

        # 정규화
        label = label/255.0
        input = input/255.0

        # 이미지와 레이블의 차원 = 2일 경우(채널이 없을 경우, 흑백 이미지), 새로운 채널(축) 생성
        if label.ndim == 2:
            label = label[:, :, np.newaxis]
        if input.ndim == 2:
            input = input[:, :, np.newaxis]

        data = {'input': input, 'label': label}

        # transform이 정의되어 있다면 transform을 거친 데이터를 불러옴
        if self.transform:
            data = self.transform(data)

        return data

# # 데이터로더 잘 구현되었는지 확인(시각화)
# import matplotlib.pyplot as plt
# dir_data = './datasets'
# dir_save_train = os.path.join(dir_data, 'train')
# files_count = int(len(os.listdir(dir_save_train))/2)

# dataset_train = Dataset(data_dir=dir_save_train)
# data = dataset_train.__getitem__(np.random.randint(files_count))
# input = data['input']
# label = data['label']

# plt.subplot(122)
# plt.imshow(label, cmap='gray')
# plt.title('label')

# plt.subplot(121)
# plt.imshow(input, cmap='gray')
# plt.title('input')

# plt.show()


"This program was adapted by Ruthvik Vaila from code written by Denny Britz "
" See http://www.wildml.com "
#http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-2-implementing-a-language-model-rnn-with-python-numpy-and-theano/
#
import numpy as np
import sys
from datetime import datetime
import matplotlib.pyplot as plt
import pickle
import time
import sys

path = '/home/visionteam/tf_tutorials/ECE_697_Fall2020/data/'
fname = 'data_fd2.pkl'
file_handle = open(path+fname,'rb')
data = pickle.load(file_handle, encoding='latin1')
file_handle.close()

print('data.keys() =  {}'.format(data.keys()))

class RNNNumpy:
    def __init__(self, output_dim, input_dim, hidden_dim=100, bptt_truncate=0):
        # Assign instance variables
        self.output_dim = output_dim
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.bptt_truncate = bptt_truncate
        # Randomly initialize the network parameters
        self.Wx = np.random.uniform(-np.sqrt(1./input_dim), np.sqrt(1./input_dim), (hidden_dim, input_dim))
        self.Wy = np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), (output_dim, hidden_dim))
        self.Wh = np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), (hidden_dim, hidden_dim))
    def forward_propagation(self, x):   # x is X_train[i]
        T = len(x)  # The total number of time steps
        # Save all hidden states h[t] for back prop.
        # One additional row for h[0] = 0
        h = np.zeros((T + 1, self.hidden_dim))  # h.shape = (T+1,nh)
        # Save all outputs for back prop.
        y_hat = np.zeros((T, self.output_dim))   # y_hat.shape = (T,no)
        for t in np.arange(T):
#           # Wx.dot(x[t]).shape = (nh,1)
            # x[t].shape = () is a scalar, Wh.dot(h[t-1]).shape is (nh,)
            h[t] = np.tanh(self.Wx.dot(x[t]).flatten() + self.Wh.dot(h[t-1]))
            y_hat[t] = self.Wy.dot(h[t])
        return [y_hat, h]
    def predict(self, x):  # x is row vector of dimension of T
        # Perform forward propagation and return index of the highest score
        y_hat, h = self.forward_propagation(x)
        return y_hat

    def calculate_total_loss(self, x, y):  # Here x is X_train, y = y_train
        C = 0
        # For each sentence...
        for i in np.arange(len(y)):

            y_hat, h = self.forward_propagation(x[i])
            #print ((y_hat.flatten()-y[i])**2).sum()
            #print(y_hat.shape,len(y[i]))
            error = ((y_hat.flatten()-y[i])**2)/2.0
            #print error.sum(),i
            # Add to the loss based on how off we were
            C +=  np.sum(error)
        #print C
        return C

    def calculate_loss(self, x, y):  #  x is X_train, y is y_train
        # Divide the total loss by the number of training examples
        #N = np.sum((len(y_i) for y_i in y))
        N = y.size
        return self.calculate_total_loss(x,y)/N

    def update_loss(self, x, y):  # Here x is X_train[i], y = y_train[i]
        Cbptt = 0
        y_hat, h = self.forward_propagation(x)
        error = (1/2)*(y_hat-y)**2
        Cbptt =  np.sum(error)
        return Cbptt

    def bptt(self, x, y):  # Here x = X_train[i], y = y_train[i]
        T = len(y)
        # Perform forward propagation  y_hat.shape = (T,nI), h.shape=(T+1,nh)
        y_hat, h = self.forward_propagation(x)
        # We accumulate the gradients in these variables
        dCdWx = np.zeros(self.Wx.shape)
        dCdWy = np.zeros(self.Wy.shape)
        dCdWh = np.zeros(self.Wh.shape)
        # y.shape = (T,) while y_hat.shape = (T,nI)
        y_hat = y_hat.flatten() # y_hat now has shape (T,)
        dCdy = -1*(y-y_hat)   #  dCdy.shape = (T,)
        # For each output backwards...
        for t in np.arange(T)[::-1]:
            dCdWy += np.outer(dCdy[t], h[t].T)
            # Initial dCdz_t calculation
            dCdz_t = self.Wy.T.dot(dCdy[t]) * (1 - (h[t] ** 2).reshape(self.hidden_dim,1))
            # Backpropagation through time (for at most self.bptt_truncate steps)
            for bptt_step in np.arange(max(0, t-self.bptt_truncate), t+1)[::-1]:
                #print "Backpropagation step t=%d bptt step=%d " % (t, bptt_step)
                dCdWh += np.outer(dCdz_t, h[bptt_step-1])
                #dCdWx[:,x[bptt_step]] += dCdz_t
                #dCdWx += dCdz_t
                dCdWx += np.outer(dCdz_t, x[bptt_step])
                # Update dCdz_t for next step
                dCdz_t = self.Wh.T.dot(dCdz_t) * (1 - h[bptt_step-1] ** 2).reshape(self.hidden_dim,1)
        return [dCdWx, dCdWy, dCdWh]

    def numpy_sdg_step(self, x, y, learning_rate): # Here x is X_train[i] and y = y_train[i]
        # Calculate the gradients
        dCdWx, dCdWy, dCdWh = self.bptt(x, y)
        # Change parameters according to gradients and learning rate
        self.Wx -= learning_rate * dCdWx
        self.Wy -= learning_rate * dCdWy
        self.Wh -= learning_rate * dCdWh

# Outer SGD Loop
# - model: The RNN model instance
# - X_train: The training data set
# - y_train: The training data labels
# - learning_rate: Initial learning rate for SGD
# - nepoch: Number of times to iterate through the complete dataset
# - evaluate_loss_after: Evaluate the loss after this many epochs
def train_with_sgd(model, X_train, y_train, learning_rate=0.005, nepoch=100, evaluate_loss_after=5):
    # We keep track of the losses so we can plot them later
    losses = []
    num_examples_seen = 0
    for epoch in range(nepoch):
    # Optionally evaluate the loss
        if (epoch % evaluate_loss_after == 0):
            loss = model.calculate_loss(X_train, y_train)
            losses.append((num_examples_seen, loss))
#            time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#            print "%s: Loss after num_examples_seen=%d epoch=%d: %f" % (time, num_examples_seen, epoch, loss)
            print("Loss after num_examples_seen=%d epoch=%d: %f" % (num_examples_seen, epoch, loss))
            # Adjust the learning rate if loss increases
            if (len(losses) > 1 and losses[-1][1] > losses[-2][1]):
                learning_rate = learning_rate * 0.5
                print("Setting learning rate to %f" % learning_rate)
            sys.stdout.flush()
        # For each training example...
        for i in range(len(y_train)):
            # One SGD step
            model.numpy_sdg_step(X_train[i], y_train[i], learning_rate)
            num_examples_seen += 1

#np.random.seed(10)
model = RNNNumpy(output_dim=1, input_dim=1, hidden_dim=10, bptt_truncate=10)
X_train = data['X_train']
y_train = data['y_train']
print('Shape of the data:{}'.format(X_train.shape))
losses = train_with_sgd(model, X_train, y_train, nepoch=5, evaluate_loss_after=1)
y_hat, h = model.forward_propagation(X_train[10])
#print(y_hat)
#print(X_train[10])
Wh = model.Wh
#print('Wh=\n {}'.format(Wh))

plt.plot(range(X_train.shape[-1]),X_train[10],label='$x(t)$')
plt.plot(range(X_train.shape[-1]),y_hat,label='$\hat{y}(t)$')
plt.plot(range(X_train.shape[-1]),y_train[10],label='$y(t)$')
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.legend(prop={'size': 14})
plt.suptitle('$\\ RNN \\ to \\ transform \\ \\sin(t) \\ to \\ sin(2t) $',fontsize=22)
plt.savefig('sinusoid1.png')
plt.show()

error = y_hat - y_train[10].reshape(X_train.shape[-1],1)
#plt.plot(range(31),X_train[10],label='$x(t)$')
plt.plot(range(X_train.shape[-1]),error,label='$y(t) - \hat{y}(t)$')
#plt.plot(range(31),y_train[10],label='$y(t)$')
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.legend(prop={'size': 14})
plt.suptitle('error(t) = $y(t) - \hat{y}(t)$',fontsize=22)
plt.savefig('sinusoid1.png')
plt.show()

#plt.plot(range(31),X_train[10],label='$x(t)$')
#plt.plot(range(31),y_hat,label='$y(t)$')
#plt.plot(range(31),y_train[10],label='$d(t)$')
#plt.xticks(fontsize=15)
#plt.yticks(fontsize=15)
#plt.legend(prop={'size': 14})
#plt.suptitle('$\\ RNN \\ to \\ transform \\ \\sin(t) \\ to \\ sin(2t) $',fontsize=22)
#plt.savefig('sinusoid2.png')


from pulumi import Output
from pulumi.resource import ResourceOptions
from pulumi_azure import monitoring
from pulumi_azure_native import insights

def _log_diagnostic_settings(
    log_analytics_workspace_id,
    resource_id,
    resource_name,
    log_config_obj,
    metrics_config_obj,
):

    # Instead of None, empty dictionary
    log_config_obj = log_config_obj or {}
    metrics_config_obj = metrics_config_obj or {}

    # Determine if we need to find what all the categories are
    if (
        log_config_obj.get("categories") is None
        or metrics_config_obj.get("categories") is None
    ):
        all_categories = monitoring.get_diagnostic_categories(resource_id=resource_id)
    else:
        all_categories = None

    # Set the categories if specified, all if not
    # Also set the setting name
    setting_name_log, setting_name_metric = "All", "All"
    if log_config_obj.get("categories") is None:
        log_categories = all_categories.logs
    else:
        log_categories = log_config_obj.get("categories")
        setting_name_log = "Configured"
    if metrics_config_obj.get("categories") is None:
        metric_categories = all_categories.metrics
    else:
        metric_categories = metrics_config_obj.get("categories")
        setting_name_metric = "Configured"

    # Change the categories from strings to objects
    if log_config_obj.get("enabled", True):
        log_objects = [
            insights.LogSettingsArgs(
                category=log,
                enabled=True,
                retention_policy=insights.RetentionPolicyArgs(
                    days=0,
                    enabled=False,
                ),
            )
            for log in sorted(log_categories)
        ]
    else:
        log_objects = []

    # Change the categories from strings to objects
    if metrics_config_obj.get("enabled", True):
        metric_objects = [
            insights.MetricSettingsArgs(
                category=metric,
                enabled=True,
                retention_policy=insights.RetentionPolicyArgs(
                    days=0,
                    enabled=False,
                ),
            )
            for metric in sorted(metric_categories)
        ]
    else:
        metric_objects = []

    insights.DiagnosticSetting(
        f"{resource_name}-diagnostic-setting",
        name=f"{setting_name_log} Logs, {setting_name_metric} Metrics",
        workspace_id=log_analytics_workspace_id,
        log_analytics_destination_type="Dedicated",
        resource_uri=resource_id,
        logs=log_objects,
        metrics=metric_objects,
        opts=ResourceOptions(ignore_changes=["log_analytics_destination_type"]),
    )

def log_diagnostic_settings(
    platform_config,
    log_analytics_workspace_id,
    resource_type,
    resource_id,
    resource_name,
    logs_config={},
    metrics_config={},
):

    # If any of these three are set, we will add the diagnostics
    # If the resource type is disabled, then the individual object must be
    # explicitly enabled
    if not any(
        [
            platform_config["logs"]["resource_types"].get(resource_type, True),
            logs_config.get("enabled", False),
            metrics_config.get("enabled", False),
        ]
    ):
        return

    # If logs and metrics both disabled, don't go any further
    if not logs_config.get("enabled", True) and not metrics_config.get("enabled", True):
        return

    if isinstance(resource_id, Output):
        resource_id.apply(lambda r_id:
            _log_diagnostic_settings(
                log_analytics_workspace_id, r_id, resource_name,
                logs_config, metrics_config)
        )
    else:
        _log_diagnostic_settings(
            log_analytics_workspace_id, resource_id, resource_name,
            logs_config, metrics_config)

def log_network_interfaces(
    platform_config,
    log_analytics_workspace_id,
    resource_name,
    network_interfaces,
    logs_config={},
    metrics_config={},
):
    network_interfaces.apply(
        lambda network_interfaces: [
            log_diagnostic_settings(
                platform_config,
                log_analytics_workspace_id,
                "Microsoft.Network/networkInterfaces",
                network_interface.id,
                f"{resource_name}-network_interface-{str(idx)}",
                logs_config=logs_config,
                metrics_config=metrics_config,
            )
            for idx, network_interface in enumerate(network_interfaces)
        ]
    )


from django import forms

from TodoApp.Todo.models import Todo
from TodoApp.users.forms import BootsTrapMixin

class CreateTodoForm(BootsTrapMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['description'].widget.attrs.update({
            'rows': 3,
        })

    class Meta:
        model = Todo
        fields = ['title', 'description']