# This is a sample for logistic optimization in python. I took this from the R
# version located in my CodeSamples folder as well as information here:
# https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html

import numpy as np
import pandas as pd
from plotnine import *
from scipy.optimize import minimize
# import matplotlib.pyplot as plt

data = pd.read_csv('../R/logitPracticeData.csv')
data.head()
data['label'] = data['label'].astype('category')
# %matplotlib inline
# figure
# Creating theme for APA in ggplot

# See for plot themes
# http://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.theme.html

# Does full apa only thing that is not implemented is that transparant legend box
apatheme = theme(panel_grid_major=element_blank(),
                 panel_grid_minor=element_blank(),
                 panel_border=element_blank(),
                 panel_background=element_rect(fill="None"),
                 axis_line=element_line(),
                 text=element_text(family='sans'),
                 plot_title=element_text(hjust=0.5),
                 legend_key=element_rect(fill="None", colour="None", size=0.25),
                 legend_box_background=element_rect(fill="None", linetype="None"),
                 plot_background=element_rect(fill="None", colour='None'))

p = ggplot(data, aes(x='score-1', y='score-2', color='label')) + \
    geom_point() + apatheme

print(p)

data['label'] = data['label'].astype('int64')

# plt.plot(data['score-1'], data['score-2'],'o', 'color', data['label'])
# plt.show()

X = data.iloc[:, 0:-1].as_matrix()
X = np.c_[np.ones(100), X]
Y = data['label']

def sigmoid(z):
    '''
    Calculates the Sigmoid value based on the input parameters, with defaults
    for SVf = 1, SFl = 0, and gamma = 1

.. math::
    \sum_{i=1}^{\\infty} x_{i}

    '''
    # 1/(1 + np.exp(gamma*(SVf - SVl)))
    return 1 / (1 + np.exp(-z))

def logitCost(theta):
    '''
    Vectorized Cost function for logistic regression
    Obtained from here:
            http://ml-cheatsheet.readthedocs.io/en/latest/logistic_regression.html
    '''
    m = Y.shape[0]
    g = sigmoid(np.dot(X, theta))
    j = (1 / m) * sum((-Y * np.log(g)) - ((1 - Y) * np.log(1 - g)))
    # cost = 1./len(y) *(-np.dot(np.log(h),(y))-np.dot(np.log(1-h),(1-y)))
    return j

x0 = np.zeros(X.shape[1])
res = minimize(logitCost, x0, method='nelder-mead', options={'xtol': 1e-8, 'disp': True, 'maxiter': 10000})
print(res.x)


"""2d spherical raytracer, constructed as visual analogue of the 3d case"""

import numpy as np
import matplotlib.pyplot as plt

from pycomplex import synthetic
from pycomplex.math import linalg

space = synthetic.icosahedron()

coordinate = linalg.orthonormalize(np.random.randn(3, 3))
p, x, y = coordinate
dx, dy = [linalg.power(linalg.rotation_from_plane(p, d), 1. / 90) for d in [x, y]]

stepsize = 10  # ray step size in degrees

fov = 1  # higher values give a wider field of view
resolution = 30,
gx = np.linspace(-stepsize, +stepsize, num=resolution[0], endpoint=True)
ray_step = np.einsum('xij,jk->xik', linalg.power(dx, gx * fov), linalg.power(dy, +stepsize))
s = np.rad2deg(linalg.angle_from_rotation(ray_step))
ray_step = linalg.power(ray_step, stepsize / s)
max_distance = 180  # trace rays half around the universe

space.plot()

ray = p
for distance in np.arange(0, max_distance, stepsize):
    ray = np.einsum('...ij,...j->...i', ray_step, ray)
    plt.scatter(*ray[:, :2].T)

plt.show()


import math
import random
import sys

class Customer:

    def __init__(self, name, address, phone_number):
        self.name = name
        self.address = address
        self.phone_number = phone_number

class Product:

    def __init__(self, name, unit_price):
        self.name = name
        self.unit_price = unit_price

CUSTOMERS = [
    Customer('Alice', 'Washington', '1000'),
    Customer('Bob', 'Texas', '1001'),
    Customer('Cindy', 'New York', '1002'),
    Customer('Dale', 'Mississippi', '1003'),
    Customer('Eric', 'North Carolina', '1004'),
    Customer('Frank', 'California', '1004'),
    Customer('Grace', 'Alabama', '1006'),
    Customer('Helen', 'Hawaii', '1007'),
    Customer('Issac', 'Florida', '1008'),
    Customer('Jack', 'Missouri', '1009'),
    Customer('Kevin', 'Pennsylvania', '1010'),
    Customer('Leo', 'Ohio', '1011'),
    Customer('Michael', 'Vermont', '1012'),
    Customer('Nancy', 'South Carolina', '1013'),
    Customer('Olivia', 'Arizona', '1014'),
    Customer('Peter', 'New Mexico', '1015'),
]

PRODUCTS = [
    Product('apple', 6.23),
    Product('banana', 7.3),
    Product('orange', 9.98),
    Product('grape', 10.77),
    Product('strawberry', 39.5),
    Product('pineapple', 5.16),
    Product('watermelon', 3.78),
    Product('lemon', 7.25),
    Product('cherry', 9.98),
    Product('kiwi', 5.98),
    Product('peach', 9.86),
    Product('bread', 5.8),
    Product('cake', 12.9),
    Product('biscuit', 15.9),
    Product('chocolate', 45.9),
    Product('candy', 16.5),
]

if __name__ == '__main__':
    with open(sys.argv[1], 'w') as f:
        for c in random.sample(CUSTOMERS, 12):
            f.write(f'{{ "{c.name}" "{c.address}" "{c.phone_number}" ')
            n_product = random.randint(1, 10)
            for p in random.sample(PRODUCTS, n_product):
                count = math.ceil(random.expovariate(0.5))
                f.write(f'("{p.name}" {p.unit_price} {count}) ')
            f.write('}\n')


def extractBlackmaskedphantomWordpressCom(item):
	'''
	Parser for 'blackmaskedphantom.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('Aloof King',                                                                  'Aloof King and Cold (Acting) Queen',                                                         'translated'),
		('The Adventures of the Idiot Hero, the Logical Mage, and Their Friends',       'The Adventures of the Idiot Hero, the Logical Mage, and Their Friends',                      'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


import numpy as np
import cma
from .optimizer import Optimizer

class CmaEsOptimizer(Optimizer):
    """Covariance Matrix Adaption-Evolution Strategy optimizer.

    Mainly hyper parameters are following:
        - sigma: A initial variance in order to generate population.
            This parameter likes the search range.
        - fixed_variables: dictionary with index-value pairs like
            {0:1.1, 2:0.1} that are not optimized.
        - popsize: population size, AKA lambda,
            number of new solution per iteration
        - CMA_stds: multipliers for sigma0 in each coordinate,
            not represented in C, makes scaling_of_variables obsolete
        - randn: randn(lam, N) must return an np.array of shape (lam, N),
            see also cma.utilities.math.randhss
    Other parmaeters indicated at line 407-480
    in cma.evolution_strategy.py

    Please see the following for algorithm details.
    https://en.wikipedia.org/wiki/CMA-ES
    """

    def __init__(self):
        super().__init__()
        self.optimizer = None
        self.sigma = None
        self.options = cma.CMAOptions.defaults()

    def set_hyper_parameters(self, **params):
        self.sigma = np.asarray(params.pop('sigma'))
        self.options.update(params)

    def setup_core(self):
        self.optimizing = True
        self.optimizer = cma.CMAEvolutionStrategy(
            self.initial_guess, self.sigma, self.options
        )

    def generate_core(self):
        self.population = self.optimizer.ask()
        return self.population

    def update_core(self, metric):
        self.optimizer.tell(self.population, metric)
        if self.optimizer.stop():
            self.optimizing = False
            self.minimal = self.optimizer.result.xbest


import speech_recognition as sr

recon = sr.Recognizer()

with sr.Microphone() as source:
    while True:
        recon.adjust_for_ambient_noise(source, duration=3)  # Ajustando audio para melhorar o reconhecimento

        print('Say something: ')
        audio = recon.listen(source)

        print(recon.recognize_sphinx(audio))


from telnetlib import STATUS
from fastapi import APIRouter, Depends, HTTPException

from ..redis.cache_updates import update_cache

from ..handlers.map_handler import MapWorkflow

router = APIRouter(prefix="/api/v1.0/ressources/map",
                   tags=["map"],
                   responses={404: {"description": "Not found"}}
                   )

@router.get("/")
async def map():
    map_workflow = MapWorkflow()
    map_workflow.build()
    if map_workflow.get() is None:
        raise HTTPException(status_code=404, detail='An error occured, please contact an administrator.')
    return map_workflow.get()

@router.get("/update")
async def update():
    update_cache()
    return 'Cache updated'


import shutil
import unittest
from uquake.grid.nlloc import VelocityGrid3D, VelocityGridEnsemble
from loguru import logger
import numpy as np

root_dir = 'projects'
test_project = 'test_project'
test_network = 'TN'

grid_dim = [10, 10, 10]
grid_spacing = [1, 1, 1]
grid_origin = [0, 0, 0]

class NLLOC(unittest.TestCase):
    def test_locate_event(self):
        from uquake.nlloc.nlloc import Srces, Observations
        from useis.processors.nlloc import NLLOC
        nll = NLLOC('projects', 'test', 'TN')

        p_velocity_grid = VelocityGrid3D(test_network,
                                         grid_dim,
                                         grid_origin,
                                         grid_spacing,
                                         phase='P', value=5000)
        s_velocity_grid = VelocityGrid3D(test_network,
                                         grid_dim,
                                         grid_origin,
                                         grid_spacing,
                                         phase='S', value=3000)

        velocity_grids = VelocityGridEnsemble(p_velocity_grid, s_velocity_grid)
        nll.add_velocities(velocity_grids, initialize_travel_times=False)

        srces = Srces.generate_random_srces_in_grid(p_velocity_grid,
                                                    n_srces=20)
        nll.add_srces(srces, initialize_travel_time=False)

        nll.init_travel_time_grids(multi_threaded=True)

        e_loc = nll.p_velocity.generate_random_points_in_grid()
        observations = Observations.generate_observations_event_location(
            nll.travel_times, e_loc=e_loc)

        result = nll.run_location(observations=observations)

        distance = np.linalg.norm(result.loc - e_loc)
        logger.info(f'\n{distance:0.1f} m - error\n'
                    f'{result.uncertainty * 2:0.1f} m - uncertainty (2 std) ')
        shutil.rmtree(root_dir)

        self.assertTrue(distance < 3 * result.uncertainty)

if __name__ == '__main__':
    unittest.main()
    shutil.rmtree(root_dir)


# 链接：https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/
# 题意：给定两个长度为 n 的整型数组 nums1 和 nums2，我们可以重排 nums2 ，
#       求 sum(nums1[i] XOR nums2[i]) 的最小值？

# 输入： nums1 = [1,2], nums2 = [2,3]
# 输出： 2
# 解释： 重排 nums2 为 [3, 2] ，
#       则最小值为： (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2

# 输入： nums1 = [1,0,3], nums2 = [5,3,4]
# 输出： 8
# 解释： 重排 nums2 为 [5, 4, 3] ，
#       则最小值为： (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8

# 思路1： 记忆化搜索
#
#       设 count(i) 表示 i 的二进制中 1 的个数，
#       设 dp[i] 表示前 count(i) 个 nums1 与 nums2 中标记的数字已组合的情况下，
#       剩余数字能组合出来的最小 XOR 的和
#       最终 dp[0] 就是我们需要的答案
#
#       初始化 dp[i] = -1, dp[(1 << len(nums2)) - 1] = 0
#       对于每一层 dfs ，我们遍历需要用到的 nums2[j]
#       （保证 nums2[j] 未使用，即 used & (1 << j) 为 0），
#       然后将其与 nums1[count(used)] 求 XOR ，即： nums1[count(used)] ^ nums[j]
#       再递归计算对应的 dfs(used | (1 << j)) 这个状态下的最下 XOR 的和即可，
#       则当前层 dp[used] = min(nums1[count(used)] ^ nums[j] + dfs(used | (1 << j)))
#
#       时间复杂度： O(n * 2 ^ n)
#       空间复杂度： O(2 ^ n)

class Solution:
    def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
        # 初始化 dp
        dp = [-1] * (1 << len(nums2))
        dp[(1 << len(nums2)) - 1] = 0
        return self.dfs(dp, nums1, nums2, 0)

    def dfs(self, dp: List[int], nums1: List[int], nums2: List[int], used: int) -> int:
        # 如果以及计算过了，则直接返回
        if dp[used] != -1:
            return dp[used]

        # 通过 used ，找到当前层需要用到的 nums1 中的哪个数
        num1 = nums1[self.count(used)]
        # 计算所有情况下的最小值
        dp[used] = 0x3f3f3f3f3f3f3f3f
        for j in range(len(nums2)):
            # 只有 nums2[j] 没有用过，才能继续更新
            if not (used & (1 << j)):
                dp[used] = min(dp[used], (num1 ^ nums2[j]) + self.dfs(dp, nums1, nums2, used | (1 << j)))

        return dp[used]

    def count(self, num: int) -> int:
        cnt = 0
        while num > 0:
            cnt += num & 1
            num >>= 1
        return cnt

# 思路2： 状压 DP
#
#       设 count(i) 表示 i 的二进制中 1 的个数，
#       dp[i] 表示前 count(i) 个 nums1 与 nums2 中标记的数字已组合的情况下，
#       所有 XOR 的和的最小值
#
#       初始化 dp[i] = 0x3f3f3f3f3f3f3f3f, dp[0] = 0
#       则已知状态 i 的情况下，遍历下一个使用的 nums2[j] ，有状态转移方程：
#           dp[i | (1 << j)] = min(dp[i | (1 << j)], dp[i] + (num1 ^ nums2[j]))
#
#       时间复杂度： O(n * 2 ^ n)
#       空间复杂度： O(2 ^ n)

class Solution:
    def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
        # 初始化 dp
        mx = 1 << len(nums2)
        dp = [0x3f3f3f3f3f3f3f3f] * mx
        dp[0] = 0
        # 遍历状态 i ，最后全使用的状态 i 不会再进行更新，不需要遍历
        for i in range(mx - 1):
            # 通过状态 i 确定当前要使用的 num1
            num1 = nums1[self.count(i)]
            # 遍历将要使用的 nums2[j]
            for j in range(len(nums2)):
                # 如果这个数没有使用过，则可以用来更新状态
                if not (i & (1 << j)):
                    dp[i | (1 << j)] = min(dp[i | (1 << j)], dp[i] + (num1 ^ nums2[j]))
        return dp[mx - 1]

    def count(self, num: int) -> int:
        cnt = 0
        while num > 0:
            cnt += num & 1
            num >>= 1
        return cnt

Python3/src/1801 ~ 1900/1879 - Minimum XOR Sum of Two Arrays.py


from src.tagmodel import TagModel
from src.pbvi import PBVI
from src.pomdpSimulation import  POMDP

def main():
    execParams = {
        'model_name': 'Tag',
        'max_play': 100,
        'print_process': True,
    }
    algoParams = {
        'algo': 'pbvi',
        'horizon_T': 5,
        'expend_N': 1,
        'expend_method': 'SSRA',  # RA, SSRA, SSEA
        'num_belief': 100,
    }
    envParams = {
        'env_name': 'Tag_env',
        'discount': 0.75,
    }

    # initialize environment
    modelEnv = TagModel()
    modelEnv.specifyEnvironmentArguments(envParams)
    pomdp = POMDP(modelEnv)

    # initialize solver
    solver = PBVI(modelEnv)
    beliefPoints = modelEnv.generateInitBeliefPoints(algoParams['num_belief'])
    solver.specifyAlgorithmArguments(beliefPoints, algoParams)

    totalRewards = 0
    belief = modelEnv.generateUniformBeliefs()  # for model evaluation
    if execParams['print_process']:
        print('''Initial State: {} || Time Horizon: {} || Max Play: {} || Initial Belief: {}
            '''.format(modelEnv.currentState, algoParams['horizon_T'], execParams['max_play'], belief))

    # start playing
    for i in range(execParams['max_play']):
        # this is a general framework of solving POMDP problems
        state = modelEnv.currentState
        action = solver.getPlanningAction(belief)  # get best action
        nextState, observation, reward = pomdp.envFeedback(state, action)  # receive environment feedback
        belief = pomdp.updateBelief(belief, action, observation)  # update the belief
        totalRewards += reward
        if 'tag' in nextState:
            break
        modelEnv.currentState = nextState

        # for every trial, print the result
        if execParams['print_process']:
            print("Play Times: {} || Action Chosen: {} || Observation: {} || Reward: {} || New State: {} || New Belief: {}".format(
                    i, action, observation, reward, nextState, belief))

    print("Total reward:{}".format(totalRewards))

if __name__ == '__main__':
    main()


def my_zip_gen(a_iter, b_iter):

    len_b = len(b_iter)

    return ((a_elem, b_iter[i]) if i < len_b else (a_elem, None)
            for i, a_elem in enumerate(a_iter))

import json

from myutils import my_zip_gen

def groping(
        output_pth="./out.txt",
        user_pth="./users.csv",
        hobby_pth="./hobby.csv"):

    if not (user_pth or hobby_pth):
        return -1

    user_lines = None
    hobby_lines = None

    with open(user_pth, "r", encoding="utf-8") as user_file:
        user_lines = user_file.readlines()

    with open(hobby_pth, "r", encoding="utf-8") as hobby_file:
        hobby_lines = hobby_file.readlines()

    if len(user_lines) < len(hobby_lines):
        return 1

    group = {}

    for fio, hobby in my_zip_gen(user_lines, hobby_lines):
        fio = fio.replace("\n", "").replace(",", " ")
        group[fio] = hobby.replace("\n", "") if hobby else None

    with open(output_pth, "w+", encoding="utf-8") as out_file:
        out_file.writelines(json.dumps(group))
    #print(group)

    return 0


#! /usr/bin/python3

import subprocess
import sys
import os

# TODO. Check if all requirments are installed: qemu cu strace ,file, etc.

CORES_DIR = "tests/cores/"

lib_paths = {
        "arm32_dynamic_core"         : "/usr/arm-linux-gnueabihf/",
        "arm64_dynamic_core"         : "/usr/aarch64-linux-gnu/",
        "i386_dynamic_core"          : "/usr/lib32",
        "mips32_dynamic_LSB_core"    : "/usr/mipsel-linux-gnu",
        "mips32_dynamic_MSB_core"    : "/usr/mips-linux-gnu",
        "mips64_dynamic_LSB_core"    : "/usr/mips64el-linux-gnuabi64",
        "x86-64_dynamic_core"        : "/usr/lib64"
}

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

    @staticmethod
    def get_ok():
        return bcolors.OKGREEN + "[PASSED]" + bcolors.ENDC

    @staticmethod
    def get_fail():
        return bcolors.FAIL + "[FAILED]" + bcolors.ENDC

    @staticmethod
    def new_test(name):
        return bcolors.OKBLUE + ("[TEST] Test for file %s" % (name)) + bcolors.ENDC

    @staticmethod
    def log(msg):
        string = ""
        if (msg[0] == True):
            string = bcolors.get_ok()
        else:
            string = bcolors.get_fail()

        print("%s %s" % (string, msg[1]))

def get_qemu_env(name):
    print(name)
    print(lib_paths.keys())
    if name in lib_paths.keys():
        return lib_paths[name]
    return ""

def run_file(path):
	proc = subprocess.Popen(["file", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	out = proc.communicate()[0]

	if proc.returncode != 0:
		return (False, "File did not return 0. Code: %d" % (proc.returncode))

	if b"ELF" not in out:
		return (False, "Invalid file output. Message: %s" % (out))

	return (True, out)

def run_readelf(path):
	proc = subprocess.Popen(["readelf", "-a", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	out = proc.communicate()[0]

	if proc.returncode != 0:
		return (False, "File did not return 0. Code: %d" % (proc.returncode))

	if b"ELF" not in out:
		return (False, "Invalid readelf output. Message: %s" % (out))

	if b"Warning" in out or b"Error" in out:
		return (False, "Found warnings/errors in readelf output. Message %s" (out))

	return (True, 'Readelf passed')

def run_program(path, core):
        menv = os.environ.copy()
        menv["QEMU_LD_PREFIX"] = get_qemu_env(os.path.basename(core))
        proc = subprocess.Popen([path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=menv)
        out = proc.communicate()[0]
        print(menv["QEMU_LD_PREFIX"])
        if proc.returncode != 42:
            return (False, "File did not return 42. Code: %d" % (proc.returncode))

        if b"Hello world" not in out:
            return (False, "Invalid program output. Message: %s" % (out))

        return (True, 'Running passed')

def run_reconstruction(core, result):
	proc = subprocess.Popen(["./core2elf", core, "-o", result], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
	proc.communicate()

	if os.path.exists(result) is False:
		return (False, "Could not reconstruct file")

	os.chmod(result, 0o777)
	return (True, "Reconstrution done.")

def run_test(path):
    opath = os.path.abspath("elf.out")
    try:
        r = run_reconstruction(path, opath)
        bcolors.log(r)
    except:
        bcolors.log((False, "Exception in reconstruction"))
    try:
        r = run_file(opath)
        bcolors.log(r)
    except:
        bcolors.log((False, "Exception in file"))
    try:
        r = run_readelf(opath)
        bcolors.log(r)
    except:
        bcolors.log((False, "Exception in readelf"))
    try:
        r = run_program(opath, core)
        bcolors.log(r)
    except Exception as e:
        print(e)
        bcolors.log((False, "Exception in run_program"))

#run_test("tests/cores/x86-64_static_core")
if __name__ == "__main__":
    cores_abs_path = os.path.abspath(CORES_DIR)
    cores = os.listdir(cores_abs_path)
    for core in cores:
        path = os.path.join(cores_abs_path, core)
        print(bcolors.new_test(core))
        run_test(path)
        print("")


class SudokuBoard:
    """"
        loads sudoku puzzle configuration from file
    """

    def __init__(self, file_name):
        self.puzzle = self.load_puzzle(file_name)

    def load_puzzle(self, file_name):
        """
        Function loads a puzzle configuration from a file
        :param file_name: str
        :return: list of lists. size: 9 x 9
        """
        file_id = open(file_name, 'r')
        line_list = file_id.readlines()
        matrix = []
        row_counter = 0

        for line in line_list:
            column_counter = 0
            row = []
            for element in line.split():
                if element.isdigit() and 0 <= int(element) < 10:
                    row.append(int(element))
                    column_counter += 1
            if column_counter != 9:
                raise ValueError("Error: input file cannot create puzzle. Needed 9X9 matrix in the file")
            matrix.append(row)
            row_counter += 1
            if row_counter > 9:
                raise ValueError("Error: input file cannot create puzzle. Needed 9X9 matrix int the file")

        file_id.close()
        return matrix

    def is_cell_empty(self, row, col):
        """
        Function checks if the cell at (row, column) in the puzzle doesn't contain a number
        :param row: int. range 0 - 8.
        :param col: int. range 0 - 8
        :return: True only if the cell is empty.
        """
        return not self.puzzle[row][col]


import unittest
import unittest
from unittest.signals import installHandler
from ciscoepnmclient.models import EpnmModelStructure

class TestEpnmModelStructure(unittest.TestCase):

    TEST_CLASS = EpnmModelStructure

    _REQUIRED_FIELD_NAMES = [x[0] for x in TEST_CLASS._required_fields]
    _OPTIONAL_FIELD_NAMES = [x[0] for x in TEST_CLASS._optional_fields]

    def test_init(self):
        instance = self.TEST_CLASS()
        self.assertIsInstance(instance, self.TEST_CLASS)

    def test_is_subclass(self):
        self.assertTrue(
            issubclass(self.TEST_CLASS, EpnmModelStructure)
        )

    def test_has_to_dict(self):
        self.assertTrue(
            callable(
                getattr(self.TEST_CLASS, "to_dict")
            )
        )

    def test_has_from_dict(self):
        self.assertTrue(
            callable(
                getattr(self.TEST_CLASS, "from_dict")
            )
        )

    def test_fields_have_dict_mapping(self):
        all_fields = set()
        all_fields.update([x[0] for x in self.TEST_CLASS._required_fields])
        all_fields.update([x[0] for x in self.TEST_CLASS._optional_fields])

        dict_field_keys = set(self.TEST_CLASS._dict_fields.keys())
        self.assertSetEqual(all_fields, dict_field_keys)

    def test_field_is_defined_once(self):
        required_fields = set([x[0] for x in self.TEST_CLASS._required_fields])
        optional_fields = set([x[0] for x in self.TEST_CLASS._optional_fields])
        self.assertTrue(required_fields.isdisjoint(optional_fields))

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


import subprocess
import logging
import re
from typing import Dict, List, Optional, Set, Tuple  # noqa

logger = logging.getLogger(__name__)

def parse_section_to_dictionary(section: str) -> Dict:
    # Nmap scan report for 192.168.0.65
    # Host is up (0.00022s latency).
    # Not shown: 998 closed ports
    # PORT     STATE SERVICE
    # 22/tcp   open  ssh
    # 5900/tcp open  vnc
    # MAC Address: DC:A6:32:C5:94:AD (Raspberry Pi Trading)
    ipv4_pattern = r'((\d{1,3}\.){3}\d{1,3})'
    matches = re.search(ipv4_pattern, section)
    ipv4 = matches.group(0)
    logger.debug(f"ipv4: {ipv4}")
    mac_addr_pattern = r'([0-9A-F]{2}:){5}[0-9A-F]{2}'
    matches = re.search(mac_addr_pattern, section, re.MULTILINE | re.IGNORECASE)
    mac_addr = matches.group(0)
    logger.debug(f"mac_addr: {mac_addr}")
    parsed_section = {
        'ipv4': ipv4,
        'mac_addr': mac_addr,
        'content': section,
    }
    return parsed_section

def search_using_nmap(ipv4: str, mask: int, filter: [str]) -> List[Dict]:
    logger.debug(f"ipv4: {ipv4}")
    logger.debug(f"mask: {mask}")
    logger.debug(f"filter: {filter}")
    cmd = f"sudo nmap {ipv4}/{mask}"
    logger.debug(f"cmd: {cmd}")
    output = subprocess.getoutput(cmd)
    sections = [section for section in output.split("\n\n")]
    results = []
    for section in sections:
        for item in filter:
            if item in section:
                results.append(parse_section_to_dictionary(section))
                break
    return results


def extractJunktranslatesWordpressCom(item):
	'''
	Parser for 'junktranslates.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('intl',       'It’s Not Too Late to Meet Again After Rebirth',                      'translated'),
		('smwom',      'Second Marriage of a Wealthy Old Man',                      'translated'),
		('rolm',       'Reborn Out of Love and Murder',                      'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


#success
N, K = map(int, input().split())
string = list(input())
# print(string)

i = 0
cnt = 0

stack = []

for i in range(len(string)):
    if i != 0:
        while stack:
            if cnt == K:
                break
            value =  stack.pop()
            if value < string[i]:
                cnt += 1
            else:
                stack.append(value)
                break
    stack.append(string[i])

while cnt != K:
    stack.pop()
    cnt += 1

for i in stack:
    print(i, end="")
print()


import numpy as np
from keras.layers import Dense
from keras.optimizers import Adam
from keras.models import Sequential
from collections import deque
from random import *
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic

# agent 안의 build_model을 가져온다
def build_model():
	model = Sequential()
	model.add(Dense(10, input_dim = 1, activation = 'relu', kernel_initializer = 'he_uniform'))
	model.add(Dense(10, activation = 'relu', kernel_initializer = 'he_uniform'))
	model.add(Dense(2, activation = 'linear', kernel_initializer = 'he_uniform'))
	model.compile(loss = 'mse', optimizer = Adam(lr = 0.001))
	return model

form_class = uic.loadUiType("holl.ui")[0]

# gameEnv
class WindowClass(QMainWindow, form_class) :
	def __init__(self) :
		self.score = 0
		self.seq = 0
		super().__init__()
		self.setupUi(self)
		self.hol.clicked.connect(self.hol_click)
		self.jjak.clicked.connect(self.jjak_click)

	def hol_click(self) :
		self.select(0)

	def jjak_click(self):
		self.select(1)

	def select(self, mine):
		model = build_model()
		model.summary()

		# 신경망에 넣어서 결과를 봐야하므로 numpy로 만든다 (주식 예제 생각하기)
		numpy_mine = np.array([mine])
		numpy_mine = np.reshape(numpy_mine, [1, 1])
		# 인공지능의 출력을 받는다
		numpy_mine = np.float32(numpy_mine)
		# 내가 낸것도 컴퓨터가 만들어준다
		q_values = model.predict(numpy_mine)
		com = np.argmax(q_values[0])

		self.seq += 1

		# 데이터 출력
		if mine == 0:
			self.myselect.setText("홀")
			print("홀")
		elif mine == 1:
			self.myselect.setText("짝")
		if com == 0:
			self.comselect.setText("홀")
			print("컴 : 홀")
		elif com == 1:
			print("컴 : 짝")
			self.comselect.setText("짝")

		# 결과 출력
		if mine == com :
			self.score += 1
			self.result.setText("이겼습니다.")
		else :
			self.result.setText("졌습니다.")

		self.jumsu.setText(str(self.score))
		self.sequence.setText(str(self.seq))

#

if __name__ == "__main__":
	app = QApplication(sys.argv)
	myWindow = WindowClass()
	myWindow.show()
	app.exec_()


import sys
import traceback
import types
import warnings

from eventlet.support import greenlets as greenlet
import six
from eventlet.hubs.hub import BaseHub, READ, WRITE

try:
    import event
except ImportError:
    event = None

def is_available():
    return event is not None

class event_wrapper(object):

    def __init__(self, impl=None, seconds=None):
        self.impl = impl
        self.seconds = seconds

    def __repr__(self):
        if self.impl is not None:
            return repr(self.impl)
        else:
            return object.__repr__(self)

    def __str__(self):
        if self.impl is not None:
            return str(self.impl)
        else:
            return object.__str__(self)

    def cancel(self):
        if self.impl is not None:
            self.impl.delete()
            self.impl = None

    @property
    def pending(self):
        return bool(self.impl and self.impl.pending())

class Hub(BaseHub):

    SYSTEM_EXCEPTIONS = (KeyboardInterrupt, SystemExit)

    def __init__(self):
        super(Hub, self).__init__()
        event.init()

        self.signal_exc_info = None
        self.signal(
            2,
            lambda signalnum, frame: self.greenlet.parent.throw(KeyboardInterrupt))
        self.events_to_add = []

        warnings.warn(
            "ACTION REQUIRED eventlet pyevent hub is deprecated and will be removed soon",
            DeprecationWarning,
        )

    def dispatch(self):
        loop = event.loop
        while True:
            for e in self.events_to_add:
                if e is not None and e.impl is not None and e.seconds is not None:
                    e.impl.add(e.seconds)
                    e.seconds = None
            self.events_to_add = []
            result = loop()

            if getattr(event, '__event_exc', None) is not None:
                # only have to do this because of bug in event.loop
                t = getattr(event, '__event_exc')
                setattr(event, '__event_exc', None)
                assert getattr(event, '__event_exc') is None
                six.reraise(t[0], t[1], t[2])

            if result != 0:
                return result

    def run(self):
        while True:
            try:
                self.dispatch()
            except greenlet.GreenletExit:
                break
            except self.SYSTEM_EXCEPTIONS:
                raise
            except:
                if self.signal_exc_info is not None:
                    self.schedule_call_global(
                        0, greenlet.getcurrent().parent.throw, *self.signal_exc_info)
                    self.signal_exc_info = None
                else:
                    self.squelch_timer_exception(None, sys.exc_info())

    def abort(self, wait=True):
        self.schedule_call_global(0, self.greenlet.throw, greenlet.GreenletExit)
        if wait:
            assert self.greenlet is not greenlet.getcurrent(
            ), "Can't abort with wait from inside the hub's greenlet."
            self.switch()

    def _getrunning(self):
        return bool(self.greenlet)

    def _setrunning(self, value):
        pass  # exists for compatibility with BaseHub
    running = property(_getrunning, _setrunning)

    def add(self, evtype, fileno, real_cb, real_tb, mac):
        # this is stupid: pyevent won't call a callback unless it's a function,
        # so we have to force it to be one here
        if isinstance(real_cb, types.BuiltinMethodType):
            def cb(_d):
                real_cb(_d)
        else:
            cb = real_cb

        if evtype is READ:
            evt = event.read(fileno, cb, fileno)
        elif evtype is WRITE:
            evt = event.write(fileno, cb, fileno)

        return super(Hub, self).add(evtype, fileno, evt, real_tb, mac)

    def signal(self, signalnum, handler):
        def wrapper():
            try:
                handler(signalnum, None)
            except:
                self.signal_exc_info = sys.exc_info()
                event.abort()
        return event_wrapper(event.signal(signalnum, wrapper))

    def remove(self, listener):
        super(Hub, self).remove(listener)
        listener.cb.delete()

    def remove_descriptor(self, fileno):
        for lcontainer in six.itervalues(self.listeners):
            listener = lcontainer.pop(fileno, None)
            if listener:
                try:
                    listener.cb.delete()
                except self.SYSTEM_EXCEPTIONS:
                    raise
                except:
                    traceback.print_exc()

    def schedule_call_local(self, seconds, cb, *args, **kwargs):
        current = greenlet.getcurrent()
        if current is self.greenlet:
            return self.schedule_call_global(seconds, cb, *args, **kwargs)
        event_impl = event.event(_scheduled_call_local, (cb, args, kwargs, current))
        wrapper = event_wrapper(event_impl, seconds=seconds)
        self.events_to_add.append(wrapper)
        return wrapper

    schedule_call = schedule_call_local

    def schedule_call_global(self, seconds, cb, *args, **kwargs):
        event_impl = event.event(_scheduled_call, (cb, args, kwargs))
        wrapper = event_wrapper(event_impl, seconds=seconds)
        self.events_to_add.append(wrapper)
        return wrapper

    def _version_info(self):
        baseversion = event.__version__
        return baseversion

def _scheduled_call(event_impl, handle, evtype, arg):
    cb, args, kwargs = arg
    try:
        cb(*args, **kwargs)
    finally:
        event_impl.delete()

def _scheduled_call_local(event_impl, handle, evtype, arg):
    cb, args, kwargs, caller_greenlet = arg
    try:
        if not caller_greenlet.dead:
            cb(*args, **kwargs)
    finally:
        event_impl.delete()


#035: ler tres retas e determinar se pode ou n formar um triangulo:

'''
Só irá existir um triângulo se, somente se, os seus lados obedeceram à seguinte regra:
um de seus lados deve ser maior  que o valor absoluto (módulo) da diferença dos outros
dois lados e menor que a soma dos outros dois lados.
Veja o resumo da regra abaixo:

| b - c | < a < b + c
| a - c | < b < a + c
| a - b | < c < a + b
'''

print("--- TRIANGULO ---")
a = int(input("Digite o 1o. valor: "))
b = int(input("Digite o 2o. valor: "))
c = int(input("Digite o 3o. valor: "))

if a < b + c and b < a + c and c < a + b:
    print("Esses valores podem formar um triângulo")
else:
    print("Esses valores não podem formar um triângulo")


from __future__ import print_function, division
from ciabatta import ejm_rcparams
import matplotlib.pyplot as plt
import numpy as np

def seg_intersect(p1, p2, yi):
    x1, y1 = p1
    x2, y2 = p2
    m = (y2 - y1) / (x2 - x1)
    c = y1 - m * x1
    xi = (yi - c) / m
    if x1 < xi < x2:
        return xi
    else:
        raise ValueError

def curve_intersect(xs, ys, yi):
    i_big = np.where(ys > yi)[0][0]
    p1 = [xs[i_big - 1], ys[i_big - 1]]
    p2 = [xs[i_big], ys[i_big]]
    return seg_intersect(p1, p2, yi)

vd_0 = 0.25

d = np.load('free_space_drift_curve.npz')
(chi_r_s, vd_r_s, vde_r_s,
 chi_a_s, vd_a_s, vde_a_s,
 chi_r_t, vd_r_t, vde_r_t,
 chi_a_t, vd_a_t, vde_a_t) = (d['chi_r_s'], d['vd_r_s'], d['vde_r_s'],
                              d['chi_a_s'], d['vd_a_s'], d['vde_a_s'],
                              d['chi_r_t'], d['vd_r_t'], d['vde_r_t'],
                              d['chi_a_t'], d['vd_a_t'], d['vde_a_t'])

plt.axhline(vd_0)
for i, vset in enumerate(([chi_r_s, vd_r_s, vde_r_s],
                          [chi_a_s, vd_a_s, vde_a_s],
                          [chi_r_t, vd_r_t, vde_r_t],
                          [chi_a_t, vd_a_t, vde_a_t])):
    chi, vd, vde = vset
    plt.errorbar(chi, vd, yerr=vde, c=ejm_rcparams.set2[i])
    chi_0 = curve_intersect(chi, vd, vd_0)
    plt.axvline(chi_0, c=ejm_rcparams.set2[i])
    print(chi_0)

plt.show()


# -*- encoding: utf-8 -*-

from __future__ import unicode_literals, absolute_import
import argparse
import atexit
import functools
import json
import sys
import letsencrypt
import os
import zope.component
from letsencrypt import (
    cli,
    configuration,
    constants,
    interfaces,
    le_util,
    reporter,
)
from letsencrypt.cli import (
    flag_default,
    config_help,
    logger,
    _handle_exception,
    _cli_log_handler,
    setup_logging,
    HelpfulArgumentParser as OriginalHelpfulArgumentParser,
    DomainFlagProcessor,
    read_file,
    WebrootPathProcessor,
)
from letsencrypt.display import util as display_util
from letsencrypt.plugins import disco as plugins_disco
from .cmd.gencsr import gencsr
from .cmd.run import run
from .cmd.obtain_cert import obtain_cert

ARGUMENT_PARSER_VERBS = OriginalHelpfulArgumentParser.VERBS.copy()
ARGUMENT_PARSER_VERBS.update(
    auth=obtain_cert,
    certonly=obtain_cert,
    everything=run,
    gencsr=gencsr,
    run=run,
)
ARGUMENT_HELP_TOPICS = OriginalHelpfulArgumentParser.HELP_TOPICS[:]
ARGUMENT_HELP_TOPICS = ARGUMENT_HELP_TOPICS + [
    key for key in ARGUMENT_PARSER_VERBS.keys()
    if key not in ARGUMENT_HELP_TOPICS
    ]

class HelpfulArgumentParser(OriginalHelpfulArgumentParser):
    """Argparse Wrapper.

    This class wraps argparse, adding the ability to make --help less
    verbose, and request help on specific subcategories at a time, eg
    'letsencrypt --help security' for security options.

    Changes the original entry to be able to use a pre existing key.
    """

    # Maps verbs/subcommands to the functions that implement them
    VERBS = ARGUMENT_PARSER_VERBS

    # List of topics for which additional help can be provided
    HELP_TOPICS = ARGUMENT_HELP_TOPICS

def prepare_and_parse_args(plugins, args):
    """Returns parsed command line arguments.

    :param .PluginsRegistry plugins: available plugins
    :param list args: command line arguments with the program name removed

    :returns: parsed command line arguments
    :rtype: argparse.Namespace

    """
    helpful = HelpfulArgumentParser(args, plugins)

    # --help is automatically provided by argparse
    helpful.add(
        None, "-v", "--verbose", dest="verbose_count", action="count",
        default=flag_default("verbose_count"),
        help="This flag can be used multiple times to incrementally increase the verbosity of output, "
             "e.g. -vvv."
    )
    helpful.add(
        None, "-t", "--text", dest="text_mode", action="store_true",
        help="Use the text output instead of the curses UI."
    )
    helpful.add(
        None, "--register-unsafely-without-email", action="store_true",
        help="Specifying this flag enables registering an account with no "
             "email address. This is strongly discouraged, because in the "
             "event of key loss or account compromise you will irrevocably "
             "lose access to your account. You will also be unable to receive "
             "notice about impending expiration of revocation of your "
             "certificates. Updates to the Subscriber Agreement will still "
             "affect you, and will be effective 14 days after posting an "
             "update to the web site."
    )
    helpful.add(None, "-m", "--email", help=config_help("email"))
    # positional arg shadows --domains, instead of appending, and
    # --domains is useful, because it can be stored in config
    # for subparser in parser_run, parser_auth, parser_install:
    #    subparser.add_argument("domains", nargs="*", metavar="domain")
    helpful.add(None, "-d", "--domains", "--domain", dest="domains",
                metavar="DOMAIN", action=DomainFlagProcessor, default=[],
                help="Domain names to apply. For multiple domains you can use "
                     "multiple -d flags or enter a comma separated list of domains "
                     "as a parameter.")
    helpful.add(
        None, "--duplicate", dest="duplicate", action="store_true",
        help="Allow getting a certificate that duplicates an existing one")

    helpful.add_group(
        "automation",
        description="Arguments for automating execution & other tweaks")
    helpful.add(
        "automation", "--version", action="version",
        version="%(prog)s {0}".format(letsencrypt.__version__),
        help="show program's version number and exit")
    helpful.add(
        "automation", "--renew-by-default", action="store_true",
        help="Select renewal by default when domains are a superset of a "
             "previously attained cert")
    helpful.add(
        "automation", "--agree-tos", dest="tos", action="store_true",
        help="Agree to the Let's Encrypt Subscriber Agreement")
    helpful.add(
        "automation", "--account", metavar="ACCOUNT_ID",
        help="Account ID to use")

    helpful.add_group(
        "testing", description="The following flags are meant for "
                               "testing purposes only! Do NOT change them, unless you "
                               "really know what you're doing!")
    helpful.add(
        "testing", "--debug", action="store_true",
        help="Show tracebacks in case of errors, and allow letsencrypt-auto "
             "execution on experimental platforms")
    helpful.add(
        "testing", "--no-verify-ssl", action="store_true",
        help=config_help("no_verify_ssl"),
        default=flag_default("no_verify_ssl"))
    helpful.add(
        "testing", "--tls-sni-01-port", type=int,
        default=flag_default("tls_sni_01_port"),
        help=config_help("tls_sni_01_port"))
    helpful.add(
        "testing", "--http-01-port", type=int, dest="http01_port",
        default=flag_default("http01_port"), help=config_help("http01_port"))

    helpful.add_group(
        "security", description="Security parameters & server settings")
    helpful.add(
        "security", "--rsa-key-size", type=int, metavar="N",
        default=flag_default("rsa_key_size"), help=config_help("rsa_key_size"))
    helpful.add(
        "security", "--redirect", action="store_true",
        help="Automatically redirect all HTTP traffic to HTTPS for the newly "
             "authenticated vhost.", dest="redirect", default=None)
    helpful.add(
        "security", "--no-redirect", action="store_false",
        help="Do not automatically redirect all HTTP traffic to HTTPS for the newly "
             "authenticated vhost.", dest="redirect", default=None)
    helpful.add(
        "security", "--hsts", action="store_true",
        help="Add the Strict-Transport-Security header to every HTTP response."
             " Forcing browser to use always use SSL for the domain."
             " Defends against SSL Stripping.", dest="hsts", default=False)
    helpful.add(
        "security", "--no-hsts", action="store_false",
        help="Do not automatically add the Strict-Transport-Security header"
             " to every HTTP response.", dest="hsts", default=False)
    helpful.add(
        "security", "--uir", action="store_true",
        help="Add the \"Content-Security-Policy: upgrade-insecure-requests\""
             " header to every HTTP response. Forcing the browser to use"
             " https:// for every http:// resource.", dest="uir", default=None)
    helpful.add(
        "security", "--no-uir", action="store_false",
        help=" Do not automatically set the \"Content-Security-Policy:"
             " upgrade-insecure-requests\" header to every HTTP response.",
        dest="uir", default=None)
    helpful.add(
        "security", "--strict-permissions", action="store_true",
        help="Require that all configuration files are owned by the current "
             "user; only needed if your config is somewhere unsafe like /tmp/")

    helpful.add_deprecated_argument("--agree-dev-preview", 0)

    _create_subparsers(helpful)
    _paths_parser(helpful)
    # _plugins_parsing should be the last thing to act upon the main
    # parser (--help should display plugin-specific options last)
    _plugins_parsing(helpful, plugins)

    return helpful.parse_args()

def _create_subparsers(helpful):
    helpful.add_group("certonly", description="Options for modifying how a cert is obtained")
    helpful.add_group("gencsr", description="Generates a CSR file for the passed domains")
    helpful.add_group("install", description="Options for modifying how a cert is deployed")
    helpful.add_group("revoke", description="Options for revocation of certs")
    helpful.add_group("rollback", description="Options for reverting config changes")
    helpful.add_group("plugins", description="Plugin options")
    helpful.add(
        None, "--user-agent", default=None,
        help="Set a custom user agent string for the client. User agent strings allow "
             "the CA to collect high level statistics about success rates by OS and "
             "plugin. If you wish to hide your server OS version from the Let's "
             'Encrypt server, set this to "".')
    helpful.add("certonly",
                "--csr", type=read_file,
                help="Path to a Certificate Signing Request (CSR) in DER"
                     " format; note that the .csr file *must* contain a Subject"
                     " Alternative Name field for each domain you want certified.")
    helpful.add("certonly",
                "--key",
                "--private-key", type=read_file,
                help="The path of the certificate",
                dest='private_key'
                )
    helpful.add("gencsr",
                "--out", type=str,
                help='The file location the csr should be exported to.',
                dest='out')
    helpful.add("rollback",
                "--checkpoints", type=int, metavar="N",
                default=flag_default("rollback_checkpoints"),
                help="Revert configuration N number of checkpoints.")
    helpful.add("plugins",
                "--init", action="store_true", help="Initialize plugins.")
    helpful.add("plugins",
                "--prepare", action="store_true", help="Initialize and prepare plugins.")
    helpful.add("plugins",
                "--authenticators", action="append_const", dest="ifaces",
                const=interfaces.IAuthenticator, help="Limit to authenticator plugins only.")
    helpful.add("plugins",
                "--installers", action="append_const", dest="ifaces",
                const=interfaces.IInstaller, help="Limit to installer plugins only.")

def _paths_parser(helpful):
    add = helpful.add
    verb = helpful.verb
    if verb == "help":
        verb = helpful.help_arg
    helpful.add_group(
        "paths", description="Arguments changing execution paths & servers")

    cph = "Path to where cert is saved (with auth --csr), installed from or revoked."
    section = "paths"
    if verb in ("install", "revoke", "certonly"):
        section = verb
    if verb == "certonly":
        add(section, "--cert-path", type=os.path.abspath,
            default=flag_default("auth_cert_path"), help=cph)
    elif verb == "revoke":
        add(section, "--cert-path", type=read_file, required=True, help=cph)
    else:
        add(section, "--cert-path", type=os.path.abspath,
            help=cph, required=(verb == "install"))

    section = "paths"
    if verb in ("install", "revoke"):
        section = verb
    # revoke --key-path reads a file, install --key-path takes a string
    add(section, "--key-path", required=(verb == "install"),
        type=((verb == "revoke" and read_file) or os.path.abspath),
        help="Path to private key for cert installation "
             "or revocation (if account key is missing)")

    default_cp = None
    if verb == "certonly":
        default_cp = flag_default("auth_chain_path")
    add("paths", "--fullchain-path", default=default_cp, type=os.path.abspath,
        help="Accompanying path to a full certificate chain (cert plus chain).")
    add("paths", "--chain-path", default=default_cp, type=os.path.abspath,
        help="Accompanying path to a certificate chain.")
    add("paths", "--config-dir", default=flag_default("config_dir"),
        help=config_help("config_dir"))
    add("paths", "--work-dir", default=flag_default("work_dir"),
        help=config_help("work_dir"))
    add("paths", "--logs-dir", default=flag_default("logs_dir"),
        help="Logs directory.")
    add("paths", "--server", default=flag_default("server"),
        help=config_help("server"))

def _plugins_parsing(helpful, plugins):
    helpful.add_group(
        "plugins", description="Let's Encrypt client supports an "
                               "extensible plugins architecture. See '%(prog)s plugins' for a "
                               "list of all installed plugins and their names. You can force "
                               "a particular plugin by setting options provided below. Further "
                               "down this help message you will find plugin-specific options "
                               "(prefixed by --{plugin_name}).")
    helpful.add(
        "plugins", "-a", "--authenticator", help="Authenticator plugin name.")
    helpful.add(
        "plugins", "-i", "--installer", help="Installer plugin name (also used to find domains).")
    helpful.add(
        "plugins", "--configurator", help="Name of the plugin that is "
                                          "both an authenticator and an installer. Should not be used "
                                          "together with --authenticator or --installer.")
    helpful.add("plugins", "--apache", action="store_true",
                help="Obtain and install certs using Apache")
    helpful.add("plugins", "--nginx", action="store_true",
                help="Obtain and install certs using Nginx")
    helpful.add("plugins", "--standalone", action="store_true",
                help='Obtain certs using a "standalone" webserver.')
    helpful.add("plugins", "--manual", action="store_true",
                help='Provide laborious manual instructions for obtaining a cert')
    helpful.add("plugins", "--webroot", action="store_true",
                help='Obtain certs by placing files in a webroot directory.')

    # things should not be reorder past/pre this comment:
    # plugins_group should be displayed in --help before plugin
    # specific groups (so that plugins_group.description makes sense)

    helpful.add_plugin_args(plugins)

    # These would normally be a flag within the webroot plugin, but because
    # they are parsed in conjunction with --domains, they live here for
    # legibiility. helpful.add_plugin_ags must be called first to add the
    # "webroot" topic
    helpful.add("webroot", "-w", "--webroot-path", action=WebrootPathProcessor,
                help="public_html / webroot path. This can be specified multiple times to "
                     "handle different domains; each domain will have the webroot path that"
                     " preceded it.  For instance: `-w /var/www/example -d example.com -d "
                     "www.example.com -w /var/www/thing -d thing.net -d m.thing.net`")
    parse_dict = lambda s: dict(json.loads(s))
    # --webroot-map still has some awkward properties, so it is undocumented
    helpful.add("webroot", "--webroot-map", default={}, type=parse_dict,
                help=argparse.SUPPRESS)

def init_key_arguments(parser):
    """
    :type parser: ArgumentParser
    """
    parser.add_argument(
        '--key',
        type=str,
        help='The private key the csr should be generated for.',
        dest='key',
    )
    parser.add_argument(
        '-d', '--domain',
        type=str,
        dest='domains',
        nargs='+',
    )
    return parser

def patch_readme_data(usage):
    gencsr_readme = '  gencsr               Generates for the domains and a private key a csr'
    usage_lines = usage.split('\n')
    index_candidates = [
        index for index, usage_line in enumerate(usage_lines)
        if usage_line.strip().startswith('plugins') and usage_line.startswith('  ')
        ]
    index = index_candidates[0]
    usage_lines = usage_lines[:index] + [gencsr_readme] + usage_lines[index:]
    return '\n'.join(usage_lines)

def patch_readme():
    """
    patches the original readme files of letsencrypt to
    include the new gencsr command.
    """
    cli.SHORT_USAGE = patch_readme_data(cli.SHORT_USAGE)
    cli.USAGE = patch_readme_data(cli.USAGE)

def main(cli_args=sys.argv[1:]):
    """Command line argument parsing and main script execution."""
    patch_readme()

    sys.excepthook = functools.partial(_handle_exception, args=None)

    # note: arg parser internally handles --help (and exits afterwards)
    plugins = plugins_disco.PluginsRegistry.find_all()
    args = prepare_and_parse_args(plugins, cli_args)
    config = configuration.NamespaceConfig(args)
    zope.component.provideUtility(config)

    # Setup logging ASAP, otherwise "No handlers could be found for
    # logger ..." TODO: this should be done before plugins discovery
    for directory in config.config_dir, config.work_dir:
        le_util.make_or_verify_dir(
            directory, constants.CONFIG_DIRS_MODE, os.geteuid(),
            "--strict-permissions" in cli_args)
    # TODO: logs might contain sensitive data such as contents of the
    # private key! #525
    le_util.make_or_verify_dir(
        args.logs_dir, 0o700, os.geteuid(), "--strict-permissions" in cli_args)
    setup_logging(args, _cli_log_handler, logfile='letsencrypt.log')

    logger.debug("letsencrypt version: %s", letsencrypt.__version__)
    # do not log `args`, as it contains sensitive data (e.g. revoke --key)!
    logger.debug("Arguments: %r", cli_args)
    logger.debug("Discovered plugins: %r", plugins)

    sys.excepthook = functools.partial(_handle_exception, args=args)

    # Displayer
    if args.text_mode:
        displayer = display_util.FileDisplay(sys.stdout)
    else:
        displayer = display_util.NcursesDisplay()
    zope.component.provideUtility(displayer)

    # Reporter
    report = reporter.Reporter()
    zope.component.provideUtility(report)
    atexit.register(report.atexit_print_messages)

    if not os.geteuid() == 0:
        logger.warning(
            "Root (sudo) is required to run most of letsencrypt functionality.")
        # check must be done after arg parsing as --help should work
        # w/o root; on the other hand, e.g. "letsencrypt run
        # --authenticator dns" or "letsencrypt plugins" does not
        # require root as well
        # return (
        #    "{0}Root is required to run letsencrypt.  Please use sudo.{0}"
        #    .format(os.linesep))

    return args.func(args, config, plugins)

if __name__ == "__main__":
    err_string = main()
    if err_string:
        logger.warn("Exiting with message %s", err_string)
    sys.exit(err_string)  # pragma: no cover


#!/usr/bin/env python3
# -*- coding utf-8 -*-

import openai, yaml

"""
根据提示，生成代码
根据提示，生成单元测试代码
"""

def get_api_key():
    with open("config.yaml", "r", encoding="utf-8") as yaml_file:
        yaml_data = yaml.safe_load(yaml_file)
        openai.api_key = yaml_data["openai"]["api_key"]

# gpt封装
def gpt35(prompt, model="text-davinci-002", temperature=0.4, max_tokens=1000,
          top_p=1, stop=["\n\n", "\n\t\n", "\n    \n"]):
    response = openai.Completion.create(
        model=model,
        prompt = prompt,
        temperature = temperature,
        max_tokens = max_tokens,
        top_p = top_p,
        stop = stop
        )
    message = response["choices"][0]["text"]
    return message

# 按要求生成一段代码
def try_copilot():
    prompt = """
用Python写一个函数，进行时间格式化输出，比如：
输入  输出
1    1s
61    1min1s
要求仅需要格式化到小时(?h?min?s)，即可
"""
    response = gpt35(prompt)
    return response, prompt

"""
def format_time(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)

    if hours > 0:
        return f"{hours}h{minutes}min{seconds}s"
    elif minutes > 0:
        return f"{minutes}min{seconds}s"
    else:
        return f"{seconds}s"
"""

# 按要求生成一段代码
def try_copilot_uint_test():
    prompt = """
可以用一下的Python代码实现时间格式化输出：

def format_time(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)

    if hours > 0:
        return f"{hours}h{minutes}min{seconds}s"
    elif minutes > 0:
        return f"{minutes}min{seconds}s"
    else:
        return f"{seconds}s"

请为这个程序用pytest写一个单元测试
"""
    response = gpt35(prompt)
    return response, prompt

"""
import pytest

def test_format_time():
    assert format_time(1) == "1s"
    assert format_time(59) == "59s"
    assert format_time(60) == "1min0s"
    assert format_time(61) == "1min1s"
    assert format_time(3600) == "1h0min0s"
    assert format_time(3661) == "1h1min1s"
"""

if __name__ == '__main__':
    get_api_key()

    # 用chatgpt生成一段代码
    code = try_copilot()
    print(code)

    # 用chatgpt生成单元测试
    test_code = try_copilot_uint_test()
    print(test_code)


class Solution(object):
    def partition(self, head, x):
        if not head:
            return None
        lessList = ListNode(0)
        greaterList = ListNode(0)
        less = lessList
        greater = greaterList
        while head:
            nextNode = head.next
            if head.val < x:
                lessList.next = head
                lessList.next.next = None
                lessList = head
            else:
                greaterList.next = head
                greaterList.next.next = None
                greaterList = head
            head = nextNode
        if not less.next:
            return greater.next
        else:
            lessList.next = greater.next
            return less.next


import os
import sys
from glob import glob
import xml.etree.ElementTree as ET
from typing import List, Union
import numpy as np
from PIL import Image
from tqdm import tqdm

def train_valid_split(
    path: str = './data/train/', test_size: float = 0.1, shuffle: bool = True) -> List:
    """
    베이스라인 코드가 정말 별로라 새로 데이터 분할 후 .xml 파일 생성
    """
    all_files = list(glob(path + '*jpg')) + list(glob(path + '*png'))
    print(f'Total dataset: {len(all_files)}...')

    split_index = int(len(all_files)*(1-test_size))
    if shuffle:
        shuffled_index = np.random.permutation(len(all_files))
    else:
        shuffled_index = np.arange(len(all_files))

    train_index = shuffled_index[:split_index]
    valid_index = shuffled_index[split_index:]
    all_files = np.asarray(all_files)

    return list(all_files[train_index]), list(all_files[valid_index])

def xml_parser(
    train_list: List[str], valid_list: List[str]) -> ET.XML:
    """
    대회 서버 내 데이터셋 레이블 파일 문제로 인해 예외처리해야 함
    """
    label_file_name = 'train.xml'
    root = ET.parse(f'./data/train/{label_file_name}').getroot()
    print('Parsed all.xml...')

    train_list: List[str] = [f.rsplit('/',1)[1] for f in train_list]
    valid_list: List[str] = [f.rsplit('/',1)[1] for f in valid_list]
    train_objects: List = []
    valid_objects: List = []
    error_train_files: List[str] = []
    error_valid_files: List[str] = []
    for child in tqdm(root):
        if child.tag not in ['version', 'meta']:
            file_name: str = child.get('name')
            for attrib in child:
                try:
                    attrib.attrib['xtl']
                    attrib.attrib['xbr']
                    attrib.attrib['ytl']
                    attrib.attrib['ybr']
                    Image.open('./data/train/' + file_name)
                    Image.open('./data/train/' + file_name)
                except (KeyError, SyntaxError, IOError, EOFError, ValueError, FileNotFoundError) as e:
                    print(e, file_name)
                    if file_name in train_list:
                        error_train_files.append(file_name)
                        train_list.remove(file_name)
                    elif file_name in valid_list:
                        error_valid_files.append(file_name)
                        valid_list.remove(file_name)

            if file_name in train_list and file_name not in error_train_files:
                train_objects.append(child)
            elif file_name in valid_list and file_name not in error_valid_files:
                valid_objects.append(child)

    return train_objects, valid_objects

def indent(node: ET.XML, level: int = 0):
    i = '\n' + level * ' ' * 4
    if len(node):
        if not node.text or not node.text.strip():
            node.text = i + ' ' * 4
        if not node.tail or not node.tail.strip():
            node.tail = i
        for node in node:
            indent(node, level + 1)
        if not node.tail or not node.tail.strip():
            node.tail = i
    else:
        if level and (not node.tail or not node.tail.strip()):
            node.tail = i

def xml_writer(objects: List, file_name: str):
    if len(objects) == 0:
        return

    root = ET.Element('annotations')
    for obj in objects:
        image = ET.SubElement(root, 'image', obj.attrib)
        for bbox in obj:
            ET.SubElement(image, 'box', bbox.attrib)

    indent(root)
    tree = ET.ElementTree(root)
    tree.write(f'./data/{file_name}_labels.xml')

def get_test_list(path: str = './data/test/') -> List[str]:
    test_files: List[str] = sorted(list(glob(path + '*jpg')) + list(glob(path + '*png')))
    print(f'Total testset: {len(test_files)}...')
    return test_files

if __name__ == '__main__' :
    train_list, valid_list = train_valid_split(test_size=0.2, shuffle=True)
    train_objects, valid_objects = xml_parser(train_list, valid_list)
    xml_writer(train_objects, 'train')
    xml_writer(valid_objects, 'valid')


import os,json,logging
import json

def parse_conf(FileName='./conf/conf.example'):
    with open(FileName) as setting_file:
        lines=map(filter_comment,setting_file.readlines())
        setting_str = ''.join(lines)
        logging.debug('configure file :\n%s'%(setting_str))
        return json.loads(setting_str)

def filter_comment(Line):
    if '#' in Line:
        if Line.index('#') == 0:
            return '\n'
        elif Line.split("#")[0].count('"') % 2 == 0 and Line.split("#")[0].count("'") %2 == 0:
            return Line.split('#')[0] + '\n'

    return Line


import sys
import collections
input=sys.stdin.readline
M,N=map(int,input().split())

def bfs():
    dx = [0, -1, 0, 1]
    dy = [1, 0, -1, 0]

    while queue:
        y,x=queue.popleft()
        #queue2=collections.deque()
        for i in range(4):
            nx=dx[i]+x
            ny=dy[i]+y
            if nx>=0 and nx<M and ny>=0 and ny<N:
                if tomato[ny][nx]==0:
                    tomato[ny][nx]=tomato[y][x]+1
                    queue.append((ny,nx))

tomato=[]
for i in range(N):
    garo=list(map(int,input().split()))
    tomato.append(garo)

queue=collections.deque()
for i in range(N):
    for j in range(M):
        if tomato[i][j]==1:
            queue.append((i,j))

bfs()
can=1
result=-2
for i in tomato:
    for j in i:

        if j==0:
            can=0
            break
        result=max(result,j)
if can==0:
    print(-1)

else:
    print(result-1)


import numpy as np
import math
import random
import os
import zipfile

def load_dataset(filename:str)->(list, list):
    data_mat = []
    label_mat = []
    fr = open(filename)
    for line in fr.readlines():
        line_array = line.strip().split("\t")
        data_mat.append([float(line_array[0]),float(line_array[1])])
        label_mat.append(float(line_array[2]))
    return data_mat,label_mat

def select_rand_J(i,n):
    """
    return a random integer J smaller than n and not equal i
    :param i:
    :param n:
    :return:
    """
    j = i
    while (j==i):
        j = int(random.uniform(0,n))
    return int(j)

def clamp(val,low,high):
    temp = [low,high]
    low =min(temp)
    high = max(temp)
    if(val < low):
        val = low
    if(val > high):
        val = high
    return val

def simple_svm(train_features, train_lables, C , tolerance, max_iter) -> (np.matrix,float,np.matrix):
    feature_mat = np.mat(train_features)
    sample_count, feaure_count = np.shape(feature_mat)
    label_mat = np.mat(train_lables).transpose() # sharp: sample_count * 1
    b = 0
    alphas = np.mat(np.zeros((sample_count,1)))
    itor = 0
    while(itor < max_iter):
        alpha_pair_changed_count = 0
        for i in range(sample_count):
            x_i = feature_mat[i,:].transpose()
            y_i = float(label_mat[i])
            f_x_i = float( np.multiply(label_mat,alphas).transpose() * (feature_mat * x_i) ) +  b
            error_i = f_x_i - y_i
            if ( ( (y_i*error_i < -tolerance) and  (alphas[i] < C) ) or ( ( y_i*error_i > tolerance ) and (alphas[i] > 0) ) ):
                j = select_rand_J(i,sample_count)
                x_j = feature_mat[j,:].transpose()
                y_j = float(label_mat[j])
                f_x_j = float( np.multiply(label_mat,alphas).transpose() * (feature_mat * x_j) ) +  b
                error_j =  f_x_j - y_j
                alpha_i_old = alphas[i].copy()
                alpha_j_old = alphas[j].copy()
                if(y_i != y_j):
                    L = max(0,alpha_j_old - alpha_i_old)
                    H = min(C,C + alpha_j_old-alpha_i_old)
                else:
                    L = max(0,alpha_j_old+alpha_i_old-C)
                    H = min(C, alpha_j_old+alpha_i_old)
                if L==H:
                    #print("L==H")
                    continue
                k_i_i = float(x_i.transpose() * x_i)
                k_j_j = float(x_j.transpose() * x_j)
                k_i_j = float(x_j.transpose() * x_i)
                eta = k_i_i + k_j_j - 2 * k_i_j
                if(eta <= 0 ):
                    #print("eta <= 0")
                    continue
                else:
                    alpha_j_new = alpha_j_old + y_j * (error_i-error_j) / eta
                    alpha_j_new = clamp(alpha_j_new,H,L)
                if(abs(alpha_j_new-alpha_j_old) < 0.0001):
                    #print("alpha_j_new equal alpha_j_old")
                    continue
                alpha_i_new = alpha_i_old + y_i * y_j * (alpha_j_old - alpha_j_new)
                b_i = b - error_i - y_i * k_i_i * (alpha_i_new - alpha_i_old) - y_j * k_i_j * (alpha_j_new - alpha_j_old)
                b_j = b - error_j - y_i * k_i_j * (alpha_i_new - alpha_i_old) - y_j * k_j_j * (alpha_j_new - alpha_j_old)
                if( (alpha_i_new > 0 ) and (alpha_i_new < C)):
                    b = b_i
                elif( ( alpha_j_new > 0 ) and (alpha_j_new < C) ):
                    b = b_j
                else:
                    b = (b_i + b_j) / 2
                alphas[i] = alpha_i_new
                alphas[j] = alpha_j_new
                alpha_pair_changed_count += 1

        if(alpha_pair_changed_count == 0):
            itor += 1
        else:
            itor = 0
            print("alpha_pair_changed_count numeber: %d" % alpha_pair_changed_count)
        print("iteration numeber: %d" % itor)
    w = np.multiply(alphas, label_mat)
    w = np.multiply(w,feature_mat)
    w = np.sum(w,axis=0)
    return  alphas, b, w

def plot(data_mat:list, label_mat:list, weights:list):
    import matplotlib.pyplot as plt
    xcoord_1 = [];
    ycoord_1 = []
    xcoord_2 = [];
    ycoord_2 = []
    for i in range(len(label_mat)):
        if math.isclose(label_mat[i],1):
            xcoord_1.append(data_mat[i][0])
            ycoord_1.append(data_mat[i][1])
        else:
            xcoord_2.append(data_mat[i][0])
            ycoord_2.append(data_mat[i][1])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcoord_1, ycoord_1, c='red')
    ax.scatter(xcoord_2, ycoord_2, c='green')

    if weights != None:
        x_line = np.arange(0.0, 10.0, 0.1)
        y_line = (-weights[0] - weights[1] * x_line) / weights[2]
        y_line = np.asarray(y_line).flatten()
        ax.plot(x_line, y_line.flatten())

    plt.show()

def kernal_trans(feature_mat:np.matrix, feature:np.matrix, kTup:list):
    m,n = np.shape(feature_mat)
    k = np.mat(np.zeros((m,1)))
    if kTup[0] == "linear":
        k = feature_mat * feature.T
    elif kTup[0] == "rbf":
        for j in range(m):
            diff = feature_mat[j] - feature
            k[j] = diff * diff.T
        #括号没打对，调试了好久。太低级了
        #k = np.exp(k / -1 * (kTup[1] ** 2))
        k = np.exp( k / (-1 * (kTup[1]**2)))
    else:
        raise NameError("huston,wo have a problem. unknown kernel")
    return  k

class PlattSVM:
    def __init__(self,data_set,class_label,C,tolerance,kTup):
        self.feature_mat = np.mat(data_set)
        self.label_mat = np.mat(class_label).transpose()
        self.C = C
        self.tolerance = tolerance
        self.sample_count = np.shape(self.feature_mat)[0]
        self.alphas = np.mat(np.zeros((self.sample_count,1)))
        self.b = 0
        self.cache = np.mat(np.zeros((self.sample_count,2)))
        self.K = np.mat(np.zeros((self.sample_count,self.sample_count)))
        for i in range(self.sample_count):
            self.K[:,i] = kernal_trans(self.feature_mat,self.feature_mat[i],kTup)

    def calc_error(self,i):
        y_i = float(self.label_mat[i])
        f_x_i = float(np.multiply(self.label_mat, self.alphas).transpose() * (self.K[:,i])) + self.b

        error_i = f_x_i - y_i
        return error_i

    def select_rand_J(self,i):
        j = i
        while j == i:
            j = int(random.uniform(0, self.sample_count))
        return j

    def select_J(self,i,error_i):
        max_index = -1
        max_delta_error = 0
        max_error = 0
        # 这个cache的设置过程很难理解。
        self.cache[i] = [1,error_i]
        valid_cache_index_array = np.nonzero(self.cache[:,0].A)[0]
        if len(valid_cache_index_array) > 1 :
            for k in valid_cache_index_array:
                if k == i:
                    continue
                error_k = self.calc_error(k)
                delta_error = abs(error_i-error_k)
                if delta_error > max_delta_error:
                    max_index = k
                    max_delta_error = delta_error
                    max_error = error_k
        else:
            max_index = self.select_rand_J(i)
            max_error = self.calc_error(max_index)
        return max_index,max_error

    def update_cache(self,i):
        error_i = self.calc_error(i)
        self.cache[i] = [1,error_i]

    def examine_example(self,i):
        x_i = self.feature_mat[i, :].transpose()
        y_i = float(self.label_mat[i])
        error_i = self.calc_error(i)
        if (((y_i * error_i < - self.tolerance) and (self.alphas[i] < self.C)) or ((y_i * error_i > self.tolerance) and (self.alphas[i] > 0))):
            j,error_j = self.select_J(i, error_i)
            x_j = self.feature_mat[j, :].transpose()
            y_j = float(self.label_mat[j])
            alpha_i_old = self.alphas[i].copy()
            alpha_j_old = self.alphas[j].copy()
            if (y_i != y_j):
                L = max(0, alpha_j_old - alpha_i_old)
                H = min(self.C, self.C + alpha_j_old - alpha_i_old)
            else:
                L = max(0, alpha_j_old + alpha_i_old - self.C)
                H = min(self.C, alpha_j_old + alpha_i_old)
            if L == H:
                #print("L==H")
                return 0
            k_i_i = float(self.K[i,i])
            k_j_j = float(self.K[j,j])
            k_i_j = float(self.K[i,j])
            eta = k_i_i + k_j_j - 2 * k_i_j
            if (eta <= 0):
                #print("eta <= 0")
                return 0
            else:
                alpha_j_new = alpha_j_old + y_j * (error_i - error_j) / eta
                alpha_j_new = clamp(alpha_j_new, H, L)
            if (abs(alpha_j_new - alpha_j_old) < 0.0001):
                #print("alpha_j_new equal alpha_j_old")
                return 0
            alpha_i_new = alpha_i_old + y_i * y_j * (alpha_j_old - alpha_j_new)
            b_i = self.b - error_i - y_i * k_i_i * (alpha_i_new - alpha_i_old) - y_j * k_i_j * (alpha_j_new - alpha_j_old)
            b_j = self.b - error_j - y_i * k_i_j * (alpha_i_new - alpha_i_old) - y_j * k_j_j * (alpha_j_new - alpha_j_old)
            if ((alpha_i_new > 0) and (alpha_i_new < self.C)):
                self.b = b_i
            elif ((alpha_j_new > 0) and (alpha_j_new < self.C)):
                self.b = b_j
            else:
                self.b = (b_i + b_j) / 2

            #print("i=%d, %f,    j=%d, %f" %(i,j,alpha_i_new,alpha_j_new))
            self.alphas[i] = alpha_i_new
            self.alphas[j] = alpha_j_new

            #self.update_cache(i)
            #self.update_cache(j)

            return 1
        else:
            return 0

    def examine_example_simple(self, i):
        x_i = self.feature_mat[i, :].transpose()
        y_i = float(self.label_mat[i])
        error_i = self.calc_error(i)
        if (((y_i * error_i < -self.tolerance) and (self.alphas[i] < self.C)) or ((y_i * error_i > self.tolerance) and (self.alphas[i] > 0))):
            j = self.select_rand_J(i)
            error_j = self.calc_error(j)
            x_j = self.feature_mat[j, :].transpose()
            y_j = float(self.label_mat[j])
            alpha_i_old = self.alphas[i].copy()
            alpha_j_old = self.alphas[j].copy()
            if (y_i != y_j):
                L = max(0, alpha_j_old - alpha_i_old)
                H = min(self.C, self.C + alpha_j_old - alpha_i_old)
            else:
                L = max(0, alpha_j_old + alpha_i_old - self.C)
                H = min(self.C, alpha_j_old + alpha_i_old)
            if L == H:
                #print("L==H")
                return 0
            k_i_i = float(self.K[i,i])
            k_j_j = float(self.K[j,j])
            k_i_j = float(self.K[i,j])
            eta = k_i_i + k_j_j - 2 * k_i_j
            if (eta <= 0):
                #print("eta <= 0")
                return 0
            else:
                alpha_j_new = alpha_j_old + y_j * (error_i - error_j) / eta
                alpha_j_new = clamp(alpha_j_new, H, L)
            if (abs(alpha_j_new - alpha_j_old) < 0.0001):
                # print("alpha_j_new equal alpha_j_old")
                return 0
            alpha_i_new = alpha_i_old + y_i * y_j * (alpha_j_old - alpha_j_new)
            b_i = self.b - error_i - y_i * k_i_i * (alpha_i_new - alpha_i_old) - y_j * k_i_j * (alpha_j_new - alpha_j_old)
            b_j = self.b - error_j - y_i * k_i_j * (alpha_i_new - alpha_i_old) - y_j * k_j_j * (alpha_j_new - alpha_j_old)
            if ((alpha_i_new > 0) and (alpha_i_new < self.C)):
                self.b = b_i
            elif ((alpha_j_new > 0) and (alpha_j_new < self.C)):
                self.b = b_j
            else:
                self.b = (b_i + b_j) / 2
            self.alphas[i] = alpha_i_new
            self.alphas[j] = alpha_j_new
            return 1
        else:
            return 0

    def svm(self,max_itor=1):
        num_alpha_pair_changed = 0
        itor = 0
        example_all = True
        while( (itor < max_itor ) and ( (num_alpha_pair_changed > 0 ) or example_all ) ):
            num_alpha_pair_changed = 0
            if example_all:
                for i in range(self.sample_count):
                    num_alpha_pair_changed += self.examine_example(i)
                print(" full set: itor:%d, pairs changed:%d" % (itor,num_alpha_pair_changed))
                itor+=1
            else:
                non_bounds = np.nonzero((self.alphas.A > 0 ) * (self.alphas.A < self.C))[0]
                for i in non_bounds:
                    num_alpha_pair_changed += self.examine_example(i)
                print(" non bounds set: itor:%d, pairs changed:%d"%(itor, num_alpha_pair_changed))
                itor += 1
            if example_all:
                example_all = False
            elif(num_alpha_pair_changed==0):
                example_all = True

    def simple_svm(self,max_itor=1):
        itor = 0
        while (itor < max_itor):
            alpha_pair_changed_count = 0
            for i in range(self.sample_count):
                alpha_pair_changed_count += self.examine_example_simple(i)

            if (alpha_pair_changed_count == 0):
                itor += 1
                print("iteration numeber: %d" % itor)
            else:
                print("alpha_pair_changed_count:%d" % alpha_pair_changed_count)
                itor = 0

    def get_linear_weigets(self):
        w = np.multiply(self.alphas, self.label_mat)
        w = np.multiply(w, self.feature_mat)
        w = np.sum(w, axis=0)
        weights = [float(self.b)]
        weights.extend(np.asarray(w)[0].tolist())
        return weights

def test_linear():
    features, lables = load_dataset("data/ch06/testSet.txt")
    use_simple_svm = False
    kTup = ["linear"]
    platt_svm = PlattSVM(features, lables, 0.6, 0.001,kTup)

    if use_simple_svm:
        platt_svm.simple_svm(100)
        weights = platt_svm.get_linear_weigets()
        plot(features, lables, weights)
    else:
        platt_svm.svm(100)
        weights = platt_svm.get_linear_weigets()
        plot(features, lables, weights)

def test_none_linear(k1=1.4):
    features, lables = load_dataset("data/ch06/testSetRBF.txt")
    kTup = ["rbf",k1]
    platt_svm = PlattSVM(features, lables, 200, 0.001, kTup)
    platt_svm.svm(100)
    support_alpha_indecies = np.nonzero(platt_svm.alphas > 0 )[0]
    support_featues_mat = platt_svm.feature_mat[support_alpha_indecies]
    support_label_mat = platt_svm.label_mat[support_alpha_indecies]
    support_alphas = platt_svm.alphas[support_alpha_indecies]
    print("support vector %d " % np.shape(support_featues_mat)[0])

    m,n = np.shape(platt_svm.feature_mat)
    error_count = 0
    for i in range(m):
        kernal_eval = kernal_trans(support_featues_mat,platt_svm.feature_mat[i],kTup)
        temp:np.matrix = np.multiply(support_alphas,support_label_mat)
        predict = temp.T * kernal_eval + platt_svm.b
        if( np.sign(predict) != np.sign(lables[i])):
            error_count+=1
    print("training error rate is %f" % (float(error_count)/m) )
    test_features,test_labels = load_dataset("data/ch06/testSetRBF2.txt")
    test_feature_mat = np.mat(test_features)
    test_labels_mat = np.mat(test_labels)
    error_count = 0
    m, n = np.shape(test_feature_mat)
    for i in range(m):
        kernal_eval = kernal_trans(support_featues_mat,test_feature_mat[i],kTup)
        temp: np.matrix = np.multiply(support_alphas, support_label_mat)
        predict = temp.T * kernal_eval + platt_svm.b
        if( np.sign(predict) != np.sign(test_labels[i])):
            error_count+=1
    print("test error rate is %f" % (float(error_count)/m) )

def img_to_vector(zip_file,file_name): #type: (zipfile.ZipFile,str)->np.ndarray
    vec = np.zeros((1,1024))
    with zip_file.open(file_name) as zip_item_file:
        line_count = 0
        for line in zip_item_file:
            for i in range(32):
                num = int(line[i])-48
                vec[0,line_count*32+i]= num
            line_count += 1
    return vec

def hand_writing_data_set(zip_file,train_name_list):
    train_data_count = len(train_name_list)
    data_label = [0]*train_data_count
    data_set = np.zeros((train_data_count, 1024))
    for i in range(train_data_count):
        item_name = train_name_list[i]# type:str
        data_set[i] = img_to_vector(zip_file,item_name)
        label_name = item_name.replace("trainingDigits/","").replace(".txt","")
        label_name = label_name.replace("testDigits/", "").replace(".txt", "")
        lable_num = label_name.split("_")[0]
        lable_num = int(lable_num)
        data_label[i] = lable_num
    return data_set,data_label

def digital_to_label(digit_list,right_digit)->list:
    label = []
    for i in digit_list:
        if i == right_digit:
            label.append(1)
        else:
            label.append(-1)
    return label

def hand_writing_class_test(k1=0.01):
    abs_cur_dir = os.path.abspath(os.curdir)
    zip_file_name = os.path.join(abs_cur_dir,"data/ch06/digits.zip")
    with zipfile.ZipFile(zip_file_name,'r') as zip_file:
        name_list = zip_file.namelist()

        train_name_list = [x for x in name_list if x.startswith("trainingDigits") and x.endswith(".txt")]
        train_feature, train_digit = hand_writing_data_set(zip_file, train_name_list)
        train_label = digital_to_label(train_digit,9)

        #kTup = ["rbf", k1]
        #kTup = ["rbf",0.1]
        kTup = ["rbf", 100]

        platt_svm = PlattSVM(train_feature, train_label, 200, 0.0001, kTup)
        platt_svm.svm(100)

        support_alpha_indecies = np.nonzero(platt_svm.alphas > 0)[0]
        support_featues_mat = platt_svm.feature_mat[support_alpha_indecies]
        support_label_mat = platt_svm.label_mat[support_alpha_indecies]
        support_alphas = platt_svm.alphas[support_alpha_indecies]
        print("support vector %d / %d" % ( np.shape(support_featues_mat)[0],platt_svm.sample_count) )

        m, n = np.shape(platt_svm.feature_mat)
        error_count = 0
        for i in range(m):
            kernal_eval = kernal_trans(support_featues_mat, platt_svm.feature_mat[i], kTup)
            temp: np.matrix = np.multiply(support_alphas, support_label_mat)
            predict = temp.T * kernal_eval + platt_svm.b
            if (np.sign(predict) != np.sign(train_label[i])):
                error_count += 1
        print("training error rate is %f" % (float(error_count) / m))

        test_name_list = [x for x in name_list if (x.startswith("testDigits") and x.endswith(".txt"))]
        test_features, test_digit = hand_writing_data_set(zip_file, test_name_list)
        test_labels = digital_to_label(test_digit,9)

        test_feature_mat = np.mat(test_features)
        test_labels_mat = np.mat(test_labels)
        error_count = 0
        m, n = np.shape(test_feature_mat)
        for i in range(m):
            kernal_eval = kernal_trans(support_featues_mat, test_feature_mat[i], kTup)
            temp: np.matrix = np.multiply(support_alphas, support_label_mat)
            predict = temp.T * kernal_eval + platt_svm.b
            if (np.sign(predict) != np.sign(test_labels[i])):

                #print("%f %f %f "% (np.sum(support_featues_mat), np.sum(test_feature_mat[i]), np.sum(kernal_eval[i])) )
                #print("error for %f %d" % (predict, test_digit[i] ) )

                error_count += 1
            else:
                #print("right for %d" % test_digit[i])
                pass

        print("test error rate is %f" % (float(error_count) / m))

if __name__ == "__main__":
    #test_linear();
    #test_none_linear()
    hand_writing_class_test()


import graphene
from graphene_django import DjangoObjectType
from server.models import Client
from graphene_django.filter import DjangoFilterConnectionField
from graphql_relay.node.node import from_global_id

class Client_Type(DjangoObjectType):
    class Meta:
        model = Client
        filter_fields = [
            # fields that can be queried
            "id",
            "user",
            "business_name",
            "first_name",
            "last_name",
            "email",
            "street_address",
            "city",
            "state",
            "zipcode",
            "created_at",
            "modified_at",
            "deadline",
        ]
        interfaces = (graphene.Node,)

class Query(graphene.ObjectType):
    client = graphene.Node.Field(Client_Type)
    all_clients = DjangoFilterConnectionField(Client_Type)

    # how to filter clients
    def resolve_all_clients(self, info, **kwargs):
        user = info.context.user
        if user.is_anonymous:
            return Client.objects.none()
        else:
            return Client.objects.filter(user=user)

    # how to filter a single client
    def resolve_client(self, info, **kwargs):
        user = info.context.user
        if user.is_anonymous:
            return Client.objects.none()
        else:
            return Client.objects.filter(user=user)

class CreateClient(graphene.Mutation):
    """Create a client -
    Clients contain:
        an optional business name,
        user,
        a first name,
        a last name,
        an email,
        a street address,
        a city,
        a state,
        a zipcode,
        and an optional deadline field"""

    class Arguments:
        business_name = graphene.String()
        first_name = graphene.String()
        last_name = graphene.String()
        email = graphene.String()
        street_address = graphene.String()
        city = graphene.String()
        state = graphene.String()
        zipcode = graphene.String()
        deadline = graphene.types.datetime.Date()

    ok = graphene.Boolean()
    client = graphene.Field(Client_Type)
    status = graphene.String()

    def mutate(
        # data that can be mutated
        self,
        info,
        first_name,
        last_name,
        email,
        street_address,
        city,
        state,
        zipcode,
        deadline=None,
        business_name="",
    ):

        user = info.context.user
        # verifies you are working with existing user
        if user.is_anonymous:
            return CreateClient(ok=False, status="Must be logged in.")
        else:
            new_client = Client(
                # sets entered info as new client info
                business_name=business_name,
                first_name=first_name,
                last_name=last_name,
                email=email,
                street_address=street_address,
                city=city,
                state=state,
                zipcode=zipcode,
                user=user,
            )
            new_client.save()
            return CreateClient(client=new_client, ok=True, status="ok")

class UpdateClient(graphene.Mutation):
    """Update a client"""

    class Arguments:
        id = graphene.ID()
        business_name = graphene.String()
        first_name = graphene.String()
        last_name = graphene.String()
        email = graphene.String()
        street_address = graphene.String()
        city = graphene.String()
        state = graphene.String()
        zipcode = graphene.String()
        deadline = graphene.types.datetime.Date()

    ok = graphene.Boolean()
    client = graphene.Field(Client_Type)
    status = graphene.String()

    def mutate(
        self,
        info,
        id,
        first_name="",
        last_name="",
        email="",
        street_address="",
        city="",
        state="",
        zipcode="",
        deadline=None,
        business_name="",
    ):
        # Will need to pass null or nothing in for empty deadline on frontend
        user = info.context.user
        if user.is_anonymous:
            return UpdateClient(ok=False, status="Must be logged in.")
        else:
            # allows client info to be mutated
            updated_client = Client.objects.get(pk=from_global_id(id)[1])
            if first_name != "":
                updated_client.first_name = first_name
            if last_name != "":
                updated_client.last_name = last_name
            if email != "":
                updated_client.email = email
            if street_address != "":
                updated_client.street_address = street_address
            if city != "":
                updated_client.city = city
            if state != "":
                updated_client.state = state
            if zipcode != "":
                updated_client.zipcode = zipcode
            if deadline is not None:
                updated_client.deadline = deadline
            if business_name != "":
                updated_client.business_name = business_name
            updated_client.save()
            return UpdateClient(
                client=updated_client,
                ok=True,
                status=f"{updated_client.first_name} {updated_client.last_name} has been updated",
            )

class DeleteClient(graphene.Mutation):
    """Delete a client"""

    class Arguments:
        id = graphene.ID()

    ok = graphene.Boolean()
    client = graphene.Field(Client_Type)
    status = graphene.String()

    def mutate(self, info, id):
        user = info.context.user

        if user.is_anonymous:
            return DeleteClient(ok=False, status="Must be logged in.")
        else:
            # how to delete client
            deleted_client = Client.objects.get(pk=from_global_id(id)[1])
            name = f"{deleted_client.last_name} {deleted_client.last_name}"
            deleted_client.delete()
            return DeleteClient(ok=True, status=f"{name} deleted")

class ClientMutation(graphene.ObjectType):
    create_client = CreateClient.Field()
    update_client = UpdateClient.Field()
    delete_client = DeleteClient.Field()


import csv

with open('top_cities.csv', 'w', newline='') as f:
  # csv.writer는 파일 객체를 매개변수로 지정합니다.
  writer = csv.writer(f)
  # 첫번째 줄에는 헤더를 작성합니다.
  writer.writerow(['rank', 'city', 'population'])
  # writerrows()에 리스트를 전달하면 여러 개의 값을 출력합니다.
  writer.writerows([
    [1, '상하이', 24150000],
    [2, '카라치', 23500000],
    [3, '베이징', 21516000],
    [4, '텐진', 147221000],
    [5, '이스탄불', 15160467],
    ])


import segmentation_models_pytorch as smp
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import time
from glob import glob
import numpy as np
from PIL import Image

def get_model(encoder_name='resnet34'):
     model = smp.Unet(
        encoder_name=encoder_name,        # choose encoder, e.g. mobilenet_v2 or efficientnet-b7
        encoder_weights="imagenet",     # use `imagenet` pre-trained weights for encoder initialization
        in_channels=3,                  # model input channels (1 for gray-scale images, 3 for RGB, etc.)
        classes=3,                      # model output channels (number of classes in your dataset)
    )

     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
     model.to(device)
     model.eval()
     return model

class VAE(nn.Module):
    def __init__(self, nc, ngf, ndf, latent_variable_size, device):
        super(VAE, self).__init__()

        self.nc = nc
        self.ngf = ngf
        self.ndf = ndf
        self.device = device
        self.latent_variable_size = latent_variable_size

        # encoder
        self.e1 = nn.Conv2d(nc, ndf, 4, 2, 1)
        self.bn1 = nn.BatchNorm2d(ndf)

        self.e2 = nn.Conv2d(ndf, ndf*2, 4, 2, 1)
        self.bn2 = nn.BatchNorm2d(ndf*2)

        self.e3 = nn.Conv2d(ndf*2, ndf*4, 4, 2, 1)
        self.bn3 = nn.BatchNorm2d(ndf*4)

        self.e4 = nn.Conv2d(ndf*4, ndf*8, 4, 2, 1)
        self.bn4 = nn.BatchNorm2d(ndf*8)

        self.e5 = nn.Conv2d(ndf*8, ndf*8, 4, 2, 1)
        self.bn5 = nn.BatchNorm2d(ndf*8)

        self.fc1 = nn.Linear(ndf*8*4*4, latent_variable_size)
        self.fc2 = nn.Linear(ndf*8*4*4, latent_variable_size)

        # decoder
        self.d1 = nn.Linear(latent_variable_size, ngf*8*2*4*4)

        self.up1 = nn.UpsamplingNearest2d(scale_factor=2)
        self.pd1 = nn.ReplicationPad2d(1)
        self.d2 = nn.Conv2d(ngf*8*2, ngf*8, 3, 1)
        self.bn6 = nn.BatchNorm2d(ngf*8, 1.e-3)

        self.up2 = nn.UpsamplingNearest2d(scale_factor=2)
        self.pd2 = nn.ReplicationPad2d(1)
        self.d3 = nn.Conv2d(ngf*8, ngf*4, 3, 1)
        self.bn7 = nn.BatchNorm2d(ngf*4, 1.e-3)

        self.up3 = nn.UpsamplingNearest2d(scale_factor=2)
        self.pd3 = nn.ReplicationPad2d(1)
        self.d4 = nn.Conv2d(ngf*4, ngf*2, 3, 1)
        self.bn8 = nn.BatchNorm2d(ngf*2, 1.e-3)

        self.up4 = nn.UpsamplingNearest2d(scale_factor=2)
        self.pd4 = nn.ReplicationPad2d(1)
        self.d5 = nn.Conv2d(ngf*2, ngf, 3, 1)
        self.bn9 = nn.BatchNorm2d(ngf, 1.e-3)

        self.up5 = nn.UpsamplingNearest2d(scale_factor=2)
        self.pd5 = nn.ReplicationPad2d(1)
        self.d6 = nn.Conv2d(ngf, nc, 3, 1)

        self.leakyrelu = nn.LeakyReLU(0.2)
        self.relu = nn.ReLU()
        self.sigmoid = nn.Sigmoid()

    def encode(self, x):
        h1 = self.leakyrelu(self.bn1(self.e1(x)))
        h2 = self.leakyrelu(self.bn2(self.e2(h1)))
        h3 = self.leakyrelu(self.bn3(self.e3(h2)))
        h4 = self.leakyrelu(self.bn4(self.e4(h3)))
        h5 = self.leakyrelu(self.bn5(self.e5(h4)))
        h5 = h5.view(-1, self.ndf*8*4*4)

        return self.fc1(h5), self.fc2(h5)

    def reparametrize(self, mu, logvar):
        std = logvar.mul(0.5).exp_()
        if self.device == 'cuda':
            eps = torch.cuda.FloatTensor(std.size()).normal_()
        else:
            eps = torch.FloatTensor(std.size()).normal_()
        eps = Variable(eps)
        return eps.mul(std).add_(mu)

    def decode(self, z):
        h1 = self.relu(self.d1(z))
        h1 = h1.view(-1, self.ngf*8*2, 4, 4)
        h2 = self.leakyrelu(self.bn6(self.d2(self.pd1(self.up1(h1)))))
        h3 = self.leakyrelu(self.bn7(self.d3(self.pd2(self.up2(h2)))))
        h4 = self.leakyrelu(self.bn8(self.d4(self.pd3(self.up3(h3)))))
        h5 = self.leakyrelu(self.bn9(self.d5(self.pd4(self.up4(h4)))))

        out = self.sigmoid(self.d6(self.pd5(self.up5(h5))))
        if torch.isnan(out).sum() > 1:
            a = 1
        return out

    def get_latent_var(self, x):
        mu, logvar = self.encode(x.view(-1, self.nc, self.ndf, self.ngf))
        z = self.reparametrize(mu, logvar)
        return z

    def forward(self, x):
        mu, logvar = self.encode(x.view(-1, self.nc, self.ndf, self.ngf))
        z = self.reparametrize(mu, logvar)
        z = z.clamp(min=-1e7, max=1e7)
        res = self.decode(z)
        return res, mu, logvar

def get_vae():
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = VAE(nc=3, ngf=128, ndf=128, latent_variable_size=500, device=device)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)
    model.eval()
    return model