'''
Implemente uma função que calcula um dos caminhos mais curtos para atravessar
um labirinto. O mapa do labirinto é quadrado e representado por uma lista
de strings, onde um ' ' representa um espaço vazio e um '#' um obstáculo.
O ponto de entrada é o canto superior esquerdo e o ponto de saída o canto
inferior direito. A função deve devolver uma string com as instruções para
atravesar o labirinto. As instruções podem ser 'N','S','E','O'.
'''

def build(arestas):
    adj = {}
    for o,d in arestas:
        if o not in adj:
            adj[o] = set()
        if d not in adj:
            adj[d] = set()
        adj[o].add(d)
        adj[d].add(o)
    return adj

def bfs(adj,o):
    pai = {}
    vis = {o}
    queue = [o]
    while queue:
        v = queue.pop(0)
        for d in adj[v]:
            if d not in vis:
                vis.add(d)
                pai[d] = v
                queue.append(d)
    return pai

def shortest(adj,o,d):
    pai = bfs(adj,o)
    caminho = [d]
    while d in pai:
        d = pai[d]
        caminho.insert(0,d)
    return caminho

def setupEdges(mapa):
    edges = []
    for l in range(len(mapa)):
        for c in range(len(mapa[l])):
            if mapa[l][c] == " ":
                if l-1 >= 0:
                    if mapa[l-1][c] == " " : edges.append(((l,c),(l-1,c)))
                if l+1 < len(mapa):
                    if mapa[l+1][c] == " " : edges.append(((l,c),(l+1,c)))
                if c-1 >= 0:
                    if mapa[l][c-1] == " " : edges.append(((l,c),(l,c-1)))
                if c+1 < len(mapa[l]):
                    if mapa[l][c+1] == " " : edges.append(((l,c),(l,c+1)))
    return edges

def caminho(mapa):

    edges = setupEdges(mapa)
    graph = build(edges)
    path = shortest(graph,(0,0),(len(mapa)-1,len(mapa[len(mapa)-1])-1))
    res = ""
    for i in range(1,len(path)):
        if path[i-1][0] < path[i][0] : res += "S"
        if path[i-1][0] > path[i][0] : res += "N"
        if path[i-1][1] < path[i][1] : res += "E"
        if path[i-1][1] > path[i][1] : res += "O"

    print(path)
    return res

def main():
    print("
caminho
")
    mapa = ["  ########",
            "# # #    #",
            "# # #### #",
            "# #      #",
            "# # # ####",
            "# # #    #",
            "#   # #  #",
            "##### ####",
            "#        #",
            "########  "]
    print("in:")
    print('\n'.join(mapa))
    print("out:",caminho(mapa))

if __name__ == '__main__':
    main()


import argparse
import math
import struct
import sys
import time
import warnings
import os
import numpy as np
from multiprocessing import Pool, Value, Array

class VocabItem:
    def __init__(self, word):
        self.word = word
        self.count = 0

class Vocab:
    def __init__(self, min_count):
        vocab_items = []
        vocab_hash = {}
        word_count = 0
        TRAIN_PATH = os.path.join('Train_Test_Set', 'train.txt')
        fi = open(TRAIN_PATH, 'r')

        # Add special tokens <bol> (beginning of line) and <eol> (end of line)
        for token in ['<bol>', '<eol>']:
            vocab_hash[token] = len(vocab_items)
            vocab_items.append(VocabItem(token))

        for line in fi:
            tokens = line.split()
            for token in tokens:
                if token not in vocab_hash:
                    vocab_hash[token] = len(vocab_items)
                    vocab_items.append(VocabItem(token))

                # assert vocab_items[vocab_hash[token]].word == token, 'Wrong vocab_hash index'
                vocab_items[vocab_hash[token]].count += 1
                word_count += 1

                if word_count % 10000 == 0:
                    sys.stdout.write("\rReading word %d" % word_count)
                    sys.stdout.flush()

            # Add special tokens <bol> (beginning of line) and <eol> (end of line)
            vocab_items[vocab_hash['<bol>']].count += 1
            vocab_items[vocab_hash['<eol>']].count += 1
            word_count += 2

        self.bytes = fi.tell()
        self.vocab_items = vocab_items  # List of VocabItem objects
        self.vocab_hash = vocab_hash  # Mapping from each token to its index in vocab
        self.word_count = word_count  # Total number of words in train file

        # Add special token <unk> (unknown),
        # merge words occurring less than min_count into <unk>, and
        # sort vocab in descending order by frequency in train file
        self.__sort(min_count)

        # assert self.word_count == sum([t.count for t in self.vocab_items]), 'word_count and sum of t.count do not agree'
        print('Total words in training file: %d' % self.word_count)
        print('Total bytes in training file: %d' % self.bytes)
        print('Vocab size: %d' % len(self))

    def __getitem__(self, i):
        return self.vocab_items[i]

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

    def __iter__(self):
        return iter(self.vocab_items)

    def __contains__(self, key):
        return key in self.vocab_hash

    def __sort(self, min_count):
        tmp = []
        tmp.append(VocabItem('<unk>'))
        unk_hash = 0

        count_unk = 0
        for token in self.vocab_items:
            if token.count < min_count:
                count_unk += 1
                tmp[unk_hash].count += token.count
            else:
                tmp.append(token)

        tmp.sort(key=lambda token: token.count, reverse=True)

        # Update vocab_hash
        vocab_hash = {}
        for i, token in enumerate(tmp):
            vocab_hash[token.word] = i

        self.vocab_items = tmp
        self.vocab_hash = vocab_hash

        print()
        print('Unknown vocab size:', count_unk)

    def indices(self, tokens):
        return [self.vocab_hash[token] if token in self else self.vocab_hash['<unk>'] for token in tokens]

class UnigramTable:
    """
    A list of indices of tokens in the vocab following a power law distribution,
    used to draw negative samples.
    """

    def __init__(self, vocab):
        vocab_size = len(vocab)
        power = 0.75
        norm = sum([math.pow(t.count, power) for t in vocab])  # Normalizing constant

        table_size = int(1e8)  # Length of the unigram table
        table = np.zeros(table_size, dtype=np.uint32)

        print('Filling unigram table')
        p = 0  # Cumulative probability
        i = 0
        for j, unigram in enumerate(vocab):
            p += float(math.pow(unigram.count, power)) / norm
            while i < table_size and float(i) / table_size < p:
                table[i] = j
                i += 1
        self.table = table

    def sample(self, count):
        indices = np.random.randint(low=0, high=len(self.table), size=count)
        return [self.table[i] for i in indices]

def sigmoid(z):
    if z > 6:
        return 1.0
    elif z < -6:
        return 0.0
    else:
        return 1 / (1 + math.exp(-z))

def init_net(dim, vocab_size):
    # Init syn0 with random numbers from a uniform distribution on the interval [-0.5, 0.5]/dim
    tmp = np.random.uniform(low=-0.5 / dim, high=0.5 / dim, size=(vocab_size, dim))
    syn0 = np.ctypeslib.as_ctypes(tmp)
    syn0 = Array(syn0._type_, syn0, lock=False)

    # Init syn1 with zeros
    tmp = np.zeros(shape=(vocab_size, dim))
    syn1 = np.ctypeslib.as_ctypes(tmp)
    syn1 = Array(syn1._type_, syn1, lock=False)

    return (syn0, syn1)

def train_process(pid):
    # Set fi to point to the right chunk of training file
    start = vocab.bytes / num_processes * pid
    end = vocab.bytes if pid == num_processes - 1 else vocab.bytes / num_processes * (pid + 1)
    fi.seek(start)
    # print 'Worker %d beginning training at %d, ending at %d' % (pid, start, end)

    alpha = starting_alpha

    word_count = 0
    last_word_count = 0

    while fi.tell() < end:
        line = fi.readline().strip()
        # Skip blank lines
        if not line:
            continue

        # Init sent, a list of indices of words in line
        sent = vocab.indices(['<bol>'] + line.split() + ['<eol>'])

        for sent_pos, token in enumerate(sent):
            if word_count % 10000 == 0:
                global_word_count.value += (word_count - last_word_count)
                last_word_count = word_count

                # Recalculate alpha
                alpha = starting_alpha * (1 - float(global_word_count.value) / vocab.word_count)
                if alpha < starting_alpha * 0.0001: alpha = starting_alpha * 0.0001

                # Print progress info
                sys.stdout.write("\rAlpha: %f Progress: %d of %d (%.2f%%)" %
                                 (alpha, global_word_count.value, vocab.word_count,
                                  float(global_word_count.value) / vocab.word_count * 100))
                sys.stdout.flush()

            # Randomize window size, where win is the max window size
            current_win = np.random.randint(low=1, high=win + 1)
            context_start = max(sent_pos - current_win, 0)
            context_end = min(sent_pos + current_win + 1, len(sent))
            context = sent[context_start:sent_pos] + sent[sent_pos + 1:context_end]  # Turn into an iterator?

            # Skip-gram
            for context_word in context:
                # Init neu1e with zeros
                neu1e = np.zeros(dim)

                # Compute neu1e and update syn1
                classifiers = [(token, 1)] + [(target, 0) for target in table.sample(neg)]
                for target, label in classifiers:
                    z = np.dot(syn0[context_word], syn1[target])
                    p = sigmoid(z)
                    g = alpha * (label - p)
                    neu1e += g * syn1[target]  # Error to backpropagate to syn0
                    syn1[target] += g * syn0[context_word]  # Update syn1

                # Update syn0
                syn0[context_word] += neu1e
            word_count += 1

    # Print progress info
    global_word_count.value += (word_count - last_word_count)
    sys.stdout.write("\rAlpha: %f Progress: %d of %d (%.2f%%)" %
                     (alpha, global_word_count.value, vocab.word_count,
                      float(global_word_count.value) / vocab.word_count * 100))
    sys.stdout.flush()
    fi.close()

def save(vocab, syn0, fo, binary):
    print('Saving model to', fo)
    dim = len(syn0[0])
    fo = open(fo, 'w')
    fo.write('%d %d\n' % (len(syn0), dim))
    for token, vector in zip(vocab, syn0):
        word = token.word
        vector_str = ' '.join([str(s) for s in vector])
        fo.write('%s %s\n' % (word, vector_str))
    fo.close()

def __init_process(*args):
    global vocab, syn0, syn1, table, cbow, neg, dim, starting_alpha
    global win, num_processes, global_word_count, fi

    vocab, syn0_tmp, syn1_tmp, table, cbow, neg, dim, starting_alpha, win, num_processes, global_word_count = args[:-1]
    fi = open(args[-1], 'r')
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', RuntimeWarning)
        syn0 = np.ctypeslib.as_array(syn0_tmp)
        syn1 = np.ctypeslib.as_array(syn1_tmp)

def train(fi, fo, cbow, neg, dim, alpha, win, min_count, num_processes, binary):
    # Read train file to init vocab
    vocab = Vocab(min_count)

    # Init net
    syn0, syn1 = init_net(dim, len(vocab))

    global_word_count = Value('i', 0)
    table = None

    print('Initializing unigram table')
    table = UnigramTable(vocab)
    # Begin training using num_processes workers
    t0 = time.time()

    pool = Pool(processes=num_processes, initializer=__init_process,
                initargs=(vocab, syn0, syn1, table, cbow, neg, dim, alpha,
                          win, num_processes, global_word_count, fi))
    pool.map(train_process, range(num_processes))

    t1 = time.time()
    print()
    print('Completed training. Training took', (t1 - t0) / 60, 'minutes')

    # Save model to file
    save(vocab, syn0, fo, binary)

if __name__ == '__main__':

    TRAIN_FILE_PATH = os.path.join('.', 'Train_Test_Set', 'train.txt')
    MODEL_SAVE_PATH = os.path.join('my_model_implemention')
    train(TRAIN_FILE_PATH, MODEL_SAVE_PATH, 0, 5, 100, 0.025, 5, 5, 4, 0)


from PyQt5 import QtWidgets
from tkinter import Tk, Label
import time

#возвращает массив из 8 элементов, где каждый элемент - это 32 бита
def genKeys_GOST(key256b:str):
    keys1 = key256b.encode()
    keys = []
    for i in range(8):
        keys.append(keys1[:4])
        keys1 = keys1[4:]
    keysBin = []
    for i in range(len(keys)):
        binStr = ''
        for j in keys[i]:
            binStr += bin(j)[2:].zfill(8)
        keysBin.append(binStr)
    return keysBin

def before_coding(text, flag: int):
    file = 0
    if type(text) == str:
        if flag == 1:
            textToInt = text.encode()
        else:
            textToInt = b''
            for i in text:
                textToInt += bytes([ord(i)])
    else:
        textToInt = text
        file = 1
        print('OK')

    blocks = []
    while len(textToInt) > 0:
        blocks.append(textToInt[:8])
        textToInt = textToInt[8:]

    count = 0
    if len(blocks[len(blocks) - 1]) != 8:
        while len(blocks[len(blocks) - 1]) != 8:
            count += 1
            blocks[len(blocks) - 1] += bytes([0])
        blocks[len(blocks) - 1] = blocks[len(blocks) - 1][:-1] + bytes([count])

    blocksBin = []
    for i in range(len(blocks)):
        binStr = ''
        for j in blocks[i]:
            binStr += bin(j)[2:].zfill(8)
        blocksBin.append(binStr)
    return blocksBin, file

def after_coding(file, block64Int, flag):
    if file == 0:
        if flag != 1:
            numb = block64Int[len(block64Int) - 1]
            blocksText1 = block64Int
            j = 2
            for i in range(numb-1):
                if blocksText1[-j] == 0:
                    blocksText1 = blocksText1[:-1]
                    j = 1
                else:
                    break
            if len(blocksText1) < len(block64Int):
                blocksText1 = blocksText1[:-1]
            blocksText = ''
            for i in blocksText1:
                blocksText += chr(i)
        else:
            blocksText = ''
            for i in block64Int:
                blocksText += chr(i)
    else:
        if flag != 1:
            numb = block64Int[len(block64Int) - 1]
            blocksText = block64Int
            j = 2
            for i in range(numb-1):
                if blocksText[-j] == 0:
                    blocksText = blocksText[:-1]
                    j = 1
                else:
                    break
            if len(blocksText) < len(block64Int):
                blocksText = blocksText[:-1]
        else:
            blocksText = block64Int
    return blocksText

def xor(a: str, b: str):
    if len(a) > len(b):
        a = a.zfill(len(b))
    elif len(b) > len(a):
        b = b.zfill(len(a))
    res = bin(int(a, 2) ^ int(b, 2))[2:].zfill(len(a))
    return res

def sdvig(str: str, n: int):
    arrTxt = str[n:] + str[:n]
    return arrTxt

def substitution(N1:str):
    __Sbox = [
        [9, 6, 3, 2, 8, 11, 1, 7, 10, 4, 14, 15, 12, 0, 13, 5],
        [3, 7, 14, 9, 8, 10, 15, 0, 5, 2, 6, 12, 11, 4, 13, 1],
        [14, 4, 6, 2, 11, 3, 13, 8, 12, 15, 5, 10, 0, 7, 1, 9],
        [14, 7, 10, 12, 13, 1, 3, 9, 0, 2, 11, 4, 15, 8, 5, 6],
        [11, 5, 1, 9, 8, 13, 15, 0, 14, 4, 2, 3, 12, 7, 10, 6],
        [3, 10, 13, 12, 1, 2, 0, 11, 7, 5, 9, 4, 8, 15, 14, 6],
        [1, 13, 2, 9, 7, 10, 6, 0, 8, 12, 4, 5, 15, 3, 11, 14],
        [11, 10, 15, 5, 0, 12, 14, 8, 6, 2, 3, 9, 1, 7, 13, 4]
    ]
    # 8 блоков по 4 бита
    blocks4b = []
    for i in range(8):
        blocks4b.append(N1[:4])
        N1 = N1[4:].zfill(4)
    blocksAfterSbox = ''
    for i in range(8):
        blocksAfterSbox+=bin(__Sbox[i][int(blocks4b[i], 2)])[2:].zfill(4)
    return sdvig(blocksAfterSbox, 11)

def round_feistel_scheme(L0: str, R0: str, key: str):
    # RES = (N1 + Ki) mod 2 ^ 32
    RES = bin((int(L0, 2) | int(key, 2)) % 2**32)[2:].zfill(32)

    # RES = RES -> Sbox, << 11
    RES = substitution(RES)
    L0, R0 = xor(RES, R0), L0
    return L0, R0

def feistel_scheme(block:str, keys:list, flag:int):
    L0 = block[:32]
    R0 = block[32:]
    if flag == 1:
        # K0, K1, K2, K3, K4, K5, K6, K7, K0, K1, K2, K3, K4, K5, K6, K7, K0, K1, K2, K3, K4, K5, K6, K7
        for i in range(3):
            for j in range(len(keys)):
                L0, R0 = round_feistel_scheme(L0, R0, keys[j])
        # K7, K6, K5, K4, K3, K2, K1, K0
        for i in range(len(keys)):
            L0, R0 = round_feistel_scheme(L0, R0,  keys[len(keys) - 1 - i])
        L0, R0 = R0, L0
    else:
        # K0, K1, K2, K3, K4, K5, K6, K7
        for i in range(len(keys)):
            L0, R0 = round_feistel_scheme(L0, R0, keys[i])
        # K7, K6, K5, K4, K3, K2, K1, K0, K7, K6, K5, K4, K3, K2, K1, K0, K7, K6, K5, K4, K3, K2, K1, K0
        for i in range(3):
            for j in range(len(keys)):
                L0, R0 = round_feistel_scheme(L0, R0, keys[len(keys) - 1 - j])
        L0, R0 = R0, L0
    return L0 + R0

def GOST_zamena(keys1, text, flag):
    start = time.time()
    if not keys1 or keys1 == '':
        keys = genKeys_GOST('this_is_a_pasw_for_GOST_28147_89')
    else:
        if len(keys1) != 256:
            msgBox = QtWidgets.QMessageBox()
            msgBox.setWindowTitle("Ошибка")
            msgBox.setText("Ошибка в ключе!")
            msgBox.exec_()
            return ("")
        for i in keys1:
            if (i != '1' and i != 1 and i != '0' and i != 0) == True:
                msgBox = QtWidgets.QMessageBox()
                msgBox.setWindowTitle("Ошибка")
                msgBox.setText("Ошибка в ключе!")
                msgBox.exec_()
                return ("")
        keys = [0, 0, 0, 0, 0, 0, 0, 0]
        for i in range(8):
            keys[i] = keys1[:32]
            keys1 = keys1[32:]

    if not text:
        msgBox = QtWidgets.QMessageBox()
        msgBox.setWindowTitle("Ошибка")
        msgBox.setText("Введите текст!")
        msgBox.exec_()
        return ("")

    blocksBin, file = before_coding(text, flag)

    block64Int = b''
    for i in range(len(blocksBin)):
        block64b = feistel_scheme(blocksBin[i], keys, flag)
        for j in range(8):
            block64Int+=bytes([int(block64b[:8], 2)])
            block64b = block64b[8:]

    blocksText = after_coding(file, block64Int, flag)
    return blocksText

def GOST_gamm(keys1, text, flag, vector_init):
    start = time.time()
    if not keys1 or keys1 == '':
        keys = genKeys_GOST('this_is_a_pasw_for_GOST_28147_89')
    else:
        if len(keys1) != 256:
            msgBox = QtWidgets.QMessageBox()
            msgBox.setWindowTitle("Ошибка")
            msgBox.setText("Ошибка в ключе!")
            msgBox.exec_()
            return ("")
        for i in keys1:
            if (i != '1' and i != 1 and i != '0' and i != 0) == True:
                msgBox = QtWidgets.QMessageBox()
                msgBox.setWindowTitle("Ошибка")
                msgBox.setText("Ошибка в ключе!")
                msgBox.exec_()
                return ("")
        keys = [0, 0, 0, 0, 0, 0, 0, 0]
        for i in range(8):
            keys[i] = keys1[:32]
            keys1 = keys1[32:]
    if not vector_init or vector_init == '':
        vector_init = '1110011110010101110010111001010010000111001010011100101001001011'
    else:
        if len(vector_init) != 64:
            msgBox = QtWidgets.QMessageBox()
            msgBox.setWindowTitle("Ошибка")
            msgBox.setText("Ошибка в векторе инициализации!")
            msgBox.exec_()
            return ("")
        for i in vector_init:
            if (i != '1' and i != 1 and i != '0' and i != 0) == True:
                msgBox = QtWidgets.QMessageBox()
                msgBox.setWindowTitle("Ошибка")
                msgBox.setText("Ошибка в векторе инициализации!!")
                msgBox.exec_()
                return ("")
    if not text:
        msgBox = QtWidgets.QMessageBox()
        msgBox.setWindowTitle("Ошибка")
        msgBox.setText("Введите текст!")
        msgBox.exec_()
        return ("")

    blocksBin, file = before_coding(text, flag)

    percent = 100 / len(blocksBin)
    progress = 0
    normal = 0
    root = Tk()

    label = Label(text='Progressbar')
    x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
    y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
    root.wm_geometry("+%d+%d" % (x, y))
    label.pack()

    if flag == 1:
        N = vector_init
        block64Int = b''
        for i in range(len(blocksBin)):
            gamma = feistel_scheme(N, keys, 1)
            try:
                progress += percent
                label.config(text='\rОбработка завершена на %3d%%' % progress)
                root.update()
                # print('\rОбработка завершена на %3d%%' % progress, end = '', flush = True)
            except Exception:
                normal = 1
                pass
            block64b = xor(gamma, blocksBin[i])
            N = block64b
            for j in range(8):
                block64Int += bytes([int(block64b[:8], 2)])
                block64b = block64b[8:]
    else:
        N = vector_init
        block64Int = b''
        for i in range(len(blocksBin)):
            gamma = feistel_scheme(N, keys, 1)
            try:
                progress += percent
                label.config(text='\rОбработка завершена на %3d%%' % progress)
                root.update()
                # print('\rОбработка завершена на %3d%%' % progress, end = '', flush = True)
                time.sleep(0.01)
            except Exception:
                normal = 1
                pass
            block64b = xor(gamma, blocksBin[i])
            for j in range(8):
                block64Int += bytes([int(block64b[:8], 2)])
                block64b = block64b[8:]
            N = blocksBin[i]

    blocksText = after_coding(file, block64Int, flag)
    if normal == 0:
        root.destroy()
    print('Время выполнения: ', (time.time() - start) / 60)
    return blocksText


def create_album(group_id,title):
    import requests
    from config import token
    resp = requests.get(f'https://api.vk.com/method/photos.createAlbum?title={title}&group_id={group_id}&access_token={token}&v=5.131')
    return (resp.json())

def photos_getAlbums(group_id):
    import requests
    from config import token

    res = f'https://api.vk.com/method/photos.getAlbums?owner_id=-{group_id}&access_token={token}&v=5.131'
    respos = requests.get(res)
    return (respos.json())

# photos_getAlbums(214298287)
def photos_get(group_id,album_id):
    from  config import token
    import requests
    resk = f'https://api.vk.com/method/photos.get?owner_id=-{group_id}&album_id={album_id}&access_token={token}&v=5.131'
    x_yi = requests.get(resk)
    return x_yi.json()

def photos_uploadServer(group_id,album_id):
    from config import token
    import requests
    getser = f'https://api.vk.com/method/photos.getUploadServer?group_id={group_id}&album_id={album_id}&access_token={token}&v=5.131'
    rest = requests.get(getser)
    return rest.json()

def save_photo_vk(lotID, groupID, albumID):
    import os
    import requests
    from config import token
    print('photos_uploadServer',photos_uploadServer(groupID, albumID))
    upload_url = (photos_uploadServer(groupID, albumID))['response']['upload_url']
    print(upload_url)
    direc = os.listdir(f'new/{lotID}/')
    print(direc)
    for pict in direc:
        file = {'file1': open(f'new/{lotID}/{pict}', 'rb')}
        ur = requests.post(upload_url, files=file).json()
        result = requests.get(f'https://api.vk.com/method/photos.save', params={'access_token': token,
                                                                                'album_id': ur['aid'],
                                                                                'group_id': ur['gid'],
                                                                                'server': ur['server'],
                                                                                'photos_list': ur[
                                                                                'photos_list'],
                                                                                'hash': ur['hash'],
                                                                                'caption': pict,
                                                                                'v': '5.131'}).json()
        print(result)


from pyapacheatlas.core.entity import AtlasEntity, AtlasUnInit
from pyapacheatlas.core import AtlasClassification

def test_getters_setters():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)

    assert(ae.attributes["name"] == "a")
    assert(ae.attributes["qualifiedName"] == "c")

    assert(ae.name == "a")
    assert(ae.qualifiedName == "c")

    ae.name = "x"
    ae.qualifiedName = "y"

    assert(ae.attributes["name"] == "x")
    assert(ae.attributes["qualifiedName"] == "y")

def test_set_guid():
    r = AtlasEntity(name="x", typeName="y", qualified_name="z", guid=-2)

    assert(r.guid == -2)
    assert(r.to_json(minimum=True)["guid"] == -2)

def test_add_relationshipAttributes():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)
    r = AtlasEntity(name="x", typeName="y", qualified_name="z", guid=-2)
    r2 = AtlasEntity(name="x2", typeName="y2", qualified_name="z2", guid=-3)
    r3 = AtlasEntity(name="x3", typeName="y3", qualified_name="z3", guid=-4)

    ae.addRelationship(test=r, test2=r2)

    # Add an update manually to make sure I'm not breaking anything
    ae.relationshipAttributes.update({"test3": r3.to_json(minimum=True)})

    assert(len(ae.relationshipAttributes) == 3)
    assert(all([isinstance(d, dict)
                for d in ae.relationshipAttributes.values()]))

    # Each should have the three minimum attributes
    req_keys = set(["guid", "qualifiedName", "typeName"])
    assert(all([(len(d) == 3 and set(d.keys()) == req_keys)
                for d in ae.relationshipAttributes.values()]))

def test_explicit_add_nulls():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1, customAttributes=None)
    assert(ae.customAttributes is None)
    assert(ae.relationshipAttributes is not None)

def test_add_classifications():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)
    ae.addClassification("a","b", AtlasClassification("c"))
    assert(ae.classifications)

    expected = [AtlasClassification("a").to_json(), AtlasClassification("b").to_json(),
    AtlasClassification("c").to_json()
    ]

    assert(ae.classifications == expected)

def test_add_classifications_transaction():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)
    # Confirm that it will keep the initial state as uninitialized
    try:
        ae.addClassification("a","b", 123, AtlasClassification("c"))
    except Exception as e:
        pass
    assert(isinstance(ae.classifications, AtlasUnInit))

    # Now confirm that it will keep the initial state
    ae.addClassification("a")
    try:
        ae.addClassification(123)
    except:
        pass
    assert(ae.classifications == [AtlasClassification("a").to_json()])

def test_add_customAttribute():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)
    ae.addCustomAttribute(custom1="blah")
    assert(ae.customAttributes)
    assert(ae.customAttributes == {"custom1":"blah"})

def test_add_businessAttribute():
    ae = AtlasEntity(name="a", typeName="b", qualified_name="c", guid=-1)
    ae.addBusinessAttribute(biz1={"prop1":"abc"})
    assert(ae.businessAttributes)
    assert(ae.businessAttributes == {"biz1":{"prop1":"abc"}})

def test_entity_from_json():
    input_entity = {
      "typeName": "DataSet",
      "attributes": {
        "owner": None,
        "replicatedTo": None,
        "replicatedFrom": None,
        "qualifiedName": "testEntity",
        "name": "testEntity",
        "description": None
      },
      "guid": "f3a2390d-f300-487e-8756-b27767e540f0",
      "status": "ACTIVE",
      "relationshipAttributes": {
        "schema": [],
        "inputToProcesses": [],
        "children": [],
        "attachedSchema": [],
        "meanings": [],
        "outputFromProcesses": []
      }
    }
    ae = AtlasEntity.from_json(input_entity)

    assert(ae.qualifiedName == input_entity["attributes"]["qualifiedName"])
    assert(ae.name == input_entity["attributes"]["name"])
    assert(ae.typeName == input_entity["typeName"])


# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2020/4/26 20:25
# @author  : Mo
# @function: constant of token-symbol and hyper-parameters-default

from macadam.conf.path_config import path_model_dir
from typing import Dict
import os

EMBEDDING_TYPE = ["ROBERTA","ELECTRA","RANDOM","ALBERT",
                   "XLNET","NEZHA","GPT2","WORD","BERT", "MIX"]

# symbol of common token
MASK = "[MASK]"
CLS = "[CLS]"
SEP = "[SEP]"
PAD = "[PAD]"
UNK = "[UNK]"
BOS = "[BOS]"
EOS = "[EOS]"
WC = "[WC]"

# task of macadam
SL = "SL" # sequence-labeling(ner, pos, tag)
TC = "TC" # text-classification
RE = "RE" # relation-extraction

# hyper_parameters of deep-learning, include sharing, embed, graph, train, save and data
hyper_parameters_default = {
"sharing": {"length_max": None,              # 句子最大长度, 不配置则会选择前95%数据的最大长度, 配置了则会强制选择, 固定推荐20-50, bert越长会越慢, 占用空间也会变大, 小心OOM
            "embed_size": 768,               # 字/词向量维度, bert取768, word取300, char可以更小些
            "vocab_size": None,              # 字典/词典大小, 可根据具体语料更新, 可不配置
            "trainable": True,               # embedding是静态的还是动态的, 即控制可不可以微调
            "task": None,                    # 任务类型, "SL"(sequence-labeling), "TC"(text-classification),"RE"(relation-extraction)
            "token_type": "CHAR",            # 级别, 最小单元, 字/词, 填 "CHAR" or "WORD", "NGRAM", 注意:word2vec模式下训练语料要首先切好
            "embed_type": "BERT",            # 级别, 嵌入类型, 还可以填"WORD"、"RANDOM"、 "BERT"、 "ALBERT"、"ROBERTA"、"NEZHA"、"XLNET"、"ELECTRA"、"GPT2"
            "gpu_memory_fraction": 0.6,     # gpu使用率, 0-1
             },
"embed": {"layer_idx": [-2],                 # 取bert的layer层输出, -1~-12, 0-11等, eg. 0, 1, 11, -1, -2, -12等
          "path_embed": None,                # 外部embed模型地址, 如word2vec, bert
          "merge_type": "concat",            # bert的layer层输出融合方式, 包括 "concat", "add", "pool-max", "pool-avg", "multi"
          "application": "encode",            # bert4keras下游任务, "encode", "lm", "unilm"等
          "length_first": None,              # 第一句最大长度, 大则截断-小则padding
          "length_second": None,             # 第二句最大长度, 大则截断-小则padding
          "xlnet_embed": {"attention_type": "bi",
                          "memory_len": 0,
                          "target_len": 5},  # xlnet的参数, 使用的是keras-xlnet
          },
"graph": {"filters_size": [3, 4, 5],         # 卷积核尺寸, 1-10
          "filters_num": 300,                # 卷积个数 text-cnn:300-600
          "rnn_type": None,                # 循环神经网络, select "LSTM", "GRU", "Bidirectional-GRU"
          "rnn_unit": 256,                   # RNN隐藏层, 8的倍数, 一般取64, 128, 256, 512, 768等
          "dropout": 0.5,                    # 随机失活, 概率， 0-1
          "activate_mid": "tanh",            # 中间激活函数, 非线性变幻, 提升逼近能力, 选择"relu","tanh"或"sigmoid"
          "activate_end": "softmax",         # 结束激活函数, 即最后一层的激活函数, 如cls激活函数, ner激活函数
          "use_onehot": True,                # label是否使用独热编码
          "use_crf": False,                  # 是否使用CRF(条件随机场), task="sl"(序列标注任务)任务
          "loss": None,                      # 损失函数, 真实值与实际预测的差值损失, 最优化的方向, "categorical_crossentropy"
          "metrics": "accuracy",             # 评估指标, 保存更好模型的评价标准, 一般选择loss, acc或f1等
          "optimizer": "Adam",               # 优化器, 可选["Adam", "Radam", "RAdam,Lookahead"]
          "optimizer_extend":[
              "gradient_accumulation",
              "piecewise_linear_lr",
              "layer_adaptation",
              "lazy_optimization",
              "]weight_decay",
              "lookahead"],                  #   优化器拓展, ["gradient_accumulation", "piecewise_linear_lr", "layer_adaptation",
                                             #              "lazy_optimization","weight_decay", "lookahead"]
          },
"train": {"learning_rate": 1e-3,             # 学习率, 必调参数, 对训练影响较大, word2vec一般设置1e-3, bert设置5e-5或2e-5
          "decay_rate": 0.999,               # 学习率衰减系数, 即乘法, lr = lr * rate
          "decay_step": 1000,                # 学习率每step步衰减, 每N个step衰减一次
          "batch_size": 32,                  # 批处理尺寸, 设置过小会造成收敛困难、陷入局部最小值或震荡, 设置过大会造成泛化能力降低
          "early_stop": 6,                   # 早停, N个轮次(epcoh)评估指标(metrics)不增长就停止训练
          "epochs": 20,                      # 训练最大轮次, 即最多训练N轮
          "label": None,                     # 类别数, auto无需定义, 如果定义则是强制指定
          "is_training": True,               # 是否训练, 用以区分训练train或预测predict, 用它判断后确定加不加载优化器optimizer
           },
"save": {
         # "path_hyper_parameters": None,    # 超参数文件地址
         "path_model_dir": None,   # 模型目录, loss降低则保存的依据, save_best_only=True, save_weights_only=True
         "path_model_info": None,            # 模型所有超参数, 保存在model_info.json
         "path_fineture": None,              # 微调后embedding文件地址, 例如字向量、词向量、bert向量等
          },
"data": {"train_data": None,                 # 训练数据
         "val_data": None                    # 验证数据
         },
}

class Config:
    def __init__(self, hyper_parameters: Dict={}):
        """
        Init of hyper_parameters and build_embed.
        Args:
            hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data".
        Returns:
            None
        """
        # 各种超参数, 设置默认超参数
        self.hyper_parameters = self.get_hyper_parameters_default()
        # 只更新传入的key-value
        for k in hyper_parameters.keys():
            self.hyper_parameters[k].update(hyper_parameters.get(k, {}))
        self.params_sharing = self.hyper_parameters.get("sharing", {})
        self.params_embed = self.hyper_parameters.get("embed", {})
        self.params_graph = self.hyper_parameters.get("graph", {})
        self.params_train = self.hyper_parameters.get("train", {})
        self.params_save = self.hyper_parameters.get("save", {})
        self.params_data = self.hyper_parameters.get("data", {})
        # params of sharing
        self.gpu_memory_fraction = self.params_sharing.get("gpu_memory_fraction", 0.60)
        self.embed_type = self.params_sharing.get("embed_type", "RANDOM")
        self.token_type = self.params_sharing.get("token_type", "CHAR")
        self.task = self.params_sharing.get("task", None)
        self.length_max = self.params_sharing.get("length_max", None)
        self.vocab_size = self.params_sharing.get("vocab_size", None)
        self.embed_size = self.params_sharing.get("embed_size", None)
        self.trainable = self.params_sharing.get("trainable", True)
        # params of embed
        self.layer_idx = self.params_embed.get("layer_idx", [])
        self.path_embed = self.params_embed.get("path_embed", None)
        self.merge_type = self.params_embed.get("merge_type", "concat")
        self.length_first = self.params_embed.get("length_first", None)
        self.length_second = self.params_embed.get("length_second", None)
        self.xlnet_embed = self.params_embed.get("xlnet_embed", {})
        self.attention_type =  self.params_embed.get("attention_type", "bi")
        self.memory_len =  self.params_embed.get("memory_len", 128)
        self.target_len =  self.params_embed.get("target_len", 128)
        # params of graph
        self.filters_size = self.params_graph.get("filters_size", [3, 4, 5])
        self.filters_num = self.params_graph.get("filters_num", 300)
        self.rnn_type = self.params_graph.get("rnn_type", None)
        self.rnn_unit = self.params_graph.get("rnn_unit", 256)
        self.dropout = self.params_graph.get("dropout", 0.5)
        self.activate_mid = self.params_graph.get("activate_mid", "tanh")
        self.activate_end = self.params_graph.get("activate_end", "softmax")
        self.use_onehot = self.params_graph.get("use_onehot", True)
        self.use_crf = self.params_graph.get("use_crf", False)
        self.loss = self.params_graph.get("loss", "categorical_crossentropy" if self.use_onehot
                                                  else "sparse_categorical_crossentropy")
        self.metrics = self.params_graph.get("metrics", "accuracy")
        self.optimizer = self.params_graph.get("optimizer", "Adam").upper()
        self.optimizer_extend = self.params_graph.get("optimizer_extend", [])
        # params of train
        self.learning_rate = self.params_train.get("learning_rate", 5e-5)
        self.decay_rate = self.params_train.get("decay_rate", 0.999)
        self.decay_step = self.params_train.get("decay_step", 32000)
        self.early_stop = self.params_train.get("early_stop", 6)
        self.batch_size = self.params_train.get("batch_size", 32)
        self.epochs = self.params_train.get("epochs", 20)
        self.label = self.params_train.get("label", None)
        self.is_training = self.params_train.get("is_training", True)
        # params of save
        self.path_model_dir = self.params_save.get("path_model_dir", path_model_dir)
        # self.path_model_info = self.params_save.get("path_model_info", None)
        self.path_fineture = self.params_save.get("path_fineture", None)
        # params of data
        self.train_data = self.params_data.get("train_data", None)
        self.val_data = self.params_data.get("val_data", None)
        # 特殊符号
        self.token_dict = {PAD: 0, UNK: 1,
                           CLS: 2, SEP: 3,
                           BOS: 4, EOS: 5,
                           MASK: 6, WC: 7
                           }
        # 递归创建模型保存目录
        if not self.path_model_dir: self.path_model_dir = path_model_dir
        if not os.path.exists(self.path_model_dir):
            os.makedirs(self.path_model_dir)

    def get_hyper_parameters_default(self) -> Dict:
        """
        Get hyper_parameters of default.
        Args:
            None
        Returns:
            Dict
        """

        return hyper_parameters_default


import requests
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
import pandas as pd

seed_url = "https://en.wikipedia.org/wiki/Sustainable_energy"

def is_valid(url):
        parsed = urlparse(url)
        return bool(parsed.netloc) and bool(parsed.scheme)

def getLinks(url):
    reqs = None
    try:
        reqs = requests.get(url,timeout=5)
    except:
        return []

    urls = []
    if reqs:
        soup = BeautifulSoup(reqs.text, 'html.parser')

        for link in soup.find_all('a'):
            urls.append(link.get('href'))
    return urls

def DFS_crawler(seedLink):
    dict = {}
    data1 = set()
    def dfs(link,level):
        if level==3 or not is_valid(link):
            return

        print(link)
        data1.add(link)

        dict[link] = True
        links = getLinks(link)

        for i in links:
            if not i in dict.keys():
                dfs(i,level+1)

    dfs(seedLink,0)
    print("----------------")
    # print(data1)
    return data1

# DFS_crawler(seed_url)


#https://www.hackerrank.com/challenges/py-set-discard-remove-pop
n = int(input())
s = set(map(int, input().split(" ")))
opNo = int(input())
for i in range(opNo):
    operation = input().split()
    if(operation[0]=='pop'):
        s.pop()
    elif(operation[0]=='remove'):
        s.remove(int(operation[1]))
    elif(operation[0]=='discard'):
        s.discard(int(operation[1]))
print(sum(s))


#לבקשת איתי שימוש ב10 קלטים בלבד
yes=0
no=0
avoid=0
veto=0
i=0
while i<=9:
    choice=int(input('plz insert youre choice, 1 for YES; 2 for NO; 3 for AVOID; 4 for VETO'))
    i=i+1
    if choice==4:
        print('the The serial number of the country is', i)
        break
    elif choice==1:
        yes=yes+1
    elif choice==2:
        no=no+1
    elif choice==3:
        avoid=avoid+1
print('the number of Supporte:', yes)
print('the number of aggainst:', no)
print('the number of avoid:', avoid)


#!/usr/bin/python3

# Lemmon equations
# "Revised Standardized Equation for Hydrogen Gas Densities for Fuel Consumption Applications"
# Journal of Research of the National Institute of Standards and Technology, 2008 Nov-Dec; 113(6): 341–350.
# Eric W. Lemmon, Jacob W. Leachman and Marcia L. Huber

import sys

sys.path.insert(0, "..")

from nomogen import Nomogen
from pynomo.nomographer import Nomographer

import math

# Constants associated with the density equation for normal hydrogen
# i       ai	         bi	ci
# 1  0.058 884 60	1.325	1.0
# 2 −0.061 361 11	1.87	1.0
# 3 −0.002 650 473	2.5	2.0
# 4  0.002 731 125	2.8	2.0
# 5  0.001 802 374	2.938	2.42
# 6 −0.001 150 707	3.14	2.63
# 7  0.958 852 8 × 10−4	3.37	3.0
# 8 −0.110 904 0 × 10−6	3.75	4.0
# 9  0.126 440 3 × 10−9	4.0	5.0

a = [0.05888460, -0.06136111, -0.002650473, 0.002731125, 0.001802374, -0.001150707, 0.9588528E-4, -0.1109040E-6,
     0.1264403E-9]

b = [1.325, 1.87, 2.5, 2.8, 2.938, 3.14, 3.37, 3.75, 4.0]

c = [1.0, 1.0, 2.0, 2.0, 2.42, 2.63, 3.0, 4.0, 5.0]

M = 2.01588  # Molar Mass, g/mol
R = 8.314472  # Universal Gas Constant,  J/(mol · K)

# p pressure in mPa
# T degrees K
def Z(p, T):
    s = 1
    for i in range( len(a) ):
        s = s + a[i] * (100 / T) ** b[i] * (p) ** c[i]
    return s

pmin = 1
pmax = 200
Tmin = 200
Tmax = 500
Zmin = 1
Zmax = Z(pmax, Tmin)

# Test points for validating
# T(K)	p(MPa)	    Z	         ρ (mol/1)
# 200	  1	1.00675450	0.59732645
# 300	  10	1.05985282	3.78267048
# 400	  50	1.24304763	12.09449023
# 500	  200	1.74461629	27.57562673
# 200	  200	2.85953449	42.06006952

correct = True
if not math.isclose(Z(1, 200), 1.00675450, abs_tol=5e-09):
    print("Z(1,200) fails")
    correct = False

if not math.isclose(Z(10, 300), 1.05985282, abs_tol=5e-09):
    print("Z(10,300) fails")
    correct = False

if not math.isclose(Z(50, 400), 1.24304763, abs_tol=5e-09):
    print("Z(50,400) fails")
    correct = False

if not math.isclose(Z(200, 500), 1.74461629, abs_tol=5e-09):
    print("Z(200,500) fails")
    correct = False

if not math.isclose(Z(200, 200), 2.85953449, abs_tol=5e-09):
    print("Z(200,200) fails")
    correct = False

if not correct:
    # print(  Z(1,200), Z(10,300), Z(50,400), Z(200,500), Z(200,200) )
    print("test points for Z(p,T) failed")
    sys.exit()

###############################################################
#
# nr Chebychev nodes needed to define the scales
# a higher value may be necessary if the scales are very non-linear
# a lower value increases speed, makes a smoother curve, but could introduce errors
NN = 9

##############################################
#
# definitions for the scales for pyNomo
# dictionary with key:value pairs

left_scale = {
    'u_min': pmin,
    'u_max': pmax,
    'title': r'$pressure \enspace MPa$',
    'scale_type': 'linear smart',
    'tick_levels': 3,
    'tick_text_levels': 2,
    'tick_side' : 'left',
    'grid': False
}

right_scale = {
    'u_min': Tmin,
    'u_max': Tmax,
    'title': r'$Temperature \enspace ^\circ K$',
    'scale_type': 'linear smart',
    'tick_levels': 3,
    'tick_text_levels': 2,
    'tick_side' : 'left',
    'grid': False
}

middle_scale = {
    'u_min': Zmin,
    'u_max': Zmax,
    'title': r'$Z$',
    'scale_type': 'log smart',
    'tick_levels': 6,
    'tick_text_levels': 5,
    'tick_side' : 'right',
    'grid': False
}

block_params0 = {
    'block_type': 'type_9',
    'f1_params': left_scale,
    'f2_params': middle_scale,
    'f3_params': right_scale,
    'transform_ini': False,
    'isopleth_values': [[(left_scale['u_min'] + left_scale['u_max']) / 2, \
                         'x', \
                         (right_scale['u_min'] + right_scale['u_max']) / 2]]
}

main_params = {
    'filename': __name__ == "__main__" and (
                __file__.endswith(".py") and __file__.replace(".py", "") or "nomogen") or __name__,
    'paper_height': 25,  # units are cm
    'paper_width': 18,
    'title_x': 9.0,
    'title_y': 3.0,
    'title_box_width': 8.0,
    'title_str': r'$\Large Z = {p \over {\rho R T}}$',
    'extra_texts': [
        {'x': 6,
         'y': 4,
         'text': r'$compressibility \thinspace factor \thinspace for \thinspace hydrogen$',
         'width': 10,
         }],
    'block_params': [block_params0],
    'transformations': [('scale paper',)],
    'pdegree': NN
}

print("calculating the nomogram ...")
Nomogen(Z, main_params)  # generate nomogram for yrs function
middle_scale.update({'tick_side': 'left'})

main_params['filename'] += '.pdf'
print("printing ", main_params['filename'], " ...")
Nomographer(main_params)


import pandas as pd
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR

advert = pd.read_csv('advertising.csv')

# Build linear regression model using TV and Radio as predictors
# Split data into predictors X and output Y
predictors = ['TV', 'Radio']
x = advert[predictors]
y = advert['Sales']

# split data into training and testing sets
trainX, testX, trainY, testY = train_test_split(x, y, test_size=0.2, random_state=0)  # 80:20
print(trainX.shape)
print(testX.shape)
print(trainY.shape)
print(testY.shape)

# initialize and fit model
lm = LinearRegression()
lm.fit(trainX, trainY)
# parameters of the model
print(f'alpha = {lm.intercept_}')
print(f'betas = {lm.coef_}')
print(f'R_squared = {lm.score(trainX, trainY)}')
# sales predict
print(lm.predict(testX))

# Recursive Feature Elimination
# Support Vector Regression
# start with all possible predictors
predictors = ['TV', 'Radio', 'Newspaper']
x = advert[predictors]
y = advert['Sales']

# estimate a linear model
estimator = SVR(kernel='linear')

# using rfe, specify 2 predictors for the final model
# and 1 predictor to remove at each iteration
selector = RFE(estimator, 2, step=1)
selector = selector.fit(x, y)
# get list of selected variables (TV, Radio, Newspaper)
print(selector.support_)
# selected variables have a ranking of 1
print(selector.ranking_)


import json
from channels.generic.websocket import WebsocketConsumer
from chess.constants import FILES_TO_COLUMNS, ROW_NAMES
from chess.engine import ChessEngine
from apps.game.models import Capture, Game, Move
from asgiref.sync import async_to_sync

from django.shortcuts import get_object_or_404

from chess.pieces import ChessPiece

class MovesConsumer(WebsocketConsumer):
    """
    Initializes a websocket connection to play the game

    Constructor
    ---
    Takes a `game: ChessBoard`

    Methods
    ---
    `receive()`: Takes a json input in the form of

    ```json
        {
            "message": {
                "start": [0, 2],
                "end": [0, 4]
            }
        }
    ```
    and shows a flow of the messages from the game engine
    """

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.board = ChessEngine()
        self.game = Game()

    def connect(self):
        self.accept()
        self.group_name = "chess"
        async_to_sync(self.channel_layer.group_add)(
                            self.group_name,
                            self.channel_name
                        )

        # Load Game messages
        if len(self.board.messages) > 1:
            for message in self.board.messages:
                self.channel_layer.group_send(self.group_name, {
                    "type": "game_message",
                    "message": message
                })
                self.send(json.dumps({
                    "type": "game_message",
                    "message": message
                }))
        else:
            self.send(json.dumps({"type": "initial_messages", "message": self.board.messages}))
        self.channel_layer.group_send(self.group_name,  {"type": "connection_success", "message": "Connection Establiched!"})
        self.send(json.dumps({"type": "game_id", "message": f"{self.group_name}"}))

    def receive(self, text_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        # Get move coordinates
        from_pos = message["from"]
        to_pos = message["to"]

        start = [FILES_TO_COLUMNS[from_pos[0]], ROW_NAMES[from_pos[1]]]
        end = [FILES_TO_COLUMNS[to_pos[0]], ROW_NAMES[to_pos[1]]]

        # initialize board
        board = self.board
        player = self.board.white_to_play

        # Move the piece
        board.make_move(initial_pos=start, destination=end)

        # Log for debugging
        print(f"{from_pos} {to_pos} by {'White' if player else 'Black'}")

        async_to_sync(self.channel_layer.group_send)(
            self.group_name,
            {
                "type": "create_move",
                "message": f"{from_pos} {to_pos} by {'White' if player else 'Black'}",
                "game_id": str(self.game.game_id),
                "game_messages": [m for m in self.board.messages],
                "board": self.board.board,
            }
        )

    def create_move(self, event):
        move = event["message"]
        game_id = event["game_id"]
        messages = event["game_messages"]

        self.send(text_data=json.dumps({
            "type": "game",
            "message": move,
            "game_id": game_id,
            "messages": messages
        }))

    def disconnect(self, code):
        game_id = self.game.game_id
        _game = Game.objects.create(game_id=game_id)
        _game.save()

        game_moves = []
        game_captures = []

        # Take the game moves
        for move in self.board.moves_history:
            board = self.board.board
            color = ""

            # Add piece to moves
            piece = board.board[move[0][0]][move[0][1]]
            if self.get_isinstance_piece(piece):
                color = "White" if piece.color else "Black"
            color = ""
            game_moves.append(
                        Move(
                            from_pos=f"{[move[0][0], move[0][1]]}",
                            to_pos=f"{[move[1][0], move[1][1]]}",
                            color=color
                        )
                    )

        # Take the game captures
        for capture in self.board.captures:
            piece = board.board[capture[0][0]][capture[0][1]]
            if self.get_isinstance_piece(piece):
                color = "White" if piece.color else "Black"
            color = ""
            game_captures.append(
                Capture(
                    color = color
                )
            )

        # Bulk create moves and captures
        this_game = get_object_or_404(Game, game_id=game_id)
        this_game.moves.bulk_create(game_moves)
        this_game.captures.bulk_create(game_captures)
        this_game.save()

    def get_isinstance_piece(self, piece):
        if isinstance(piece, ChessPiece):
           return True
        return False


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from pymongo import MongoClient
import requests, csv

# 실행 안해도 됨, 바로 mountainscrap.py를 실행하기!
driver = webdriver.Chrome(executable_path='/home/rapa/Documents/mountain/chromedriver')
db_url='mongodb://127.0.0.1:27017'
driver.get('http://bac.blackyak.com/html/challenge/ChallengeVisitList.asp?CaProgram_key=114')

f = open('mtngps.csv', 'wt', encoding='utf-8') # csv file 생성
data = {'C_name', 'C_gps1', 'C_gps2'} # colum설정
writer = csv.DictWriter(f,fieldnames=data)
writer.writeheader()

for i in range(1, 101):
    C_name = driver.find_element_by_xpath(f'//*[@id="VisitRecordList"]/ul/li[{i}]/div/div[2]/span[1]').text
    C_gps = driver.find_element_by_xpath(f'//*[@id="VisitRecordList"]/ul/li[{i}]/div/div[2]/a').text
    C_gps = C_gps.split(',')
    C_gps1 = C_gps[0]
    C_gps2 = C_gps[1]
    data = {'C_name':C_name, 'C_gps1':C_gps1, 'C_gps2':C_gps2}
    writer.writerow({'C_name':C_name,'C_gps1': C_gps1, 'C_gps2':C_gps2})
    print(data)

f.close()


'''
Qrcode example application
==========================

Author: Mathieu Virbel <mat@meltingrocks.com>

Featuring:

- Android camera initialization
- Show the android camera into a Android surface that act as an overlay
- New AndroidWidgetHolder that control any android view as an overlay
- New ZbarQrcodeDetector that use AndroidCamera / PreviewFrame + zbar to
  detect Qrcode.

'''

__version__ = '1.0'

from collections import namedtuple
from kivy.lang import Builder
from kivy.app import App
from kivy.properties import ObjectProperty, ListProperty, BooleanProperty, \
    NumericProperty
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.graphics import Color, Line
from jnius import autoclass, PythonJavaClass, java_method, cast
from android.runnable import run_on_ui_thread

# preload java classes
System = autoclass('java.lang.System')
System.loadLibrary('iconv')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Camera = autoclass('android.hardware.Camera')
ImageScanner = autoclass('net.sourceforge.zbar.ImageScanner')
Config = autoclass('net.sourceforge.zbar.Config')
SurfaceView = autoclass('android.view.SurfaceView')
LayoutParams = autoclass('android.view.ViewGroup$LayoutParams')
Image = autoclass('net.sourceforge.zbar.Image')
ImageFormat = autoclass('android.graphics.ImageFormat')
LinearLayout = autoclass('android.widget.LinearLayout')
Symbol = autoclass('net.sourceforge.zbar.Symbol')

class PreviewCallback(PythonJavaClass):
    '''Interface used to get back the preview frame of the Android Camera
    '''
    __javainterfaces__ = ('android.hardware.Camera$PreviewCallback', )

    def __init__(self, callback):
        super(PreviewCallback, self).__init__()
        self.callback = callback

    @java_method('([BLandroid/hardware/Camera;)V')
    def onPreviewFrame(self, data, camera):
        self.callback(camera, data)

class SurfaceHolderCallback(PythonJavaClass):
    '''Interface used to know exactly when the Surface used for the Android
    Camera will be created and changed.
    '''

    __javainterfaces__ = ('android.view.SurfaceHolder$Callback', )

    def __init__(self, callback):
        super(SurfaceHolderCallback, self).__init__()
        self.callback = callback

    @java_method('(Landroid/view/SurfaceHolder;III)V')
    def surfaceChanged(self, surface, fmt, width, height):
        self.callback(fmt, width, height)

    @java_method('(Landroid/view/SurfaceHolder;)V')
    def surfaceCreated(self, surface):
        pass

    @java_method('(Landroid/view/SurfaceHolder;)V')
    def surfaceDestroyed(self, surface):
        pass

class AndroidWidgetHolder(Widget):
    '''Act as a placeholder for an Android widget.
    It will automatically add / remove the android view depending if the widget
    view is set or not. The android view will act as an overlay, so any graphics
    instruction in this area will be covered by the overlay.
    '''

    view = ObjectProperty(allownone=True)
    '''Must be an Android View
    '''

    def __init__(self, **kwargs):
        self._old_view = None
        from kivy.core.window import Window
        self._window = Window
        kwargs['size_hint'] = (None, None)
        super(AndroidWidgetHolder, self).__init__(**kwargs)

    def on_view(self, instance, view):
        if self._old_view is not None:
            layout = cast(LinearLayout, self._old_view.getParent())
            layout.removeView(self._old_view)
            self._old_view = None

        if view is None:
            return

        activity = PythonActivity.mActivity
        activity.addContentView(view, LayoutParams(*self.size))
        view.setZOrderOnTop(True)
        view.setX(self.x)
        view.setY(self._window.height - self.y - self.height)
        self._old_view = view

    def on_size(self, instance, size):
        if self.view:
            params = self.view.getLayoutParams()
            params.width = self.width
            params.height = self.height
            self.view.setLayoutParams(params)
            self.view.setY(self._window.height - self.y - self.height)

    def on_x(self, instance, x):
        if self.view:
            self.view.setX(x)

    def on_y(self, instance, y):
        if self.view:
            self.view.setY(self._window.height - self.y - self.height)

class AndroidCamera(Widget):
    '''Widget for controling an Android Camera.
    '''

    index = NumericProperty(0)

    __events__ = ('on_preview_frame', )

    def __init__(self, **kwargs):
        self._holder = None
        self._android_camera = None
        super(AndroidCamera, self).__init__(**kwargs)
        self._holder = AndroidWidgetHolder(size=self.size, pos=self.pos)
        self.add_widget(self._holder)

    @run_on_ui_thread
    def stop(self):
        if self._android_camera is None:
            return
        self._android_camera.setPreviewCallback(None)
        self._android_camera.release()
        self._android_camera = None
        self._holder.view = None

    @run_on_ui_thread
    def start(self):
        if self._android_camera is not None:
            return

        self._android_camera = Camera.open(self.index)

        # create a fake surfaceview to get the previewCallback working.
        self._android_surface = SurfaceView(PythonActivity.mActivity)
        surface_holder = self._android_surface.getHolder()

        # create our own surface holder to correctly call the next method when
        # the surface is ready
        self._android_surface_cb = SurfaceHolderCallback(self._on_surface_changed)
        surface_holder.addCallback(self._android_surface_cb)

        # attach the android surfaceview to our android widget holder
        self._holder.view = self._android_surface

    def _on_surface_changed(self, fmt, width, height):
        # internal, called when the android SurfaceView is ready
        # FIXME if the size is not handled by the camera, it will failed.
        params = self._android_camera.getParameters()
        params.setPreviewSize(width, height)
        self._android_camera.setParameters(params)

        # now that we know the camera size, we'll create 2 buffers for faster
        # result (using Callback buffer approach, as described in Camera android
        # documentation)
        # it also reduce the GC collection
        bpp = ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8.
        buf = '\x00' * int(width * height * bpp)
        self._android_camera.addCallbackBuffer(buf)
        self._android_camera.addCallbackBuffer(buf)

        # create a PreviewCallback to get back the onPreviewFrame into python
        self._previewCallback = PreviewCallback(self._on_preview_frame)

        # connect everything and start the preview
        self._android_camera.setPreviewCallbackWithBuffer(self._previewCallback);
        self._android_camera.setPreviewDisplay(self._android_surface.getHolder())
        self._android_camera.startPreview();

    def _on_preview_frame(self, camera, data):
        # internal, called by the PreviewCallback when onPreviewFrame is
        # received
        self.dispatch('on_preview_frame', camera, data)
        # reintroduce the data buffer into the queue
        self._android_camera.addCallbackBuffer(data)

    def on_preview_frame(self, camera, data):
        pass

    def on_size(self, instance, size):
        if self._holder:
            self._holder.size = size

    def on_pos(self, instance, pos):
        if self._holder:
            self._holder.pos = pos

class ZbarQrcodeDetector(AnchorLayout):
    '''Widget that use the AndroidCamera and zbar to detect qrcode.
    When found, the `symbols` will be updated
    '''
    camera_size = ListProperty([320, 240])

    symbols = ListProperty([])

    # XXX can't work now, due to overlay.
    show_bounds = BooleanProperty(False)

    Qrcode = namedtuple('Qrcode',
            ['type', 'data', 'bounds', 'quality', 'count'])

    def __init__(self, **kwargs):
        super(ZbarQrcodeDetector, self).__init__(**kwargs)
        self._camera = AndroidCamera(
                size=self.camera_size,
                size_hint=(None, None))
        self._camera.bind(on_preview_frame=self._detect_qrcode_frame)
        self.add_widget(self._camera)

        # create a scanner used for detecting qrcode
        self._scanner = ImageScanner()
        self._scanner.setConfig(0, Config.ENABLE, 0)
        self._scanner.setConfig(Symbol.QRCODE, Config.ENABLE, 1)
        self._scanner.setConfig(0, Config.X_DENSITY, 3)
        self._scanner.setConfig(0, Config.Y_DENSITY, 3)

    def start(self):
        self._camera.start()

    def stop(self):
        self._camera.stop()

    def _detect_qrcode_frame(self, instance, camera, data):
        # the image we got by default from a camera is using the NV21 format
        # zbar only allow Y800/GREY image, so we first need to convert,
        # then start the detection on the image
        parameters = camera.getParameters()
        size = parameters.getPreviewSize()
        barcode = Image(size.width, size.height, 'NV21')
        barcode.setData(data)
        barcode = barcode.convert('Y800')

        result = self._scanner.scanImage(barcode)

        if result == 0:
            self.symbols = []
            return

        # we detected qrcode! extract and dispatch them
        symbols = []
        it = barcode.getSymbols().iterator()
        while it.hasNext():
            symbol = it.next()
            qrcode = ZbarQrcodeDetector.Qrcode(
                type=symbol.getType(),
                data=symbol.getData(),
                quality=symbol.getQuality(),
                count=symbol.getCount(),
                bounds=symbol.getBounds())
            symbols.append(qrcode)

        self.symbols = symbols

    '''
    # can't work, due to the overlay.
    def on_symbols(self, instance, value):
        if self.show_bounds:
            self.update_bounds()

    def update_bounds(self):
        self.canvas.after.remove_group('bounds')
        if not self.symbols:
            return
        with self.canvas.after:
            Color(1, 0, 0, group='bounds')
            for symbol in self.symbols:
                x, y, w, h = symbol.bounds
                x = self._camera.right - x - w
                y = self._camera.top - y - h
                Line(rectangle=[x, y, w, h], group='bounds')
    '''

if __name__ == '__main__':

    qrcode_kv = '''
BoxLayout:
    orientation: 'vertical'

    ZbarQrcodeDetector:
        id: detector

    Label:
        text: '\\n'.join(map(repr, detector.symbols))
        size_hint_y: None
        height: '100dp'

    BoxLayout:
        size_hint_y: None
        height: '48dp'

        Button:
            text: 'Scan a qrcode'
            on_release: detector.start()
        Button:
            text: 'Stop detection'
            on_release: detector.stop()
'''

    class QrcodeExample(App):
        def build(self):
            return Builder.load_string(qrcode_kv)

    QrcodeExample().run()


from collections import deque

n = int(input())

board = []
visit = [[0] * n for _ in range(n)]

for _ in range(n):
  board.append(list(map(int, input())))

count = []

for i in range(n):
  for j in range(n):
    if board[i][j] and not visit[i][j]:
      queue = deque([(j, i)])
      move = 0

      while queue:
        x, y = queue.popleft()

        visit[y][x] = 1
        move += 1

        for dx, dy in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
          nx, ny = x + dx, y + dy

          if 0 <= nx < n and 0 <= ny < n and (nx, ny) not in queue:
            if board[ny][nx] and not visit[ny][nx]:
              queue.append((nx, ny))

      count.append(move)

count.sort()

print(len(count))
print(*count, sep="\n")


#-*- coding:utf-8 -*-

print('****Mostra se Números estão em Ordem Crescente****\n')

n=int(input('Digite o Valor para Verificar: '))

a=n
i=0

while a!=0:
	a=a//10  # Acha a qtd de caracteres i
	i=i+1

n1=0

for a in range(i):
	n1=n%10
	n=(n-n1)//10
	a=n%10
	if n1>a:
		print('Sim')
		break
	elif n1<=a:
		print('Não')
		break

input()


# 타원형을 그리기 전에 사각형을 그리는 좌표 2개를 먼저 설정한다.
# 그 후에 사각형의 각 변에 접하는 타원형을 그린다.

# 타원 그리기

from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
canvas.create_oval(10, 10, 200, 150)
window.mainloop()

# 호 그리기

from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
canvas.create_arc(10, 10, 200, 150, extent=45, style=ARC)
window.mainloop()

# 반복문을 사용하여 각도를 증가시키면서 호 그리는 프로그램

from tkinter import *

window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
for degree in range(0, 360, 30):
    canvas.create_arc(10, 10+degree//5, 200, 150+degree//5, extent=degree, style=ARC)
window.mainloop()

# 다각형 그리기

from tkinter import *
window = Tk()

canvas = Canvas(window, width=300, height=200)
canvas.pack()

canvas.create_polygon(10, 10, 150, 110, 250, 20, fill="blue")
window.mainloop()

from tkinter import *

w = 300
h = 200
window = Tk()

w = Canvas(window, width=w, height=h)
w.pack()

points = [0, 0, 80, 150, 250, 20]
w.create_polygon(points, outline="red", fill="yellow", width=5)

window.mainloop()

# 텍스트 그리기

from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
canvas.create_text(100, 100, text='싱 스트리트(Sing Street)', fill='blue')
window.mainloop()

# 폰트 설정

from tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=200)
canvas.pack()
canvas.create_text(250, 10, text='Sing Street(싱 스트리트)', fill='blue', font=('Courier', 20))
canvas.create_text(250, 100, text='Sing street', fill="red", font=('Hevetica', 30))
canvas.create_text(250, 150, text='Sing Street', font=('Times', 40), fill='green')
window.mainloop()

from tkinter import *
window = Tk()

canvas = Canvas(window, width=300, height=200)
canvas.pack()

img = PhotoImage(file="C:\\Users\yaung\Desktop\빌리.png")
canvas.create_image(20, 20, anchor=NW, image=img)

window.mainloop()

import time
from tkinter import *
window = Tk()
canvas = Canvas(window, width=400, height=300)
canvas.pack()
id=canvas.create_oval(10, 100, 50, 150, fill="green")

for i in range(100):
    canvas.move(id, 3, 2)
    window.update()
    time.sleep(0.05)

def call_back(event):
    canvas.move(id, -10, 0)

from tkinter import *
window = Tk()
canvas = Canvas(window, width=400, height=300)
canvas.pack()

id = canvas.create_oval(10, 100, 50, 150, fill="green")

def move_right(event):
    canvas.move(id, 5, 0)
canvas.bind_all('<KeyPress-Right>', move_right)


def potencia( a, b):
    #Este programa cunta con 2 numeros que son una base y un exponente
    #
    #   a^b = a^(b/2) × a^(b/2)                si n es par.
    #   a^b = a^(b−1)/2 × a^(b−1)/2 × a        si n es impar.
#     Caso Base
    if b <= 0:
        return 1

#     b par
    if b % 2 == 0:
        pot = potencia(a, b/2) # recursion
        return pot * pot

#     b impar
    else:
        pot = potencia(a, (b-1)/2) # recursion
        return pot * pot * a

x = int(input("numero base: "))
y = int(input("numero exponente: "))
print(potencia(x, y))


import flask
import flask_login
from . import members
from . import schemas
from . import models

from ...models import requires_permission, get_config

@members.route('/', methods=['GET'])
@flask_login.login_required
@requires_permission('members_get')
def membersearch():
    """
        Allows the user to search for members. Note: We might externalise such an API call in future so it checks
        if the user has a memberid, and if it does overrides search criteria to only return that member ID.
    """
    schema = schemas.membersearchschema(data=flask.request.args)

    # If the user does not provide a pagenumber or provides something that is not an integer, we just set to 1.
    try:
        if flask.request.args.get('page') > 1:
            page = int(flask.request.args.get('page'))
        else:
            page = 1
    except TypeError:
        page = 1

    limit = flask.request.args.get('limit') or get_config('PAGINATION_COUNT')['configvalue']
    if schema.validate():
        try:
            if flask_login.current_user.memberid:
                memberid = flask_login.current_user.memberid
            else:
                memberid = flask.request.args.get('memberid')

            memberslist = models.member_get(memberid=memberid,
                                            surname=flask.request.args.get('surname'),
                                            addressline1=flask.request.args.get('addressline1'),
                                            county=flask.request.args.get('county'),
                                            postcode=flask.request.args.get('postcode'),
                                            offset=((page - 1)*int(limit)),
                                            limit=int(limit)
                                            )
            if len(memberslist) == 0:
                return '', 204
            return flask.jsonify({'members': memberslist}), 200
        except Exception as e:
            flask.abort(500, e)
    else:
        flask.abort(400, schema.errors)

@members.route('/<int:memberid>/', methods=['GET'])
@flask_login.login_required
@requires_permission('members_get')
def member_main(memberid):
    """
        Allows the user to get member details. Note: We might externalise such an API call in future so it checks
        if the user has a memberid, and if it does overrides search criteria to only return that member ID.
    """
    if flask_login.current_user.memberid == memberid:
        member = models.member_get(memberid=memberid)
    elif flask_login.current_user.memberid is None:
        member = models.member_get(memberid=memberid)
    else:
        flask.abort(403)

    if len(member) == 0:
        flask.abort(404)
    else:
        return flask.jsonify({'member': member[0]}), 200

@members.route('/', methods=['POST'])
@flask_login.login_required
@requires_permission('members_create')
def new_member_entry():

    schema = schemas.memberdetailsschema(data=flask.request.json)

    if schema.validate():
        try:
            newid = models.member_create(entryuserid=flask_login.current_user.userid,
                                         title=flask.request.json.get('title'),
                                         forename=flask.request.json.get('forename'),
                                         surname=flask.request.json.get('surname'),
                                         companyname=flask.request.json.get('companyname'),
                                         addressline1=flask.request.json.get('addressline1'),
                                         addressline2=flask.request.json.get('addressline2'),
                                         city=flask.request.json.get('city'),
                                         county=flask.request.json.get('county'),
                                         country=flask.request.json.get('country'),
                                         postcode=flask.request.json.get('postcode'),
                                         homephone=flask.request.json.get('homephone'),
                                         mobilephone=flask.request.json.get('mobilephone'),
                                         dateofbirth=flask.request.json.get('dateofbirth')
                                         )

            return flask.jsonify({'memberid': newid}), 201
        except Exception as e:
            flask.abort(500, e)
    else:
        flask.abort(400, schema.errors)

@members.route('/<int:memberid>/', methods=['PUT'])
@flask_login.login_required
@requires_permission('members_update')
def member_update(memberid):

    schema = schemas.memberdetailsschema(data=flask.request.json)

    if schema.validate():
        try:
            models.member_update(memberid=memberid,
                                 title=flask.request.json.get('title'),
                                 forename=flask.request.json.get('forename'),
                                 surname=flask.request.json.get('surname'),
                                 companyname=flask.request.json.get('companyname'),
                                 addressline1=flask.request.json.get('addressline1'),
                                 addressline2=flask.request.json.get('addressline2'),
                                 city=flask.request.json.get('city'),
                                 county=flask.request.json.get('county'),
                                 country=flask.request.json.get('country'),
                                 postcode=flask.request.json.get('postcode'),
                                 homephone=flask.request.json.get('homephone'),
                                 mobilephone=flask.request.json.get('mobilephone'),
                                 dateofbirth=flask.request.json.get('dateofbirth')
                                 )
            return '', 204
        except KeyError as e:
            flask.abort(404)
        except Exception as e:
            flask.abort(500, e)
    else:
        flask.abort(400, schema.errors)


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

from testtools import TestCase

from .. import Ngram

class IndicNgramTest(TestCase):

    def setUp(self):
        super(IndicNgramTest, self).setUp()
        self.ngram = Ngram()

    def test_letterNgram_English(self):
        self.assertEqual(self.ngram.letterNgram("catterpillar"),
                         ['ca', 'at', 'tt', 'te', 'er', 'rp',
                          'pi', 'il', 'll', 'la', 'ar'])

    def test_wordNgram_English(self):
        self.assertEqual(self.ngram.wordNgram("The quick \
        brown fox jumped over the lazy dog"),
                         [['The', 'quick'],
                          ['quick', 'brown'],
                          ['brown', 'fox'],
                          ['fox', 'jumped'],
                          ['jumped', 'over'],
                          ['over', 'the'],
                          ['the', 'lazy'],
                          ['lazy', 'dog']])

    def test_syllableNgram_English(self):
        self.assertEqual(self.ngram.syllableNgram("catterpillar", 4),
                         [' cat', 'cat-', 'at-t', 't-te', '-ter', 'ter-',
                          'er-p', 'r-pi', '-pil', 'pil-', 'il-l', 'l-la',
                          '-lar', 'lar '])

    def test_syllableNgram_Malayalam(self):
        self.assertEqual(self.ngram.syllableNgram(u"അധ്യാപകൻ"),
                         [[u'അ', u'ധ്യാ'],
                          [u'ധ്യാ', u'പ'],
                          [u'പ', u'ക'],
                          [u'ക', u'ൻ']])


#--------------------------------------------------------------------------

#This sample can be run using either the Azure Storage Emulator (Windows) or by updating the config.properties file with your Storage account name and key.

#To run the sample using the Storage Emulator (default option):
#1.Download and install the Azure Storage Emulator https://azure.microsoft.com/en-us/downloads/
#2.Start the emulator (once only) by pressing the Start button or the Windows key and searching for it by typing "Azure Storage Emulator". Select it from the list of applications to start it.
#3.Set breakpoints and run the project.

#To run the sample using the Storage Service
#1.Open the config.properties file and comment out the connection string for the emulator (UseDevelopmentStorage=True) and uncomment the connection string for the storage service (AccountName=[]...).
#2.Create a Storage Account through the Azure Portal and provide your [AccountName] and [AccountKey] in the config.properties file. See https://azure.microsoft.com/en-us/documentation/articles/storage-create-storage-account/ for more information
#3.Set breakpoints and run the project.
#---------------------------------------------------------------------------

import config
import azure.common
from azure.storage import CloudStorageAccount
from Queues import queue_samples
from Tables import table_samples
from Files import file_samples
from Blobs import blob_samples

print('Azure Storage samples for Python')

#try:
    # Create the storage account object and specify its credentials to either point to the local Emulator or your Azure subscription
if config.IS_EMULATED:
    account = CloudStorageAccount(is_emulated=True)
else:
    account_name = config.STORAGE_ACCOUNT_NAME
    account_key = config.STORAGE_ACCOUNT_KEY
    account = CloudStorageAccount(account_name, account_key)

#Basic Blob samples
print ('---------------------------------------------------------------')
print('Azure Storage Blob samples')
blob_samples.run_all_samples(account)

#Basic File samples
print ('---------------------------------------------------------------')
print('Azure Storage File samples')
file_samples.run_all_samples(account)

#Basic Table samples
print ('---------------------------------------------------------------')
print('Azure Storage Table samples')
table_samples.run_all_samples(account)

#Basic Queue samples
print ('---------------------------------------------------------------')
print('Azure Storage Queue samples')
queue_samples.run_all_samples(account)


from gevent import monkey
monkey.patch_all()

# conf='/etc/uwsgi/uwsgi.yaml'
# entity_class_name='beehive_service.controller.ApiAccount'
# task_name='beehive_service.task_v2.metrics.acquire_metric_task'
# task_class_name='beehive_service.task_v2.metrics.AcquireMetricTask'
# params_string='{}'

from beecell.simple import import_class, id_gen
from beehive.common.data import set_operation_params
from beehive.server import configure_server
from beehive.common.apimanager import ApiManager
from beehive.common.task_v2.manager import task_manager, configure_batch_task_manager
from beehive.common.task_v2 import prepare_or_run_task
from six import ensure_text
import ujson
from beehive.server import configure_server
from uuid import uuid4

from sys import argv

if __name__ == '__main__':
    params = configure_server()

    conf = argv[1]  #'/etc/uwsgi/uwsgi.yaml'
    entity_class_name = argv[2]  #'beehive_service.controller.ApiAccount'
    # task_name = argv[3]  #'beehive_service.task_v2.metrics.acquire_metric_task'
    task_class_name = argv[3]  #'beehive_service.task_v2.metrics.AcquireMetricTask'
    params_string = argv[4]  #'{}'

    task_params = ujson.loads(params_string)
    task_params['sync'] = False
    task_params['parent_task'] = ''
    task_params['hostname'] = 'localhost'
    task_params['user'] = 'task_manager'
    task_params['server'] = 'localhost'
    task_params['identity'] = ''
    task_params['api_id'] = 'batch'
    # task_params['objid'] = id_gen()
    task_params['task_id'] = id_gen()

    configure_batch_task_manager(params)
    set_operation_params({
        'user': ('task_manager', 'localhost', ''),
        'authorize': False,
        'id': ensure_text(params['api_id']) + '.batch',
        'cache': False,
    })

    api_manager: ApiManager = task_manager.api_manager
    entity_class = import_class(entity_class_name)
    # instance_class = entity_class(api_manager.main_module.get_controller())

    task_class= import_class(task_class_name)
    task_instance = task_class()
    task_instance.entity_class = entity_class
    task_instance.app = task_manager
    task_instance.entity_class = entity_class

    task_instance.get_session()
    task_instance.request.kwargsreprid = ''
    task_instance.request.id = str(uuid4())
    task_instance.task_result.task_prerun(task=task_instance, task_id=task_instance.request.id)
    task_instance.run(task_params)


from . import models, db

# Products table init.
def db_products_init():
    all_products = models.Product.query.all()
    if len(all_products) < 5:
        product1 = models.Product(name="a", quantity=1000)
        product2 = models.Product(name="b", quantity=1000)
        product3 = models.Product(name="c", quantity=1000)
        product4 = models.Product(name="d", quantity=1000)
        product5 = models.Product(name="e", quantity=1000)
        db.session.add(product1)
        db.session.add(product2)
        db.session.add(product3)
        db.session.add(product4)
        db.session.add(product5)
        db.session.commit()

# Transports table init.
def db_transports_init():
    all_transports = models.Transport.query.all()
    if len(all_transports) < 10:
        for _ in range(1, 11):
            transport = models.Transport(product_name=None, product_id=None)
            db.session.add(transport)
        db.session.commit()

# Shelfs table init.
def db_shelf_init():
    all_shelfs = models.Shelf.query.all()
    if len(all_shelfs) < 100:
        for _ in range(1, 101):
            shelf = models.Shelf(product_id=0)
            db.session.add(shelf)
        db.session.commit()


import os
import numpy as np

from sklearn.cluster import MeanShift, estimate_bandwidth

def cluster(prediction):
    bandwidth = estimate_bandwidth(prediction, quantile=0.01)
    print("bandwidth: ", bandwidth)
    ms = MeanShift(bandwidth=bandwidth, bin_seeding=False)

    ms.fit(prediction)

    labels = ms.labels_
    cluster_centers = ms.cluster_centers_
    num_clusters = cluster_centers.shape[0]

    return num_clusters, labels, cluster_centers


from django.urls import path
from . import views

urlpatterns = [
    path('', views.add_image, name='add_image'),
    path(
        'image_detail/<image_id>/<data_id>',
        views.image_detail,
        name='image_detail'),
    path('user_images/', views.all_user_images, name='all_user_images'),
    path('site_management', views.all_images_su, name='all_images_su'),
    path('delete_image/<image_id>', views.delete_image, name='delete_image'),
    path(
        'edit_image/<image_id>',
        views.edit_image_details,
        name='edit_image_details'),
]


import numpy as np
import tensorflow as tf
import cv2
import time
from sklearn.metrics import pairwise
from imutils.video import FPS

from utils import ops as utils_ops
from utils import label_map_util
from utils import visualization_utils as vis_util

font = cv2.FONT_HERSHEY_TRIPLEX

utils_ops.tf = tf.compat.v1
tf.gfile = tf.io.gfile
PATH_TO_LABELS = './data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

# model can be downloaded by http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz
model_name = 'ssdlite_mobilenet_v2_coco_2018_05_09'

model_dir = "./models/" + model_name + "/saved_model"
detection_model = tf.saved_model.load(str(model_dir))
detection_model = detection_model.signatures['serving_default']

# Setup initial positions in the line
heightF = 0
widthF = 0

crash_count_frames = 0
accident = 0
line_left = 0.3
line_right = 0.7
line_pos = 0.9

def estimate_collide(output_dict, height, width, image_np):
    global crash_count_frames, accident, line_left, line_right, line_pos
    cv2.line(image_np, (int(line_left * width + 1), int(line_pos * height)),
             (int(line_right * widthF - 1), int(line_pos * heightF)), (255, 127, 0), 4)
    details = [0, 0, 0, 0]
    for ind, scr in enumerate(output_dict['detection_classes']):
        if scr == 2 or scr == 3 or scr == 4 or scr == 6 or scr == 8:
            ymin, xmin, ymax, xmax = output_dict['detection_boxes'][ind]
            score = output_dict['detection_scores'][ind]
            if score > 0.5:
                details = [ymin, xmin, ymax, xmax]

    if (details[2] > line_pos) and ((details[1] < line_left and details[3] > line_left) or (
        details[1] < line_left and details[3] > line_right) or (
                                        details[1] < line_right and details[3] > line_right) or (
                                        details[1] > line_left and details[3] < line_right)):
        vehicle_crash = 1
        crash_count_frames = 15
    else:
        vehicle_crash = 0

    if vehicle_crash == 0:
        crash_count_frames = crash_count_frames - 1

    if crash_count_frames > 0:
        cv2.putText(image_np, "Slow down vehicle", (100, 100), font, 2, (0, 0, 255), 3, cv2.LINE_AA)

def run_inference_for_single_image(model, image):
    image = np.asarray(image)
    input_tensor = tf.convert_to_tensor(image)
    input_tensor = input_tensor[tf.newaxis, ...]

    output_dict = model(input_tensor)

    num_detections = int(output_dict.pop('num_detections'))

    output_dict = {key: value[0, :num_detections].numpy()
                   for key, value in output_dict.items()}
    output_dict['num_detections'] = num_detections
    output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
    return output_dict

def show_inference(model, image_path):
    image_np = np.array(image_path)
    height, width, channel = image_np.shape

    global heightF, widthF
    if heightF == 0:
        heightF = height
        widthF = width

    output_dict = run_inference_for_single_image(model, image_np)
    estimate_collide(output_dict, height, width, image_np)

    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks_reframed', None),
        use_normalized_coordinates=True,
        line_thickness=8)

    return image_np

cap = cv2.VideoCapture('./videos/test03.mp4')
time.sleep(2.0)

cap.set(1, 0)

fps = FPS().start()

ctt = 0
while True:
    (grabbed, frame) = cap.read()
    frame = frame[:-150, :, :]
    ctt = ctt + 1
    if ctt == 3334:
        break
    frame = show_inference(detection_model, frame)

    cv2.imshow("One & Zero", frame)
    fps.update()

    key = cv2.waitKey(1)
    if key == 27:
        break
    elif key == 119 and line_pos > 0:  # up (w)
        line_pos -= 0.05
    elif key == 115 and line_pos < heightF:  # down (s)
        line_pos += 0.05
    elif key == 97:  # left (a)
        line_left -= 0.05
    elif key == 122:  # left reverse (z)
        line_left += 0.05
    elif key == 100:  # right (d)
        line_right += 0.05
    elif key == 99:  # right reverse (c)
        line_right -= 0.05

fps.stop()
cap.release()
cv2.destroyAllWindows()


import logging

from odoo import _, api, fields, models
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

try:
    import phonenumbers
except ImportError:
    _logger.debug("Cannot `import phonenumbers`.")

class NumberNotFound(models.TransientModel):
    _name = "number.not.found"
    _description = "Number not found"

    calling_number = fields.Char(
        string="Calling Number",
        size=64,
        readonly=True,
        help="Phone number of calling party that has been obtained from the "
        "telephony server, in the format used by the telephony server (not "
        "E.164).",
    )
    e164_number = fields.Char(
        string="E.164 Number", size=64, help="E.164 equivalent of the calling number."
    )
    number_type = fields.Selection(
        selection=[("phone", "Fixed"), ("mobile", "Mobile")],
        string="Fixed/Mobile",
        required=True,
    )
    to_update_partner_id = fields.Many2one(
        comodel_name="res.partner",
        string="Partner to Update",
        help="Partner on which the phone number will be written",
    )
    current_partner_phone = fields.Char(
        related="to_update_partner_id.phone", string="Current Phone"
    )
    current_partner_mobile = fields.Char(
        related="to_update_partner_id.mobile", string="Current Mobile"
    )

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        if not res:
            res = {}
        if res.get("calling_number"):
            if not self.env.company.country_id:
                raise UserError(
                    _("Missing country on company %s" % self.env.company.display_name)
                )
            country_code = self.env.company.country_id.code
            try:
                parsed_num = phonenumbers.parse(res["calling_number"], country_code)
                res["e164_number"] = phonenumbers.format_number(
                    parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL
                )
                number_type = phonenumbers.number_type(parsed_num)
                if number_type == 1:
                    res["number_type"] = "mobile"
                else:
                    res["number_type"] = "phone"
            except Exception as e:
                _logger.error(
                    "Cannot reformat the phone number '%s': %s",
                    res["calling_number"],
                    e,
                )
        return res

    def create_partner(self):
        """Function called by the related button of the wizard"""
        self.ensure_one()
        parsed_num = phonenumbers.parse(self.e164_number, None)
        phonenumbers.number_type(parsed_num)

        context = dict(self._context or {})
        context["default_%s" % self.number_type] = self.e164_number
        action = {
            "name": _("Create New Partner"),
            "view_mode": "form,tree,kanban",
            "res_model": "res.partner",
            "type": "ir.actions.act_window",
            "target": "current",
            "context": context,
        }
        return action

    def update_partner(self):
        """Function called by the related button of the wizard"""
        self.ensure_one()
        if not self.to_update_partner_id:
            raise UserError(_("Select the Partner to Update."))
        self.to_update_partner_id.write({self.number_type: self.e164_number})
        action = {
            "name": _("Partner: %s" % self.to_update_partner_id.name),
            "type": "ir.actions.act_window",
            "res_model": "res.partner",
            "view_mode": "form,tree,kanban",
            "target": "current",
            "res_id": self.to_update_partner_id.id,
            "context": self._context,
        }
        return action


import cv2 as cv
import sys
import numpy as np
from matplotlib import pyplot as plt

def frame_update(s):
    blur = cv.GaussianBlur(img,(5,5),s)
    cv.imshow("Gaussienne",blur)

img = cv.imread(sys.argv[1])

if img is None:
	sys.exit("Could not read the image.")

cv.namedWindow('controls')
cv.createTrackbar('sigma','controls',0,1,frame_update)

blur = img
cv.imshow("Original",img)
cv.imshow("Gaussienne",blur)

cv.waitKey(0)
cv.destroyAllWindows()


from docx import Document

def checkAndChange(document, replaceDict):
    """
    遍历word中的所有 paragraphs，在每一段中发现含有key 的内容，就替换为 value 。
   （key 和 value 都是replace_dict中的键值对。）
    """
    for para in document.paragraphs:
        for i in range(len(para.runs)):
            print(para.runs[i].text)
            for key, value in replaceDict.items():
                if key in para.runs[i].text:
                    print(key + "->" + value)
                    para.runs[i].text = para.runs[i].text.replace(key, value)
    return document

def checkAndChangeTable(document, replaceDict):
    tableNum = len(document.tables)
    for i in range(0, tableNum):
        rowNum = len(document.tables[i].rows)
        for j in range(0, rowNum):
            colNum = len(document.tables[i].rows[j].cells)
            for k in range(0, colNum):
                cell = document.tables[i].rows[j].cells[k]
                # print("cell: " + cell)
                for key, value in replaceDict.items():
                    if key == cell.text:
                        print(key + "->" + value)
                        cell.text = cell.text.replace(key, value)

def generateWordDocuments(tempFile,replaceDict,rowData,colExternal):
    doc = Document(tempFile)
    newDict = {}
    for key in replaceDict.keys():
        newDict[key] = rowData[replaceDict[key]]
    print(newDict)
    checkAndChangeTable(doc,newDict)
    doc.save(rowData[colExternal]+".docx")


#!/usr/bin/python3
""" Add integer """

def add_integer(a, b=98):
    """ Adds two integers and returns the result
        a and b must be integers or floats
    """
    import doctest
    if not isinstance(a, int) and not isinstance(a, float):
        raise TypeError("a must be an integer")
    elif not isinstance(b, int) and not isinstance(b, float):
        raise TypeError("b must be an integer")
    else:
        return int(a) + int(b)


import sys

sys.setrecursionlimit(1000000)
input = sys.stdin.readline

# start -> end까지 weight 무게로 통과가능한지
# DFS 재귀함수로 구현
def check(cur, weight):
    global end
    if cur == end:
        return True

    for node, bridgeW in graph[cur]:
        if bridgeW >= weight and not visited[node]:  # 중량이 넘지 않는다면
            visited[node] = True
            if check(node, weight):
                return True
            # visited[node] = False -> ✅ 이부분 때문에 자꾸 시간초과남

    return False

if __name__ == "__main__":
    n, m = map(int, input().split())
    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a].append((b, c))
        graph[b].append((a, c))

    start, end = map(int, input().split())

    left = 1
    right = 1000000000
    while left <= right:
        mid = (left + right) // 2
        visited = [False] * (n + 1)
        visited[start] = True

        if check(start, mid):
            left = mid + 1
        else:
            right = mid - 1

    print(right)


#!/usr/bin/env python3

import threading

from flask import Flask, jsonify, request
from flask_api import status

from game_state import UserDoesntExistError, UserAlreadyExistsError, InvalidUserActionError
from session import InvalidSessionError, InvalidCredentialsError

app = Flask(__name__)

# TODO session in cookies so GET can be used

# TODO dependency injection
session_config = {
    'expiry_timeout_s': 100,
    'expiry_sliding_window_s': 60
}
from stateful_ticket_session import StatefulTicketSessionManager as SessionManager
session_manager = SessionManager(session_config)
game_config = {'alert_chance_of_multiply':0.2}
from stateful_game_state import StatefulGameState as GameState
game_state = GameState(game_config)

def create_json_error_response(msg, code):
    """
    Returns flask error response body and code pair

    :param string msg: error message

    :param int code: HTTP Status Code

    :return (json, int): json message and status code
    """
    return jsonify({'msg': msg}), code

def parse_json(req):
    return req.get_json(force=True)

def check_expired_sessions():
    expired_sessions = session_manager.check_expired_sessions()
    for id in expired_sessions.keys():
        game_state.remove_user(id)

@app.route('/login', methods=['POST'])
def login():
    check_expired_sessions()
    result = None
    try:
        credentials = parse_json(request)
        result = session_manager.new_session(credentials)
        game_state.add_user(result['id'])
    except InvalidCredentialsError as exc:
        return create_json_error_response('failed to login', status.HTTP_401_UNAUTHORIZED)
    return jsonify(result)

@app.route('/session', methods=['POST'])
def session():
    check_expired_sessions()
    result = None
    try:
        session_details = parse_json(request)
        result = session_manager.extend_session(session_details)
    except InvalidSessionError as exc:
        return create_json_error_response('failed to extend session', status.HTTP_401_UNAUTHORIZED)
    return jsonify(result)

@app.route('/signout', methods=['POST'])
def signout():
    check_expired_sessions()
    try:
        session_details = parse_json(request)
        session_manager.destroy_session(session_details)
        game_state.remove_user(session_details['id'])
    except InvalidSessionError as exc:
        return create_json_error_response('failed to destroy session', status.HTTP_401_UNAUTHORIZED)
    except UserDoesntExistError:
        return create_json_error_response('unknown error', status.HTTP_500_INTERNAL_SERVER_ERROR)
    return '', status.HTTP_200_OK

@app.route('/action', methods=['POST'])
def action():
    check_expired_sessions()
    result = None
    try:
        req = parse_json(request)
        session_manager.authenticate_session(req['session'])
        req['session'] = session_manager.extend_session(req['session'])
        result = game_state.user_action(req['session']['id'], req['user_action'])
    except InvalidSessionError:
        return create_json_error_response('cant take user action', status.HTTP_401_UNAUTHORIZED)
    except InvalidUserActionError as error:
        return create_json_error_response(
            'invalid user action ' + error.msg,
            status.HTTP_400_BAD_REQUEST
        )
    except KeyError:
        return create_json_error_response('invalid request', status.HTTP_400_BAD_REQUEST)
    except UserDoesntExistError:
        return create_json_error_response('unknown error', status.HTTP_500_INTERNAL_SERVER_ERROR)
    return jsonify(result)

if __name__ == "__main__":
    app.run()


import pathlib
from tkinter import *
from tkinter import ttk

from PIL import Image, ImageTk

class TrafficLight():
    def __init__(self):
        width = 700
        height = 900
        #Create an instance of tkinter frame
        self.win= Tk()
        #Set the geometry
        self.win.geometry(f'{width}x{height}')
        #Define function to update the image

        #Create a canvas and add the image into it
        self.canvas= Canvas(self.win, width=width, height= height)
        self.canvas.pack()

        #Open an Image in a Variable
        imagespath = pathlib.Path(__file__).parent.parent.joinpath("images")
        im1= Image.open(imagespath.joinpath("smiley_grey.png"))
        im2= Image.open(imagespath.joinpath("smiley_green.png"))
        im3= Image.open(imagespath.joinpath("smiley_red.png"))
        imgsize =  (width, height)
        resized_image1 = im1.resize(imgsize, Image.ANTIALIAS)
        resized_image2 = im2.resize(imgsize, Image.ANTIALIAS)
        resized_image3 = im3.resize(imgsize, Image.ANTIALIAS)

        img1= ImageTk.PhotoImage(resized_image1)
        img2= ImageTk.PhotoImage(resized_image2)
        img3= ImageTk.PhotoImage(resized_image3)

        self.imageList = [img1, img2, img3]
        #Add image to the canvas
        self.image_container = self.canvas.create_image(0,0, anchor="nw",image=img1)

        self.win.update()

    def update_image(self, input):
        self.imageList[input]

        self.canvas.itemconfig(self.image_container,image=self.imageList[input])
        self.win.update()