import numpy as np
import sys
from collections import deque

from sklearn.linear_model import Ridge, LinearRegression
from sklearn.ensemble import GradientBoostingRegressor
from numpy.linalg import solve

if sys.version_info.major == 2:
	input = raw_input

OFFSET = 3000
SKIP_SIZE = 28
TARGET_CHANNEL = 15
N_CHANNELS = 21

experiment_id = input()

class DelayedRLSPredictor:
	def __init__(self, n_channels, M=3, lambda_=0.999, delta=100, delay=0, mu=0.3):
		self._M = M
		self._lambda = lambda_
		self._delay = delay
		self._mu = mu
		size = M * n_channels
		self._w = np.zeros((size,))
		self._P = delta * np.eye(size)

		self.M2 = 30
		size2 = self.M2
		self._w2  = np.zeros((size2,))
		self._P2 = delta * np.eye(size2)
		self.regressors = deque(maxlen = self.M2 + delay + 1)
		#self.regressors = deque(maxlen = 3000)
		#self.regressors = []

	def append(self, sample):
		self.regressors.append(sample)
	def update(self):
		regressors = np.array(self.regressors)
		if regressors.shape[0] > self._delay + self._M:
			# predicted var x(t)
			# это ПОСЛЕДНЯЯ строка, которую я получил.
			predicted = regressors[-1, TARGET_CHANNEL]

			# predictor var [x(t - M), x(t - M + 1), ..., x(t - delay)]
			# читаю M последних строк (с учётом лага) в один вектор длины M * n_channels
			predictor = regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()  #

			# update helpers
			pi = np.dot(predictor, self._P) # это вектор-строка - произведение вектора и матрицы XP
			# k = XP/(l + XPy) # нормируем полученное произведение
			k = pi / (self._lambda + np.dot(pi, predictor))
			# обновляем матрицу, вычтя матричное произведение векторов k*pi P = 1/l * (P -k*pi)
			self._P = 1 / self._lambda * (self._P - np.dot(k[:, None], pi[None, :]))

			# update weights
			dw = (predicted - np.dot(self._w, predictor)) * k
			self._w = self._w + self._mu * dw
	def update2(self):
		regressors = np.array(self.regressors)
		if regressors.shape[0] > self._delay + self.M2:
			predicted = regressors[-1, TARGET_CHANNEL]
			predictor = regressors[- self.M2 - self._delay - 1: - self._delay - 1, TARGET_CHANNEL].flatten()
			pi = np.dot(predictor, self._P2) # это вектор-строка - произведение вектора и матрицы XP
			k = pi / (self._lambda + np.dot(pi, predictor))
			self._P2 = 1 / self._lambda * (self._P2 - np.dot(k[:, None], pi[None, :]))
			dw = (predicted - np.dot(self._w2, predictor)) * k
			self._w2 = self._w2 + self._mu * dw
	def predict_linear(self):
		regressors = np.array(self.regressors)
		if regressors.shape[0] > self._delay + self._M:
			# return prediction x(t + delay)
			return np.dot(self._w, regressors[- self._M:].flatten())
		# if lenght of regressor less than M + delay + 1 return 0
		return 0
	def predict_linear2(self):
		regressors = np.array(self.regressors)
		if regressors.shape[0] > self._delay + self.M2:
			return np.dot(self._w2, regressors[- self.M2:,TARGET_CHANNEL].flatten())
		return 0
	def update_predict(self, sample):
		self.append(sample)
		self.update()
		return self.predict_linear()
	def total_update(self):
		self.total_update_ridge()
	def total_update_ridge(self):
		regressors = np.array(self.regressors)
		X = []
		y = []
		# i символизирует первую строку в X
		# X будет использовать строки [i, i+M)
		# y будет использовать строку i + delay + M
		for i in range(0, regressors.shape[0] - self._delay - self._M):
			predictor = regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()
			X.append(predictor)
			y.append(regressors[i + self._delay + self._M, TARGET_CHANNEL])
			_ = 1
		X = np.array(X)
		y = np.array(y)

		#self.ridge = Ridge(alpha = 0.000001)
		#self.ridge = LinearRegression() #Ridge(solver = 'lsqr', max_iter = 1)

		#print(regressors.shape)
		#print(X.shape, y.shape)
		#self.ridge.fit(X,y)
		#print(X.shape[1])
		self.beta = solve(np.dot(X.transpose(), X) + np.eye(X.shape[1])*0.0003, np.dot(X.transpose(), y))
		#print(self.ridge.coef_)
	def total_update_tree(self):
		regressors = np.array(self.regressors)
		X = []
		y = []
		# i символизирует первую строку в X
		# X будет использовать строки [i, i+M)
		# y будет использовать строку i + delay + M
		for i in range(0, regressors.shape[0] - self._delay - self._M):
			predictor = regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()
			X.append(predictor)
			y.append(regressors[i + self._delay + self._M, TARGET_CHANNEL])
			_ = 1
		X = np.array(X)
		y = np.array(y)
		self.tree = GradientBoostingRegressor()
		self.tree.fit(X, y)
	def ridge_predict(self):
		#regressors = np.array(self.regressors) #
		predictor = [v for x in self.regressors[- self._M - self._delay - 1: - self._delay - 1] for v in x]
		#predictor = [regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()]
		#prediction = self.ridge.predict([predictor]	)[0]
		prediction = np.dot(predictor, self.beta)
		#print(type(prediction))
		return prediction
	def tree_predict(self):
		#regressors = np.array(self.regressors) #
		predictor = [v for x in self.regressors[- self._M - self._delay - 1: - self._delay - 1] for v in x]
		#predictor = [regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()]
		#prediction = self.ridge.predict([predictor]	)[0]
		prediction = self.tree.predict([predictor])[0]
		#print(type(prediction))
		return prediction

	def append_predict(self, sample):
		"""
		Устаревший метод, который делает всё в один мах - и добавляет наблюдения, и дообучается, и предсказывает.
		Вместо него следует использовать update_predict, который делает три вещи отдельными функциями.
		"""
		# метод добавляет sample в правый конец очереди
		self.regressors.append(sample)
		regressors = np.array(self.regressors)
		if regressors.shape[0] > self._delay + self._M:
			# predicted var x(t)
			# это ПОСЛЕДНЯЯ строка, которую я получил.
			predicted = regressors[-1, TARGET_CHANNEL]

			# predictor var [x(t - M), x(t - M + 1), ..., x(t - delay)]
			# читаю M последних строк (с учётом лага) в один вектор длины M * n_channels
			predictor = regressors[- self._M - self._delay - 1: - self._delay - 1].flatten()  #

			# update helpers
			pi = np.dot(predictor, self._P) # это вектор-строка - произведение вектора и матрицы XP
			# k = XP/(l + XPy) # нормируем полученное произведение
			k = pi / (self._lambda + np.dot(pi, predictor))
			# обновляем матрицу, вычтя матричное произведение векторов k*pi P = 1/l * (P -k*pi)
			self._P = 1 / self._lambda * (self._P - np.dot(k[:, None], pi[None, :]))

			# update weights
			dw = (predicted - np.dot(self._w, predictor)) * k
			self._w = self._w + self._mu * dw

			# return prediction x(t + delay)
			return np.dot(self._w, regressors[- self._M:].flatten())

		# if lenght of regressor less than M + delay + 1 return 0
		return 0

rls = DelayedRLSPredictor(n_channels=N_CHANNELS, M=20, lambda_=0.9996, delta=0.01, delay=SKIP_SIZE, mu=1)

# читаю первые 3000 строк, обучающие, и каждый раз что-то предсказываю (и забываю)
for i in range(OFFSET):
	cur_data = list(map(float, input().split()))
	#pr0 = rls.update_predict(cur_data)
	rls.append(cur_data)
	rls.update()
	rls.update2()

#rls.total_update_ridge()
#rls.total_update_tree()
pr0 = rls.predict_linear()
pr1= rls.predict_linear2()
#pr1 = rls.ridge_predict()
w1 = 0.5
prediction = pr0 * (1-w1) + pr1 * w1
#prediction = rls.tree_predict()
# вывожу предсказание после первых 3000 строк
print(prediction)
sys.stdout.flush()

# читаю очередную тестовую строку и делаю предсказание на её основе.
while True:
	cur_data = list(map(float, input().split()))
	#prediction = rls.update_predict(cur_data)
	rls.append(cur_data)
	rls.update2()
	rls.update()
	pr0 = rls.predict_linear()
	pr1 = rls.predict_linear2()
	#pr1 = rls.ridge_predict()
	prediction = pr0 * (1-w1) + pr1 * w1
	#prediction = rls.tree_predict()
	print(prediction)
	sys.stdout.flush()

yandex_neurohack_2016/current_solution — наилучшая смесь длинного и широкого.py


import datetime

import pycord
import asyncio

async def message_handler(msg):
    print("This event was registered in __init__ and doesn't have to be part of my client class")

class MyBot(pycord.Client):
    """
    Example of dynamic event registration
    ------------------------------------
    on_{event} methods are automatically called to make event
    registration easier if you decide to make a subclass
    of `pycord.Client`. Otherwise you can use the `self.on` method
    and pass in a callback to register it for the specified event.
    """

    def __init__(self):
        super().__init__('asyncio')
        self.on('message', message_handler)

    async def on_message(self, msg):
        print("We've received a message in #{} with content \"{}\"".format(msg.channel.name, msg.content))
        await self.process_commands(msg)

    async def on_ready(self, _bootup):
        if not hasattr(self, 'uptime'):
            self.uptime = datetime.datetime.utcnow()
        print("We're ready!")

if __name__ == '__main__':
    client = MyBot()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.login('token'))


from rest_framework import serializers
from .models import User
from company_service.serializers import CompanySerializer

class UserSerializer(serializers.HyperlinkedModelSerializer):
    default_company = CompanySerializer()

    class Meta:
        model = User
        fields = (
            'id',
            'name',
            'email',
            'is_active',
            'default_company',
            'groups',
            'created',
            'modified',
        )


# -*- coding: utf-8 -*-
import skillSchData

OK = 0
ERR_TOP_LEVEL = -1
ERR_LACK_CASH = -2

#===============================================================================
# 职业技能相关
#===============================================================================
def checkSchSkillOpen(who):
	'''检查职业技能开启
	'''
	updated = False
	skillList = skillSchData.getOpenSchSkill(who.school, who.level)
	for skId in skillList:
		if who.querySkillLevel(skId):
			continue
		who.setSkill(skId, 1)
		updated = True
		writeLog("skill/skillopen", "%d %d" % (who.id, skId))

	if updated:
		who.reCalcAttr()

def doSkillSchUpgrade(who, skId):
	'''升级
	'''
	skObj = who.skillCtn.getItem(skId)
	if not skObj:
		return
	level = skObj.level
	tRet = calcUpgradeSkillSch(who, skId, level, skObj.getLevelMax(who))
	errCode = tRet[0]
	cost = tRet[1]
	add = tRet[2]
	if errCode == ERR_LACK_CASH:
		if not money.checkCash(who, cost):
			return
	elif errCode == ERR_TOP_LEVEL:
		message.tips(who, "门派技能无法超过人物等级")
		return
	who.costCash(cost, "升级技能%d"%skId)
	writeLog("skill/upgrade", "%d %d %d %d->%d" % (who.id, skId, cost, level, level+add))
	who.setSkill(skId, level + add)
	who.reCalcAttr()

	import listener
	listener.doListen("升级门派技能", who)

def calcUpgradeSkillSch(who, skId, level, levelMax, realCost=0):
	# 返回：(错误码,费用,提升等级)
	if level >= levelMax:
		return ERR_TOP_LEVEL, 0, 0
	cost = calcSkillSchCost(skId, level)
	if who.cash < cost + realCost:
		return ERR_LACK_CASH, cost, 1
	return OK, cost, 1

def upgradeSkillSch(who, skObj, isRepeat=False):
	skId = skObj.id
	level = skObj.level
	levelMax = skObj.getLevelMax(who)
# 	skIdBase = getBaseSkill(who.school)
	if level >= levelMax:
		return
# 	if skId != skIdBase and level >= who.querySkillLevel(skIdBase): # 策划说没有基础技能
# 		return

	cost = calcSkillSchCost(skId, level)
	if isRepeat:
		add = levelMax - level
	else:
		add = 1

	if who.cash < cost * add:
		add = who.cash / cost
		if add < 1:
			return

	# 扣费用
	cost = cost * add
	who.costCash(cost, "升级技能%d"%skId)
	writeLog("skill/upgrade", "%d %d %d %d->%d" % (who.id, skId, cost, level, level+add))
	who.setSkill(skId, level + add)
	who.reCalcAttr()

def doCheckCash(who, skillList):
	'''判断一键升级是否需要弹出银币不足
	'''
	iTotalCost = calcSkillSchTotalCost(who, skillList)
	iLen = len(skillList)
	# 先模拟循环一次，如果因为银币不足一个都不能升级，则弹出银币不足接口
	iCheckCash = 0
	for skObj in skillList:
		tRet = calcUpgradeSkillSch(who, skObj.id, skObj.level, skObj.getLevelMax(who))
		if tRet[0] == ERR_LACK_CASH:
			iCheckCash += 1
	# 一个都不能升级的情况
	if iCheckCash == len(skillList):
		if not money.checkCash(who, iTotalCost):
			return False
	return True

def doSkillSchUpgradeLoop(who, skillList, iRepeat):
	'''所有已解锁的技能按解锁等级逐个进行等级+1的升级
	当所有可升级的技能等级都+1后，再次进行上一条
	'''
	dTmp = {skill.id:(0, 0) for skill in skillList}
	iRealCost = 0
	iLen = len(skillList)
	for i in xrange(iRepeat):
		iCheckCash = 0
		for skObj in skillList:
			skId = skObj.id
			oldValue = dTmp.get(skId, (0, 0))
			tRet = calcUpgradeSkillSch(who, skObj.id, skObj.level+oldValue[0], skObj.getLevelMax(who), iRealCost)
			if tRet[0] != OK:
				iCheckCash += 1
			else:
				iRealCost += tRet[1]
				dTmp[skId] = (oldValue[0]+tRet[2], oldValue[1]+tRet[1])
		# 一直循环到本轮技能都不能升级为止
		if iCheckCash == iLen:
			break
	return iRealCost, dTmp

def doSkillSchUpgradeAll(who):
	'''一键升级
	'''
	skillList = getCanUpgradeSkillList(who)
	if not skillList:
		message.tips(who, "门派技能等级都已达到上限，提升人物等级可提高该上限")
		return
	skillList.sort(key=lambda skObj:skObj.level)
	iRepeat = who.level - skillList[0].level
	skillList.sort(key=lambda skObj:skObj.getOpenLevel())
	if not doCheckCash(who, skillList):
		return
	iRealCost, dTmp = doSkillSchUpgradeLoop(who, skillList, iRepeat)
	# 扣费用
	who.costCash(iRealCost, "一键升级门派技能")
	for skObj in skillList:
		skId = skObj.id
		oldLevel = skObj.level
		addLevel, cost = dTmp.get(skId, 0)
		if not addLevel:
			continue
		writeLog("skill/upgrade", "%d %d %d %d->%d" % (who.id, skId, cost, oldLevel, oldLevel+addLevel))
		who.setSkill(skId, oldLevel + addLevel)
	who.reCalcAttr()
	message.tips(who, "一键升级成功")

	import listener
	listener.doListen("升级门派技能", who)

def getBaseSkill(sch):
	'''职业基础技能
	'''
	return 1011 + sch * 100

def getCanUpgradeSkillList(who):
	'''获取可升级的技能列表
	'''
	skillList = []
	for skObj in who.skillCtn.getAllValues():
		if not hasattr(skObj, "school"): # 非职业技能
			continue
		if skObj.level >= skObj.getLevelMax(who):
			continue
		skillList.append(skObj)
	return skillList

def calcSkillSchCost(skId, level):
	'''费用
	'''
	if 1111 <= skId < 3000: # 职业技能
		return skillSchUpgrade.getCostByLevel(level)
	return 999999

def calcSkillSchTotalCost(who, skillList):
	'''升级列表里的技能所需的费用
	'''
	iTotalCost = 0
	for skObj in skillList:
		skId = skObj.id
		level = skObj.level
		levelMax = skObj.getLevelMax(who)
		while level < levelMax:
			iTotalCost += calcSkillSchCost(skId, level)
			level += 1
	return iTotalCost

#===============================================================================
# 学习帮派技能相关
#===============================================================================
def doSkillGuildLearn(who, skId):
	'''学习帮派技能
	'''
# 	guildObj = who.guild
# 	if not guildObj:
# 		# toDo 弹出加入帮派界面
# 		return
	if who.level < 15:
		return
	# elif not who.getGuildObj():
	# 	message.tips(who, "你的帮贡处于冻结状态，需要加入帮派才能使用")
	# 	return
	skObj = skill.get(skId)
	skName = skObj.name
	lastLevel = who.querySkillLevel(skId)
	level = lastLevel + 1
	if level > skObj.getLevelMax(who):
		message.tips(who, "继续学习#C02%s#n需要#C04%d级#n" % (skName, who.level+1))
		# message.tips(who, "学习#C03%d级%s#n需要#C03%d级#n" % (level, skName, who.level+1))
		return

	costData = calSkillGuildLearnCost(skId, level)
	costCash = costData["银币"]
	costGuildPoint = costData["帮贡"]
	if who.cash < costCash:
		# message.tips(who, "学习#C02%d级%s#n需要帮贡#C02%d点#n" % (level, skName, costCash))
		#toDo 进入银币不足界面
		if not money.checkCash(who, costCash):
			return
		# return
	if who.fetch("guildPoint") < costGuildPoint:
		message.tips(who, "学习#C04{}级#n#C02{}#n需要仙盟贡献#R<{},7,2>#n#C02点#n".format(level, skName, costGuildPoint))
		return

	writeLog("skill/learn", "%d %d %d->%d cost %d %d" % (who.id, skId, lastLevel , level, costCash, costGuildPoint))
	who.costCash(costCash, "学习帮派技能", None)
	if costGuildPoint:
		who.addGuildPoint(-costGuildPoint, "学习帮派技能")
	who.setSkill(skId, level)
	who.reCalcAttr()
	message.tips(who, "消耗#IS#n#C02{:,}#n，将#C02{}#n提升至#C04{}#n级".format(costCash, skName, level))

def calSkillGuildLearnCost(skId, level):
	'''学习帮派技能费用
	'''
	costData = {}
	for costType in ("银币", "帮贡",):
		val = skillGuildData.getConfig(skId, costType)
		baseVal = skillGuildLearn.getConfig(level, costType)
		val = val.replace("B", str(baseVal))
		costData[costType] = int(eval(val))
	return costData

#===============================================================================
#使用帮派技能相关
#===============================================================================
def doSkillGuildUse(who, skId, skLv):
	'''使用帮派技能
	'''
	useFunc = skillGuildUseHandler.get(skId)
	if not useFunc:
		return

	level = who.querySkillLevel(skId)
	if not level:
		return
	skObj = skill.new(skId)
	skObj.level = level
	useFunc(who, skObj, skLv)

def calSkillGuildUseCost(skId, level):
	'''使用帮派技能消耗
	'''
	costData = {}
	for costType in ("活力", ):
		val = skillGuildData.getConfig(skId, costType)
		val = val.replace("LV", str(level))
		costData[costType] = int(eval(val))
	return costData

def makeFood(who, skObj, skLv=0):
	'''厨艺
	'''
	if who.propsCtn.leftCapacity() < 1:
		message.tips(who, "背包已满，请先清理背包")
		return
	costData = calSkillGuildUseCost(skObj.id, skObj.level)
	costHuoli = costData["活力"]
	if who.huoli < costHuoli:
		message.tips(who, "活力不足，无法烹饪" )
		return

	data = makeFoodData.getConfig(skObj.level)
	propsNoList = data["物品"]
	propsNo = propsNoList[rand(len(propsNoList))]
	quality = 0
	if propsNo in (220001,):
		propsObj = props.new(propsNo)
	else:
		quality = skObj.getEffectVal(who) # 品质
		propsObj = props.new(propsNo, quality=quality)

	writeLog("skill/makefood", "%d get %d(%d) cost %d" % (who.id, propsNo, quality, costHuoli))
	who.addHuoli(-costHuoli, "厨艺")
	launch.launchProps(who, propsObj, "厨艺", None)
	qualityStr = "#C04%d#n品质的" % propsObj.quality if propsNo != 220001 else ""
	message.tips(who, "$P<1,0.4,%s>#n烹饪成功，获得1个%s#C02%s#n" % (propsNo, qualityStr, propsObj.name))
	message.message(who,"你获得了#C02%s#n" % propsObj.name)

def makeMedicine(who, skObj, skLv=0):
	'''炼丹
	'''
	if who.propsCtn.leftCapacity() < 1:
		message.tips(who, "背包已满，请先清理背包")
		return
	costData = calSkillGuildUseCost(skObj.id, skObj.level)
	costHuoli = costData["活力"]
	if who.huoli < costHuoli:
		message.tips(who, "活力不足，无法炼丹")
		return

	data = makeMedicineData.getConfig(skObj.level)
	propsNo = chooseKey(data)
	quality = 0

	if propsNo in (221001, 221002,):
		propsObj = props.new(propsNo)
		tips = "$P<1,0.4,%s>#n炼丹失败，获得1个#C02%s#n" % (propsNo, propsObj.name)
	else:
		quality = max(skObj.getEffectVal(who),1) # 品质,保底1
		propsObj = props.new(propsNo, quality=quality)
		tips = "$P<1,0.4,%s>#n炼丹成功，获得1个#C04%d#n品质的#C02%s#n" % (propsNo, quality,propsObj.name)

	writeLog("skill/makeMedicine", "%d get %d(%d) cost %d" % (who.id, propsNo, quality, costHuoli))
	who.addHuoli(-costHuoli, "炼丹")
	launch.launchProps(who, propsObj, "炼丹", None)
	message.tips(who, tips)
	message.message(who,"你获得了#C02%s#n" % propsObj.name)

def makeMaterial(who, skObj, skLv):
	'''制作材料符(打造符、裁缝符、炼金符)
	'''
	if who.propsCtn.leftCapacity() < 1:
		message.tips(who, "背包已满，请先清理背包")
		return
	costData = calSkillGuildUseCost(skObj.id, skLv)
	costHuoli = costData["活力"]
	if who.huoli < costHuoli:
		message.tips(who, "活力不足，无法制作")
		return

	propsNo = getMaterial(skObj.id, skLv)
	if who.querySkillLevel(skObj.id) < 40:
		message.tips(who, "制作#C02{}#n需要#C02{}#n#C04≥40级#n".format(props.getPropsName(propsNo), skObj.name))
		return

	propsObj = props.new(propsNo)

	writeLog("skill/makematerial", "%d get %d cost %d" % (who.id, propsNo, costHuoli))
	who.addHuoli(-costHuoli, skObj.name)
	launch.launchProps(who, propsObj, skObj.name, None)
	message.tips(who, "$P<1,0.4,%s>#n制作成功，获得1个#C02%s#n" % (propsNo, propsObj.name))
	message.message(who,"你获得了#C02%s#n" % propsObj.name)

def getMaterial(skId, level):
	'''技能对应的材料符
	'''
	# 材料符从10级开始，故level最少应该为10
	level = max(level, 10)
	propsNo = skillGuildData.getConfig(skId, "效果物品")
	propsNo = propsNo.replace("LV", str(level))
	return int(eval(propsNo))

# 使用帮派技能的处理函数
skillGuildUseHandler = {
	503: makeFood,
	504: makeMedicine,
	505: makeMaterial,
	506: makeMaterial,
	507: makeMaterial,
}

#===============================================================================
#使用修炼相关
#===============================================================================
CASH_ONE_TIME = 20000 #一次消耗的金钱

def doSkillPracticeLearn(who, skId, learnType):
	'''学习修炼技能
	'''
	if skId not in (6101,6102,6103,6104,6105,6106,6107,6108):
		return

	maxLevel = checkAndGetPracticeLevel(who,skId)
	if not maxLevel:
		return
	if not checkPracticeCost(who,learnType):
		return

	func = practiceByType.get(learnType)
	if func:
		func(who,skId,maxLevel)

def checkPracticeCost(who,learnType):
	'''检查金钱
	'''
	costCash = 0
	if learnType == 1:
		costCash = CASH_ONE_TIME
	elif learnType == 2:
		costCash = CASH_ONE_TIME * 10

	return money.checkCash(who,costCash)

def checkAndGetPracticeLevel(who,skId):
	'''获取修炼等级上限
	'''
	lastLevel = who.querySkillLevel(skId)
	guildLevel = who.getPracticeGuildLevel()
	roleLevel = who.getPracticeRoleLevel()
	guildPoint = who.getPracticeGuildPoint()
	maxLevel = min(guildLevel,roleLevel,guildPoint)

	if lastLevel < maxLevel:
		return maxLevel

	lst = []
	if maxLevel == roleLevel:
		lst.append("等级")
	if maxLevel == guildLevel:
		lst.append("帮派等级")
	if maxLevel == guildPoint:
		lst.append("历史帮贡")

	message.tips(who,"你的修炼已达上限，请提升#C04%s#n" % "、".join(lst))
	return 0

def practiceOne(who,skId,maxLevel):
	'''修炼一次
	'''
	oldLevel = who.skillCtn.getLevel(skId)
	who.costCash(CASH_ONE_TIME,"修炼",None)
	who.skillCtn.addPracticePoint(skId,10)
	sendMessage(who,skId,oldLevel,10)

def practiceTen(who,skId,maxLevel):
	'''修炼十次
	'''
	times = 10
	skObj = who.skillCtn.getItem(skId)
	oldLevel = who.skillCtn.getLevel(skId)
	if skObj and skObj.level == maxLevel-1:
		needPoint = skObj.getPointNext()-skObj.getPoint()
		times = min(times,needPoint/10)

	who.costCash(CASH_ONE_TIME*times,"修炼",None)
	who.skillCtn.addPracticePoint(skId,10*times)
	sendMessage(who,skId,oldLevel,10*times)

def practiceByProps(who,skId,maxLevel):
	'''使用道具修炼
	'''
	propsNo = 202024 if skId in (6101,6102,6103,6104) else 202025
	amount, = who.propsCtn.getPropsAmountByNos(propsNo)
	if not amount:
		propsObj = props.getCacheProps(propsNo)
		message.tips(who,"你的%s不足" % propsObj.name)
		return
	oldLevel = who.skillCtn.getLevel(skId)
	skObj = who.skillCtn.getItem(skId)
	if not skObj:
		skObj = skill.get(skId)
		needPoint = skillPraticeLevelData.getPointNext(skObj.name,1)
	else:
		needPoint = skObj.getPointNext()-skObj.getPoint()

	amount = min(amount,needPoint/10)
	who.propsCtn.subPropsByNo(propsNo,amount,"修炼")
	who.skillCtn.addPracticePoint(skId,10*amount)
	sendMessage(who,skId,oldLevel,10*amount)

def sendMessage(who,skId,oldLevel,point):
	message.tips(who,"获得#C02%d#n点修炼经验" % point)
	skObj = who.skillCtn.getItem(skId)
	if skObj.level > oldLevel:
		message.tips(who,"#C02%s#n提升到#C04%d#n级" % (skObj.name,skObj.level))

practiceByType = {
	1:practiceOne,
	2:practiceTen,
	3:practiceByProps,
}

# def doSkillMakeMedicine(who, skObj, propsIdList):
# 	'''炼丹.消耗药材
# 	'''
# 	costData = calSkillGuildUseCost(skObj.id, skObj.level)
# 	makeMedicine(who, skObj, propsIdList, costData)

# def doSkillMakeMedicineByCash(who, skObj):
# 	'''炼丹.消耗银币
# 	'''
# 	propsIdList = []
# 	costData = calSkillGuildUseCost(skObj.id, skObj.level)
# 	costData["银币"] = 6000
# 	makeMedicine(who, skObj, propsIdList, costData)

# def makeMedicine(who, skObj, propsIdList, costData):
# 	if not checkForMakeMedicine(who, propsIdList, costData):
# 		return

# 	isSuccess, propsObj = produceProps(who, propsIdList, skObj)
# 	if propsObj:
# 		propsNo = propsObj.no()
# 		quality = getattr(propsObj, "quality", 0)
# 	else:
# 		propsNo = 0
# 		quality = 0

# 	costMsg = ",".join(["%s=%s"%(k,v) for k,v in costData.iteritems()])
# 	writeLog("skill/makemedicine", "%d get %d(%d) cost %s" % (who.id, propsNo, quality, costMsg))
# 	resumeForMakeMedicine(who, propsIdList, costData)

# 	if propsObj:
# 		launch.launchProps(who, propsObj, "炼丹", None)
# 		if isSuccess:
# 			message.tips(who, "$P<1,0.6,%s>#n炼丹成功，获得1个#C3$%d#n品质的#C3%s#n" % (propsNo,quality,propsObj.name))
# 		else:
# 			message.tips(who, "$P<1,0.6,%s>#n炼丹成功，获得1个#C3%s#n" % (propsNo,propsObj.name))
# 	else:
# 		message.tips(who, "炼丹失败")

# 	who.endPoint.rpcSkillMedicineResult(isSuccess)

# def checkForMakeMedicine(who, propsIdList, costData):
# 	'''检查炼丹
# 	'''
# 	# 检查消耗
# 	costHuoli = costData.get("活力")
# 	if costHuoli and who.huoli < costHuoli:
# 		message.tips(who, "炼丹需要活力#C3%d点#n" % costHuoli)
# 		return 0
# 	costCash = costData.get("银币")
# 	if costCash and who.cash < costCash:
# 		message.tips(who, "炼丹需要银币#C3%d#n" % costCash)
# 		return 0

# 	# 检查炼丹材料
# 	if propsIdList:
# 		for propsId, amount in propsIdList.iteritems():
# 			propsObj = who.propsCtn.getItem(propsId)
# 			if not propsObj:
# 				message.tips(who, "请放入炼丹材料")
# 				return 0
# 			if propsObj.stack() < amount:
# 				message.tips(who, "你身上没有这么多的%s" % propsObj.name)
# 				return 0
# 			if propsObj.kind != ITEM_MEDICINE_LEVEL or propsObj.level not in (1, 2,):
# 				message.tips(who, "请放入炼丹材料")
# 				return 0

# 	return 1

# def produceProps(who, propsIdList, skObj):
# 	'''炼丹产出物品
# 	'''
# 	isSuccess = 0
# 	modeData = getModeData(who, propsIdList)
# 	if rand(100) >= modeData["成功率"]:
# 		propsNoList = modeData.get("失败", [])
# 	else:
# 		isSuccess = 1
# 		propsNoList = modeData["成功"]

# 	propsObj = None
# 	if propsNoList:
# 		propsNo = propsNoList[rand(len(propsNoList))]
# 		if propsNo in (221001, 221002,):
# 			propsObj = props.new(propsNo)
# 		else:
# 			quality = skObj.getEffectVal(who) # 品质
# 			propsObj = props.new(propsNo, quality=quality)

# 	return isSuccess, propsObj

# def getModeData(who, propsIdList):
# 	'''获取匹配的炼丹模式数据
# 	'''
# 	mode = {}
# 	if propsIdList:
# 		for propsId, amount in propsIdList.iteritems():
# 			propsObj = who.propsCtn.getItem(propsId)
# 			level = propsObj.level
# 			mode[level] = mode.get(level, 0) + amount
# 	else:
# 		mode = {1:4,}
# 	return makeMedicineData.getConfig(mode)

# def resumeForMakeMedicine(who, propsIdList, costData):
# 	'''消耗
# 	'''
# 	if propsIdList:
# 		for propsId, amount in propsIdList.iteritems():
# 			propsObj = who.propsCtn.getItem(propsId)
# 			who.propsCtn.addStack(propsObj, -amount)

# 	if costData.get("活力"):
# 		who.addHuoli(-costData["活力"], "炼丹")
# 	if costData.get("银币"):
# 		who.costCash(costData["银币"], "炼丹", None)

from common import *
from props.defines import *
import message
import skill
import launch
import props
import skillSchUpgrade
import skillGuildData
import skillGuildLearn
import makeFoodData
import makeMedicineData
import money
import skillPraticeLevelData


#!/usr/bin/python

def number_to_words(hour, minutes, join=True):
	"""
	"""
	units = ['','one','two','three','four','five','six','seven','eight','nine','ten']
	teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
	tens  = ['ten','twenty','quarter']

	if minutes == '00':
		return units[int(hour)] + " o' clock"

	if minutes[0] == '3':
		if minutes[1] == '0':
			return 'half past ' + units[int(hour)]
		elif minutes[1] > '0':
			return abs()

	if minutes == '15':
		return 'quarter past ' + units[int(hour)]

	return NotImplementedError

if __name__ == '__main__':
	import sys
	h = int(sys.stdin.readline())
	m = int(sys.stdin.readline())
	assert 1 <= hour <= 12
	assert 0 <= minutes <= 59


import nuke.rotopaint as rp
import nuke
import nuke.curvelib as curvelib
import petfactory.util.persistance.persistance as pet_persistamce
reload(pet_persistamce)

def create_anim_crv(time_value_list):

    anim_curve = nuke.rotopaint.AnimCurve()

    for time_value in time_value_list:

        key = curvelib.AnimCurveKey()
        key.time = time_value[0]
        key.value = time_value[1]
        anim_curve.addKey(key)

    return anim_curve

def create_roto_from_anim_crv(anim_crv_list):

    roto_node = nuke.nodes.Roto()
    roto_node.setXYpos(0,0)
    curve_knob = roto_node['curves']
    shape = rp.Shape(curve_knob)

    for i in range(len(anim_crv_list)):

        acp = rp.AnimControlPoint(0,0)
        acp.setPositionAnimCurve(0, anim_crv_list[i][0])
        acp.setPositionAnimCurve(1, anim_crv_list[i][1])
        shape.append(acp)

    curve_knob.changed()

def create_anim_crv_from_2d_json():

    json_data = pet_persistamce.load_json('Select a 2d pos json file')
    #json_data = pet_persistamce.load_json_url('/Users/johan/Desktop/pos.json')
    time_step = 10
    anim_crv_list = []

    if json_data is not None:

        null_info_dict = json_data.get('info')
        #print(null_info_dict)
        frame_start = null_info_dict.get('frame_start')
        frame_end = null_info_dict.get('frame_end')
        duration = frame_end - frame_start

        null_dict_list = json_data.get('null')

        for null_dict in null_dict_list:
            for name, pos_dict in null_dict.iteritems():
                #print(name)

                pos_dict_x = pos_dict['x']
                pos_dict_y = pos_dict['y']

                time_list = []
                pos_x = []
                pos_y = []
                for index in range(0, duration, time_step):
                    time_list.append(frame_start+index)
                    pos_x.append(pos_dict_x[index])
                    pos_y.append(pos_dict_y[index])

                time_x_val = zip(time_list, pos_x)
                time_y_val = zip(time_list, pos_y)

                anim_crv_list.append((create_anim_crv(time_x_val), create_anim_crv(time_y_val)))

    #print(anim_crv_list)
    create_roto_from_anim_crv(anim_crv_list)

create_anim_crv_from_2d_json()


import pytest

from rsocket.connection import Connection
from rsocket.frame import (SetupFrame, CancelFrame, ErrorFrame)

@pytest.fixture()
def decoder():
    return Connection()

def test_setup():
    connection = Connection()
    data = b'\x00\x00\x40\x00\x00\x00\x00\x05\x00\x00\x01\x00\x00\x00\x00\x00'
    data += b'\x7b\x00\x00\x01\xc8\x18\x61\x70\x70\x6c\x69\x63\x61\x74\x69\x6f'
    data += b'\x6e\x2f\x6f\x63\x74\x65\x74\x2d\x73\x74\x72\x65\x61\x6d\x09\x74'
    data += b'\x65\x78\x74\x2f\x68\x74\x6d\x6c\x00\x00\x05\x04\x05\x06\x07\x08'
    data += b'\x01\x02\x03'

    frame, = connection.receive_data(data)
    assert isinstance(frame, SetupFrame)
    assert frame.serialize() == data

    assert frame.metadata_encoding == b'application/octet-stream'
    assert frame.data_encoding == b'text/html'
    assert frame.keep_alive_milliseconds == 123
    assert frame.max_lifetime_milliseconds == 456
    assert frame.data == b'\x01\x02\x03'
    assert frame.metadata == b'\x04\x05\x06\x07\x08'

def test_cancel():
    connection = Connection()
    data = b'\x00\x00\x06\x00\x00\x00\x7b\x24\x00'
    frame, = connection.receive_data(data)
    assert isinstance(frame, CancelFrame)
    assert frame.serialize() == data

def test_error():
    connection = Connection()
    data = b'\x00\x00\x13\x00\x00\x26\x6a\x2c\x00\x00\x00\x02\x04\x77\x65\x69'
    data += b'\x72\x64\x6e\x65\x73\x73'
    frame, = connection.receive_data(data)
    assert isinstance(frame, ErrorFrame)
    assert frame.serialize() == data

def test_multiple_frames():
    connection = Connection()
    data = b'\x00\x00\x06\x00\x00\x00\x7b\x24\x00'
    data += b'\x00\x00\x13\x00\x00\x26\x6a\x2c\x00\x00\x00\x02\x04\x77\x65\x69'
    data += b'\x72\x64\x6e\x65\x73\x73'
    data += b'\x00\x00\x06\x00\x00\x00\x7b\x24\x00'
    data += b'\x00\x00\x06\x00\x00\x00\x7b\x24\x00'
    data += b'\x00\x00\x06\x00\x00\x00\x7b\x24\x00'
    frames = connection.receive_data(data)
    assert len(frames) == 5


# Copyright 2017-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
# License MIT (https://opensource.org/licenses/MIT).
import logging

from odoo import api
from odoo.tests.common import HttpCase

_logger = logging.getLogger(__name__)

class TestBackend(HttpCase):
    # Making post_install True requires to update demo data, because other modules may change them
    at_install = True
    post_install = False

    def test_base(self):
        att_email = "att2@example.com"
        att_function = "JOB2"

        # data in tours are saved (but not commited!) via different cursor. So, we have to use that one
        test_env = api.Environment(self.registry.test_cr, self.uid, {})

        partner = test_env["res.partner"].search([("email", "=ilike", att_email)])
        self.assertFalse(
            partner,
            "It's assumed that partner with email %s doesn't not exist" % att_email,
        )

        registration_count_before = test_env["event.registration"].search_count([])

        self.phantom_js(
            "/event",
            "odoo.__DEBUG__.services['web_tour.tour']"
            ".run('website_event_attendee_fields_test_tour_base', 1000)",
            "odoo.__DEBUG__.services['web_tour.tour']"
            ".tours.website_event_attendee_fields_test_tour_base.ready",
            login="demo",
            timeout=200,
        )
        registration_count_after = test_env["event.registration"].search_count([])

        self.assertEqual(
            registration_count_before,
            registration_count_after - 2,
            "Amount of created registrations is not equal to 2",
        )

        registration = test_env["event.registration"].search(
            [], order="id desc", limit=1
        )

        _logger.debug(
            "registration_count_after=%s; registration: %s",
            registration_count_after,
            (registration, registration.partner_id, registration.partner_id.name),
        )
        self.assertTrue(
            registration.attendee_partner_id, "Latest registration doesn't have partner"
        )
        self.assertEqual(
            registration.attendee_partner_id.email,
            att_email,
            "Latest registration doesn't have correct partner's email",
        )
        self.assertEqual(
            registration.attendee_partner_id.function,
            att_function,
            "Latest registration doesn't have correct partner's Job",
        )


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

import threading

import pytest

from peewee import CharField, IntegerField, Model, SqliteDatabase
from tests.base import (ModelTestCase, PeeweeTestCase, TestModel, compiler,
                        database_initializer, query_db, skip_unless, test_db)
from tests.models import (Blog, MultiIndexModel, SeqModelA,
                          SeqModelB, UniqueModel, User)

try:
    from Queue import Queue
except ImportError:
    from queue import Queue

class TestMultiThreadedQueries(ModelTestCase):
    requires = [User]
    threads = 4

    def setUp(self):
        self._orig_db = test_db
        kwargs = {}
        try:  # Some engines need the extra kwargs.
            kwargs.update(test_db.connect_kwargs)
        except Exception:
            pass
        if isinstance(test_db, SqliteDatabase):
            # Put a very large timeout in place to avoid `database is locked`
            # when using SQLite (default is 5).
            kwargs['timeout'] = 30

        User._meta.database = self.new_connection()
        super(TestMultiThreadedQueries, self).setUp()

    def tearDown(self):
        User._meta.database = self._orig_db
        super(TestMultiThreadedQueries, self).tearDown()

    def test_multiple_writers(self):
        def create_user_thread(low, hi):
            for i in range(low, hi):
                User.create(username='u{0:d}'.format(i))
            User._meta.database.close()

        threads = []

        for i in range(self.threads):
            threads.append(threading.Thread(target=create_user_thread,
                                            args=(i * 10, i * 10 + 10)))

        [t.start() for t in threads]
        [t.join() for t in threads]

        assert User.select().count() == self.threads * 10

    def test_multiple_readers(self):
        data_queue = Queue()

        def reader_thread(q, num):
            for i in range(num):
                data_queue.put(User.select().count())

        threads = []

        for i in range(self.threads):
            threads.append(threading.Thread(target=reader_thread,
                                            args=(data_queue, 20)))

        [t.start() for t in threads]
        [t.join() for t in threads]

        assert data_queue.qsize() == self.threads * 20

class TestDeferredDatabase(PeeweeTestCase):
    def test_deferred_database(self):
        deferred_db = SqliteDatabase(None)
        assert deferred_db.deferred

        class DeferredModel(Model):
            class Meta:
                database = deferred_db

        with pytest.raises(Exception):
            deferred_db.connect()
        sq = DeferredModel.select()
        with pytest.raises(Exception):
            sq.execute()

        deferred_db.init(':memory:')
        assert not deferred_db.deferred

        # connecting works
        deferred_db.connect()
        DeferredModel.create_table()
        sq = DeferredModel.select()
        assert list(sq) == []

        deferred_db.init(None)
        assert deferred_db.deferred

class TestSQLAll(PeeweeTestCase):
    def setUp(self):
        super(TestSQLAll, self).setUp()
        fake_db = SqliteDatabase(':memory:')
        UniqueModel._meta.database = fake_db
        SeqModelA._meta.database = fake_db
        MultiIndexModel._meta.database = fake_db

    def tearDown(self):
        super(TestSQLAll, self).tearDown()
        UniqueModel._meta.database = test_db
        SeqModelA._meta.database = test_db
        MultiIndexModel._meta.database = test_db

    def test_sqlall(self):
        sql = UniqueModel.sqlall()
        assert sql == [
            ('CREATE TABLE "uniquemodel" ("id" INTEGER NOT NULL PRIMARY KEY, '
             '"name" VARCHAR(255) NOT NULL)'),
            'CREATE UNIQUE INDEX "uniquemodel_name" ON "uniquemodel" ("name")']

        sql = MultiIndexModel.sqlall()
        assert sql == [
            ('CREATE TABLE "multiindexmodel" ("id" INTEGER NOT NULL PRIMARY '
             'KEY, "f1" VARCHAR(255) NOT NULL, "f2" VARCHAR(255) NOT NULL, '
             '"f3" VARCHAR(255) NOT NULL)'),
            ('CREATE UNIQUE INDEX "multiindexmodel_f1_f2" ON "multiindexmodel"'
             ' ("f1", "f2")'),
            ('CREATE INDEX "multiindexmodel_f2_f3" ON "multiindexmodel" '
             '("f2", "f3")')]

        sql = SeqModelA.sqlall()
        assert sql == [
            ('CREATE TABLE "seqmodela" ("id" INTEGER NOT NULL PRIMARY KEY '
             'DEFAULT NEXTVAL(\'just_testing_seq\'), "num" INTEGER NOT NULL)')]

class TestLongIndexName(PeeweeTestCase):
    def test_long_index(self):
        class LongIndexModel(TestModel):
            a123456789012345678901234567890 = CharField()
            b123456789012345678901234567890 = CharField()
            c123456789012345678901234567890 = CharField()

        fields = LongIndexModel._meta.sorted_fields[1:]
        assert len(fields) == 3

        sql, params = compiler.create_index(LongIndexModel, fields, False)
        assert sql == (
            'CREATE INDEX "longindexmodel_85c2f7db" '
            'ON "longindexmodel" ('
            '"a123456789012345678901234567890", '
            '"b123456789012345678901234567890", '
            '"c123456789012345678901234567890")')

class TestDroppingIndex(ModelTestCase):
    def test_drop_index(self):
        db = database_initializer.get_in_memory_database()

        class IndexedModel(Model):
            idx = CharField(index=True)
            uniq = CharField(unique=True)
            f1 = IntegerField()
            f2 = IntegerField()

            class Meta:
                database = db
                indexes = ((('f1', 'f2'), True),
                           (('idx', 'uniq'), False))

        IndexedModel.create_table()
        indexes = db.get_indexes(IndexedModel._meta.db_table)

        assert sorted(idx.name for idx in indexes) == [
            'indexedmodel_f1_f2',
            'indexedmodel_idx',
            'indexedmodel_idx_uniq',
            'indexedmodel_uniq']

        with self.log_queries() as query_log:
            IndexedModel._drop_indexes()

        assert sorted(query_log.queries) == sorted(
            [('DROP INDEX "{0!s}"'.format(idx.name), []) for idx in indexes])
        assert db.get_indexes(IndexedModel._meta.db_table) == []

class TestConnectionState(PeeweeTestCase):
    def test_connection_state(self):
        test_db.get_conn()
        assert not test_db.is_closed()
        test_db.close()
        assert test_db.is_closed()
        test_db.get_conn()
        assert not test_db.is_closed()

    def test_sql_error(self):
        bad_sql = 'select asdf from -1;'
        with pytest.raises(Exception):
            query_db.execute_sql(bad_sql)
        assert query_db.last_error == (bad_sql, None)

@skip_unless(lambda: test_db.drop_cascade)
class TestDropTableCascade(ModelTestCase):
    requires = [User, Blog]

    def test_drop_cascade(self):
        u1 = User.create(username='u1')
        Blog.create(user=u1, title='b1')

        User.drop_table(cascade=True)
        assert not User.table_exists()

        # The constraint is dropped, we can create a blog for a non-
        # existant user.
        Blog.create(user=-1, title='b2')

@skip_unless(lambda: test_db.sequences)
class TestDatabaseSequences(ModelTestCase):
    requires = [SeqModelA, SeqModelB]

    def test_sequence_shared(self):
        a1 = SeqModelA.create(num=1)
        a2 = SeqModelA.create(num=2)
        b1 = SeqModelB.create(other_num=101)
        b2 = SeqModelB.create(other_num=102)
        a3 = SeqModelA.create(num=3)

        assert a1.id == a2.id - 1
        assert a2.id == b1.id - 1
        assert b1.id == b2.id - 1
        assert b2.id == a3.id - 1

@skip_unless(lambda: isinstance(test_db, SqliteDatabase))
class TestOuterLoopInnerCommit(ModelTestCase):
    requires = [User, Blog]

    def tearDown(self):
        test_db.set_autocommit(True)
        super(TestOuterLoopInnerCommit, self).tearDown()

    def test_outer_loop_inner_commit(self):
        # By default we are in autocommit mode (isolation_level=None).
        assert test_db.get_conn().isolation_level == None

        for username in ['u1', 'u2', 'u3']:
            User.create(username=username)

        for user in User.select():
            Blog.create(user=user, title='b-{0!s}'.format(user.username))

        # These statements are auto-committed.
        new_db = self.new_connection()
        count = new_db.execute_sql('select count(*) from blog;').fetchone()
        assert count[0] == 3

        assert Blog.select().count() == 3
        blog_titles = [b.title for b in Blog.select().order_by(Blog.title)]
        assert blog_titles == ['b-u1', 'b-u2', 'b-u3']

        assert Blog.delete().execute() == 3

        # If we disable autocommit, we need to explicitly call begin().
        test_db.set_autocommit(False)
        test_db.begin()

        for user in User.select():
            Blog.create(user=user, title='b-{0!s}'.format(user.username))

        # These statements have not been committed.
        new_db = self.new_connection()
        count = new_db.execute_sql('select count(*) from blog;').fetchone()
        assert count[0] == 0

        assert Blog.select().count() == 3
        blog_titles = [b.title for b in Blog.select().order_by(Blog.title)]
        assert blog_titles == ['b-u1', 'b-u2', 'b-u3']

        test_db.commit()
        count = new_db.execute_sql('select count(*) from blog;').fetchone()
        assert count[0] == 3

class TestConnectionInitialization(PeeweeTestCase):
    def test_initialize_connection(self):
        state = {'initialized': 0}

        class TestDatabase(SqliteDatabase):
            def initialize_connection(self, conn):
                state['initialized'] += 1

                # Ensure we can execute a query at this point.
                self.execute_sql('pragma stats;').fetchone()

        db = TestDatabase(':memory:')
        assert not state['initialized']

        db.get_conn()
        assert state['initialized'] == 1

        # Since a conn is already open, this will return the existing conn.
        db.get_conn()
        assert state['initialized'] == 1

        db.close()
        db.connect()
        assert state['initialized'] == 2


#-*- coding: utf-8-*-
# author : Takuro Yamazaki
# description : bottle templete engine

import os
import map_utils
import numpy as np

from bottle import route, run, url, request, static_file
from bottle import TEMPLATE_PATH, jinja2_template as template

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_PATH.append(BASE_DIR + "/views")

@route("/")
@route('/top')
def top():
    return template('top')

@route('/img/<filename:path>', name='img_file')
def static(filename):
    """views/imgの画像を表示するためのstatic_file設定
    """
    tmp = "/var/www/html/views"
    return static_file(filename, root=tmp+"/img")

@route('/milk', method="GET")
def milk():
    """半径2km以内の授乳室をtempleteに載せる
    """
    lat = request.query.get("lat")
    lng = request.query.get("lng")

    # set default value
    lat = 35.714263 if lat is None else float(lat)
    lng = 139.761892 if lng is None else float(lng)

    # 2km以内の授乳台一覧取得
    near_spot = np.array(map_utils.get_near_spot(lat, lng, "milk"))

    return template('map', lat=lat, lng=lng, near_spot=near_spot, ptype="milk", url=url)

@route('/omutsu', method="GET")
def omutsu():
    """半径2km以内の授乳室をtempleteに載せる
    """
    lat = request.query.get("lat")
    lng = request.query.get("lng")

    # set default value
    lat = 35.714263 if lat is None else float(lat)
    lng = 139.761892 if lng is None else float(lng)

    # 2km以内のオムツ台一覧取得
    near_spot = np.array(map_utils.get_near_spot(lat, lng, "omutsu"))

    return template('map', lat=lat, lng=lng, near_spot=near_spot, ptype="omutsu", url=url)

if __name__ == "__main__":
    run(host="localhost", port=8080, debug=True, reloader=True)


import tensorflow as tf
from os import path, getcwd, chdir

def train_mnist_conv():

    class myCallBacks(tf.keras.callbacks.Callback):
        def on_epoch_end(self, epoch, logs = {}):
            if logs.get("accuracy") >= 0.998:
                print("\nReached 99.8% accuracy so cancelling training!")
                self.model.stop_training = True

    mnist = tf.keras.datasets.mnist

    (training_images, training_labels), (test_images, test_labels) = mnist.load_data(path=path)
    training_images = training_images.reshape(training_images.shape[0], training_images.shape[1], training_images.shape[2],1)

    test_images = test_images.reshape(test_images.shape[0], test_images.shape[1], test_images.shape[2], 1)

    training_images, test_images = training_images/255.0, test_images/255.0

    callbacks = myCallBacks()
    model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(32, (3,3), activation=tf.nn.relu, input_shape=(28,28,1)),
        tf.keras.layers.MaxPool2D((2,2)),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation=tf.nn.relu),
        tf.keras.layers.Dense(10, activation=tf.nn.softmax)
    ])

    model.compile(optimizer="adam",
                  loss="sparse_categorical_crossentropy",
                  metrics=["accuracy"])
    history = model.fit(training_images, training_labels, epochs=10, callbacks=[callbacks])
    return history.epoch, history.history["accuracy"][-1]

if __name__ == "__main__":
    path = f"{getcwd()}/data/mnist.npz"
    """
    tf_1x
    config = tf.ConfigProto()
    config.gpu.options.allow_growth = True
    sess = tf.Session(config=config)
    """
    epoch, accuracy = train_mnist_conv()
    print("EPOCH", epoch, "ACC",accuracy)


import numpy as np

spTup = np.load(open("corSparseMatrix"))
tmp = []
covered = np.zeros(357, dtype=int)
clusterSize = []

'''#Each matrix element would be updated to 1 when the grah element is covered in a given cluster
for i in range(5):
	for j in range(357):
		tmp.append(np.zeros(len(spTup[i][j])))
	countCheck.append(tmp)
'''

count = 0
def calClusterSize(rowNo, week, year):
	global spTup; global count; global covered
	if (len(spTup[year][week][rowNo])!=0):
		for edge in spTup[year][week][rowNo]:
			if (covered[edge] == 0):
				covered[edge] = 1
				count = count + 1
				calClusterSize(edge, week, year)
			else :
				count = count + 1
	return count
temp = []

for year in range(3):
	for week in range(345):
		for loc1 in range(357):
			if (covered[loc1] == 0):
				covered[loc1] = 1
				temp.append(calClusterSize(loc1, week, year))
				count = 0
		clusterSize.append(temp)
		temp = []
		covered = np.zeros(357, dtype=int)


#<ImportModules>
import sys
import ShareYourSystem as SYS
#</ImportModules>

#<DefineClass>
class FilterClass(SYS.UserClass):

	#<DefineHookMethods>
	def initAfterWithFilter(self):

		#<DefineSpecificDict>
		"""
		self(
				**{
					'TypeDictString':"Use",
					'UsingTypeString':"Filter",
					'UsedTypeString':"Functor"
				}
			)
		"""
		self+={'UsedTypeString':"Functor",'UsingTypeString':"Filter"}
		#</DefineSpecificDict>

		#Remove KeyStrings for print
		self.SkippedKeyStringsList+=[]

		#Update the TypeStringToKeyStringsListDict
		self.TypeStringToKeyStringsListDict["Filter"]=[
												]

	def callAfterBasesWithFilter(self,*_ArgsList,**_KwargsDict):

		#Check that the _KwargsDict is ok
		if 'TypeDictString' in _KwargsDict:
			if _KwargsDict['TypeDictString']=="Filter":
				if 'FilteredVariablesList' in _KwargsDict:

					#Call a filter for each Variable in the _ArgsList
					if callable(self['<Used>OfFilter_Functor']):
						return list(
									filter(
											lambda FilteredVariable:
											self['<Used>OfFilter_Functor'](FilteredVariable),
											list(_KwargsDict['FilteredVariablesList'])
											)
									)

	#</DefineHookMethods>

	#<DefineBindingHookMethods>
	#<DefineBindingHookMethods>

#</DefineClass>


from rfc3339 import rfc3339

from datetime import time
from schematics.types import (
    StringType as DefaultStringType, DateTimeType as DefaultDateTimeType,
    FloatType, IntType, ListType, BooleanType, BaseType, DictType
)

class ISODateTimeType(DefaultDateTimeType):
    SERIALIZED_FORMAT = "%Y-%m-%dT%H:%M:%S%z"

class RFC3339DateTimeType(DefaultDateTimeType):
    SERIALIZED_FORMAT = lambda kls, value: rfc3339(value)

class SecondsType(IntType):

    def convert(self, value, context=None):
        if isinstance(value, int):
            return value

        value = int(value.replace("s", "")) if value else None

        if not value:
            return None

        return self.to_native(value, context)

    def to_primitive(self, value, context=None):
        value = super(SecondsType, self).to_primitive(value, context=context)
        return "{}s".format(value)

class StringType(DefaultStringType):
    def convert(self, value, context=None):
        if not value:
            return None

        return self.to_native(value, context)

class TimeType(StringType):

    def convert(self, value, context=None):
        return value

    def to_primitive(self, value, context=None):
        if not value:
            return None

        if isinstance(value, time):
            return value.strftime("%H:%M:%S")

        return value

class AnyOrListType(ListType):

    def convert(self, value, context=None):
        if value == "*any":
            return []

        if isinstance(value, list):
            return value

        return value.split(";")

    def export(self, value, format, context=None):
        result = super(AnyOrListType, self).export(value, format=format, context=context)
        return ";".join([str(x) for x in result]) if result else "*any"


# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import SmsSender, SmsTemplate, SmsSendHistory, AutoSmsSenderManager, MassiveSmsReservation
from .views import SmsMixin
from examinees.models import Examinee
from django import forms
from django.utils.html import format_html
from django.contrib import messages
from django.forms.models import BaseInlineFormSet
from rangefilter.filter import DateRangeFilter

import csv
import codecs
import datetime

class SmsSenderAdmin(admin.ModelAdmin):
	list_display = ('sender', 'description', 'reg_timestamp')
	readonly_fields = ['reg_timestamp']

	def save_model(self, request, obj, form, change):
		obj.sender = obj.sender.replace('-', '')

		super(SmsSenderAdmin, self).save_model(request, obj, form, change)

class SmsSendHistoryAdmin(admin.ModelAdmin):
	actions = ('sms_cancel', 'sms_resend', 'sms_permit')
	fieldsets = (
		('수진자 정보', {
			'fields': (('examinee',),)
		}),
		('발송 정보', {
			'fields': ('contents', 'sender', 'booked_datetime', 'registration_type')

		}),
		('승인 상태', {
			'fields': ('is_permitted',)
		}),
		('전송 상태', {
			'fields': ('status', 'result_code')
		}),
	)
	list_display = (
		'examinee_data', 'phone_number', 'registration_type', 'send_datetime', 'booked_datetime', 'permission', 'status',
	)
	list_filter = (
		'status', 'send_type', 'is_permitted',
		('booked_datetime', DateRangeFilter)
	)

	ordering = ('-booked_datetime',)
	readonly_fields = ['examinee', 'send_datetime', 'result_code', 'registration_type']
	search_fields = ('examinee__name', 'status', 'is_permitted')

	def examinee_data(self, obj):
		return format_html(
			"""
				{}
			""", obj.examinee.id, obj.examinee.name)

	examinee_data.allow_tags = True
	examinee_data.short_description = '수진자'

	def permission(self, obj):
		if obj.is_permitted:
			return '승인'
		else:
			return format_html(
				"""

						보류

				""",
				obj.pk,
			)

	permission.allow_tags = True
	permission.short_description = '승인 여부'

	def phone_number(self, obj):
		return obj.examinee.phone_number

	phone_number.allow_tags = True
	phone_number.short_description = '휴대폰 번호'

	def registration_type(self, obj):
		message_type = obj.get_send_type_display()

		if "menqol" in obj.contents:
			message_type = "MENQoL"
		elif 'reservation' in obj.contents:
			message_type = "재방문 검사"
		elif "survey" in obj.contents:
			message_type = "3개월 주기 추적"

		return format_html(
			'{}', obj.id, message_type
		)

	registration_type.allow_tag = True
	registration_type.short_description = '메시지 형식'

	def sms_cancel(self, request, queryset):
		queryset.update(status=SmsSendHistory.SMS_STATUS_CANCELLED)
		messages.success(request, '예약 취소 처리 완료')

	def sms_resend(self, request, queryset):
		queryset.update(status=SmsSendHistory.SMS_STATUS_WAIT)
		messages.success(request, '재발송 예약 처리 완료')

	def sms_permit(self, request, queryset):
		queryset.update(is_permitted=SmsSendHistory.PERMITTED)
		messages.success(request, '전송 승인 완료')

	sms_cancel.short_description = '예약 취소 하기'
	sms_resend.short_description = '재발송 예약 하기'
	sms_permit.short_description = '전송 승인 하기'

	def has_add_permission(self, request):
		return False

class SmsSendHistoryFormSet(BaseInlineFormSet):
	def get_queryset(self):
		qs = super(SmsSendHistoryFormSet, self).get_queryset().order_by('-send_datetime')
		return qs[:5][::-1]

class SmsSendHistoryForm(forms.ModelForm):
	class Meta:
		model = SmsSendHistory
		fields = '__all__'
		widgets = {
			'contents': forms.Textarea(attrs={'rows': 5, 'cols': 30}),
		}

class SmsSendHistoryInline(admin.TabularInline):
	model = SmsSendHistory
	can_delete = False
	extra = 0
	max_num = 5
	formset = SmsSendHistoryFormSet
	form = SmsSendHistoryForm
	readonly_fields = ['examinee', 'send_datetime', 'result_code']

	def has_add_permission(self, request):
		return False

class AutoSmsSenderManagerAdmin(admin.ModelAdmin):
	list_display = ('manager_',)

	def manager_(self, obj):
		if obj.send_timestamp is None:
			send_timestamp = '즉시 발송'
		else:
			send_timestamp = obj.send_timestamp.strftime('%p %I:%M')

		return '문자 자동 전송 내용 : {}
자동 전송 시각 : {}
등록 전화번호 : {}
문자 타입 : {} 티입'.format(
			obj.content.subject,
			send_timestamp,
			obj.sender.description,
			obj.send_type_string,
		)

	manager_.short_description = '문자 자동 전송 관리자'
	manager_.allow_tags = True

	def get_actions(self, request):
		actions = super(AutoSmsSenderManagerAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		return actions

	def has_add_permission(self, request):
		count = AutoSmsSenderManager.objects.all().count()
		if count == 0:
			return True
		return False

	def has_delete_permission(self, request, obj=None):
		count = AutoSmsSenderManager.objects.all().count()
		if count > 2:
			return True
		return False

class MassiveSmsReservationAdmin(admin.ModelAdmin):
	list_display = ('booked_datetime', 'content_subject', 'total_count', 'success_count', 'fail_count', 'created_at')
	readonly_fields = ['success_count', 'fail_count', 'content_subject', 'total_count']

	def content_subject(self, obj):
		return obj.content.subject

	content_subject.short_description = '템플릿 제목'

	def get_actions(self, request):
		actions = super(MassiveSmsReservationAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		return actions

	def has_delete_permission(self, request, obj=None):
		return True

	def save_model(self, request, obj, form, change):
		if change:
			messages.error(request, '예약된 내용은 변경할 수 없습니다.')
			return

		super(MassiveSmsReservationAdmin, self).save_model(request, obj, form, change)

		examinee_list = dict()
		for examinee in Examinee.objects.all():
			try:
				examinee_list[examinee.phone_number] = examinee.id
			except:
				pass

		count = 0
		fail_list = []
		success_list = []

		send_datetime = obj.booked_datetime

		with codecs.open(obj.examinee_list_file.path, "r", encoding='utf-8') as f:
			reader = csv.reader(f)

			for i, inline in enumerate(reader):
				rid, name, phone = inline

				if count % 100 == 0:
					send_datetime = send_datetime + datetime.timedelta(minutes=2)

				try:
					phone = phone.replace('-', '').replace(' ', '')
					_id = examinee_list.get(phone)
					examinee = Examinee.objects.get(id=_id)

					content = SmsMixin.make_sms_massage(obj.content.contents, examinee)
					SmsSendHistory.objects.create(
						examinee=examinee,
						contents=content,
						sender=obj.sender,
						is_permitted=SmsSendHistory.PERMITTED,
						booked_datetime=send_datetime,
					)
					success_list.append(examinee)

				except Exception:
					fail_list.append('{}, {}, {}'.format(inline[0].replace(' ', ''), inline[1].replace(' ', ''), inline[2].replace(' ', '')))

				count += 1

		obj.total_count = count
		obj.success_count = len(success_list)
		obj.fail_count = len(fail_list)
		obj.save()

		if len(fail_list) > 0:
			messages.error(request, '[메시지 발송 예약 실패 명단] 수진자 등록 정보를 다시 확인해주세요.')

		for excepted_examinee in fail_list:
			messages.error(request,  excepted_examinee)

class SmsTemplateAdmin(admin.ModelAdmin):
	list_display = ('subject', 'reg_timestamp')

admin.site.register(SmsSender, SmsSenderAdmin)
admin.site.register(SmsTemplate, SmsTemplateAdmin)
admin.site.register(SmsSendHistory, SmsSendHistoryAdmin)
admin.site.register(AutoSmsSenderManager, AutoSmsSenderManagerAdmin)
admin.site.register(MassiveSmsReservation, MassiveSmsReservationAdmin)


"""
1295. 统计位数为偶数的数字
给你一个整数数组 nums，请你返回其中位数为 偶数 的数字的个数。

示例 1：

输入：nums = [12,345,2,6,7896]
输出：2
解释：
12 是 2 位数字（位数为偶数）
345 是 3 位数字（位数为奇数）
2 是 1 位数字（位数为奇数）
6 是 1 位数字 位数为奇数）
7896 是 4 位数字（位数为偶数）
因此只有 12 和 7896 是位数为偶数的数字
示例 2：

输入：nums = [555,901,482,1771]
输出：1
解释：
只有 1771 是位数为偶数的数字。

提示：

1 <= nums.length <= 500
1 <= nums[i] <= 10^5
"""
from typing import List

class Solution:
    def findNumbers_one(self, nums: List[int]) -> int:
        data = len(list(filter(lambda x: len(str(x)) % 2 == 0, nums)))
        return data

    def findNumbers(self, nums: List[int]) -> int:
        data = 0
        for i in nums:
            if len(str(i)) % 2 == 0:
                data += 1
        return data

if __name__ == "__main__":
    solution = Solution()
    data = solution.findNumbers([12, 345, 2, 6, 7896])
    print(data)


class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        return([i for i in A if i%2==0]+[i for i in A if i%2!=0])

    def sortArrayByParity(self, A: List[int]) -> List[int]:

        output = []
        for i in range(len(A)):
            if A[i] % 2 == 0:
                output.append(A[i])

        for i in range(len(A)):
            if A[i] % 2 != 0:
                output.append(A[i])

        return output


# coding:utf-8
# --author-- lanhua.zhou
from __future__ import print_function

import os
import logging

import maya.cmds as cmds

import zfused_api
from zcore import filefunc

import zfused_maya.core.record as record

import zfused_maya.node.core.alembiccache as alembiccache
import zfused_maya.node.core.texture as texture
import zfused_maya.node.core.material as material
import zfused_maya.node.core.fixmeshname as fixmeshname
import zfused_maya.node.core.renderinggroup as renderinggroup

__all__ = ["publish_material"]

logger = logging.getLogger(__name__)

# test
def publish_material(*args, **kwargs):
    """ 上传任务模型文件

    """
    output_entity_type, output_entity_id, output_attr_id = args

    _output_attr_handle = zfused_api.outputattr.OutputAttr(output_attr_id)
    _suffix = _output_attr_handle.suffix()
    _file_format = _output_attr_handle.format()
    _attr_code = _output_attr_handle.code()

    _project_step_id = _output_attr_handle.data()["ProjectStepId"]
    _project_step_handle = zfused_api.step.ProjectStep(_project_step_id)
    _step_code = _project_step_handle.code()
    _software_code = zfused_api.software.Software(_project_step_handle.data()["SoftwareId"]).code()

    _output_link_handle = zfused_api.objects.Objects(output_entity_type, output_entity_id)
    _production_path = _output_link_handle.production_path()
    _temp_path = _output_link_handle.temp_path()
    _file_code = _output_link_handle.file_code()

    _task = _output_link_handle.tasks([_project_step_id])[0]
    _task_id = _task["Id"]
    _task_handle = zfused_api.task.Task(_task_id)
    if kwargs.get("fix_version"):
        _file_index = "{:0>4d}".format(_task_handle.last_version_index( 0 ))
    else:
        _file_index = "{:0>4d}".format(_task_handle.last_version_index() + 1)

    _production_file = "{}/{}/{}/{}/{}.{}{}".format( _production_path, _step_code, _software_code, _attr_code, _file_code, _file_index, _suffix )
    _production_file_dir = os.path.dirname(_production_file)
    _cover_file = "{}/{}/{}/{}/{}{}".format(_production_path, _step_code, _software_code, _attr_code, _file_code, _suffix)
    _publish_file = "{}/{}/{}/{}/{}.{}{}".format( _temp_path, _step_code, _software_code, _attr_code, _file_code, _file_index, _suffix )
    _publish_file_dir = os.path.dirname(_publish_file)
    if not os.path.isdir(_publish_file_dir):
        os.makedirs(_publish_file_dir)

    try:
        # save publish file
        cmds.file(rename = _publish_file)
        cmds.file(save = True, type = _file_format, f = True)

        # fix mesh name
        _is_rendering = renderinggroup.nodes()
        fixmeshname.fix_mesh_name("_rendering", _is_rendering)

        # recore material
        material.record()

        # get all material
        _meshs = _get_rendering_mesh()
        if not _meshs:
            return
        # 对大量模型操作时会卡死，弃用
        # cmds.select(_meshs, replace = True)
        # cmds.hyperShade(shaderNetworksSelectMaterialNodes = True)
        _sg = cmds.listConnections(_meshs,d = 1,type = "shadingEngine")
        _mat = [cmds.listConnections("{}.surfaceShader".format(i),d = 1)[0] for i in set(_sg)]
        cmds.select(_mat,r =1)
        cmds.file(_publish_file, op = "v=0;", type = "mayaBinary", pr = True, es = True, f = True)

        # publish file
        _result = filefunc.publish_file(_publish_file, _production_file)
        _result = filefunc.publish_file(_publish_file, _cover_file)

    except Exception as e:
        logger.error(e)
        return False

    # open orignal file
    # cmds.file(_current_file, o = True, f = True, pmt = True)
    return True

def _get_rendering_mesh():
    mesh = []
    rendering = []
    allDags = cmds.ls(dag = True)
    for dag in allDags:
        dag
        #get
        if cmds.objExists("%s.rendering"%dag):
            value = cmds.getAttr("%s.rendering"%dag)
            if value:
                rendering.append(dag)
    for grp in rendering:
        allDags = cmds.ls(grp, dag = True, ni = True)
        mesh += allDags
    return mesh


import pypinyin #汉语转拼音模块
import urllib.request
import urllib.parse
import json
import re

def spider(word):#网上爬取

    try:

        url = 'https://fanyi.baidu.com/sug' #资源地址
        data = {} #得到的数据的容器
        data['kw'] = word

        data = urllib.parse.urlencode(data).encode('utf-8') #获取数据并转码
        req = urllib.request.Request(url,data,headers)

        response = urllib.request.urlopen(req) #提取出需要的字符串并做成表格
        html = response.read().decode('utf-8')
        terget = json.loads(html)['data'][0]['v']
        terget = terget.replace('[','').split(']')[0]

        return terget
    except Exception:
        return word

def modular(word):#模块转换

    target = ''.join((pypinyin.pinyin(word))[0])#将结果转换为字符串

    return target

def trans(word):

    try:

        word = modular(word)

        return word

    except Exception:#如果模块出错，就网上爬取

        word = spider(word)

        return word

if __name__ == '__main__': #测试
    while True:
        word = input('输入：')
        print (trans(word))


from setuptools import setup

__author__ = 'Sempr'

setup(
    name='taobaopy',
    version='5',
    url='https://github.com/sempr/taobaopy',
    license='BSD',
    author='Fred Wang',
    author_email='taobao-pysdk@1e20.com',
    description='A Very Easy Learned Python3 SDK For TaoBao.com API',
    long_description=__doc__,
    packages=['taobaopy'],
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=['requests >= 2.4.3'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
)


from django.urls import path
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('',views.index,name='home'),
    path('movies',views.movies,name='movies'),
    path('celebrities',views.celebrities,name='celebrities'),
    path('top-movies',views.topmovies,name='topmovies'),
    path('blog',views.blog,name='blog'),
    path('blog-details',views.blogdetails,name='blogdetails'),
    path('movie-details',views.moviedetails,name='moviedetails'),
]

urlpatterns += staticfiles_urlpatterns()


import torch as th
import numpy as np
# Note: please don't import any new package. You should solve this problem using only the package(s) above.
#-------------------------------------------------------------------------

'''
    Problem 1: Softmax Regression (with PyTorch) (12 points)
    In this problem, you will implement the softmax regression for multi-class classification problems.
The main goal of this problem is to get familiar with the PyTorch package for deep learning methods.

    -------------------------
    Package(s) to Install:
        Please install python version 3.7 or above and the following package(s):
        * torch (for building deep learning models)
    How to Install:
        * torch: To install 'torch' using pip, you could type in the terminal:
            python3 -m pip install torch
    -------------------------
    A list of all variables being used in this problem is provided at the end of this file.
'''

#--------------------------
def Terms_and_Conditions():
    '''
        By submitting this homework or changing this function, you agree with the following terms:
       (1) Not sharing your code/solution with any student before and after the homework due. For example, sending your code segment to another student, putting your solution online or lending your laptop (if your laptop contains your solution or your Dropbox automatically copied your solution from your desktop computer and your laptop) to another student to work on this homework will violate this term.
       (2) Not using anyone's code in this homework and building your own solution. For example, using some code segments from another student or online resources due to any reason (like too busy recently) will violate this term. Changing other's code as your solution (such as changing the variable names) will also violate this term.
       (3) When discussing with any other students about this homework, only discuss high-level ideas or use pseudo-code. Don't discuss about the solution at the code level. For example, two students discuss about the solution of a function (which needs 5 lines of code to solve) and they then work on the solution "independently", however the code of the two solutions are exactly the same, or only with minor differences (variable names are different). In this case, the two students violate this term.
      All violations of (1),(2) or (3) will be handled in accordance with the WPI Academic Honesty Policy.  For more details, please visit: https://www.wpi.edu/about/policies/academic-integrity/dishonesty
      Note: we may use the Stanford Moss system to check your code for code similarity. https://theory.stanford.edu/~aiken/moss/
      Historical Data: in one year, we ended up finding 25% of the students in that class violating this term in their homework submissions and we handled ALL of these violations according to the WPI Academic Honesty Policy.
    '''
    #*******************************************
    # CHANGE HERE: if you have read and agree with the term above, change "False" to "True".
    Read_and_Agree = True
    #*******************************************
    return Read_and_Agree

#----------------------------------------------------
'''
    Given a softmax regression model with parameters W and b, please compute the linear logits z on a mini-batch of data samples x1, x2, ... x_batch_size. In the mean time, please also connect the global gradients of the linear logits z (dL_dz) with the global gradients of the weights dL_dW and the biases dL_db in the PyTorch tensors.
    ---- Inputs: --------
        * x: the feature vectors of a mini-batch of data samples, a float torch tensor of shape (batch_size, p).
        * W: the weight matrix of softmax regression, a float torch Tensor of shape (p by c).
        * b: the bias values of softmax regression, a float torch vector of length c.
    ---- Outputs: --------
        * z: the linear logits on a mini-batch of data samples, a float torch tensor of shape (batch_size, c).
    ---- Hints: --------
        * When computing z values, in order to connect the global gradients dL_dz with dL_dW and dL_db, you may want to use the operators in PyTorch, instead of in NumPy or Python. For example, np.dot() is the numpy product of two numpy arrays, which will only compute the values z correctly, but cannot connect the global gradients of the torch tensors W and b. Instead, you may want to find the PyTorch version of dot product for two torch tensors.
        * For PyTorch tensors, A@B represents the matrix multiplication between two torch matrices A and B.
        * This problem can be solved using 1 line(s) of code.
'''
#---------------------
def compute_z(x, W, b):
    #########################################
    ## INSERT YOUR CODE HERE (2 points)
    z = x@W + b
    #########################################
    return z
    #-----------------
    '''
        TEST: Now you can test the correctness of your code above by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py:test_compute_z
        --- OR ----
        python3 -m nose -v test1.py:test_compute_z
        --- OR ----
        python -m nose -v test1.py:test_compute_z
        ---------------------------------------------------
    '''

#----------------------------------------------------
'''
    Suppose we are given a softmax regression model and we have already computed the linear logits z on a mini-batch of training samples. Suppose the labels of the training samples are in y. Please compute the average loss of the softmax regression model on the mini-batch of training samples. In the mean time, please also connect the global gradients of the linear logits z (dL_dz) with the loss L correctly.
    ---- Inputs: --------
        * z: the linear logits on a mini-batch of data samples, a float torch tensor of shape (batch_size, c).
        * y: the labels of a mini-batch of data samples, a torch integer vector of length batch_size. The value of each element can be 0,1,2, ..., or (c-1).
    ---- Outputs: --------
        * L: the average multi-class cross entropy loss on a mini-batch of training samples, a torch float scalar.
    ---- Hints: --------
        * The loss L is a scalar, computed from the average of the cross entropy loss on all samples in the mini-batch. For example, if the loss on the four training samples are 0.1, 0.2, 0.3, 0.4, then the final loss L is the average of these numbers as (0.1+0.2+0.3+0.4)/4 = 0.25.
        * You could use CrossEntropyLoss in PyTorch to compute the loss.
        * This problem can be solved using 1 line(s) of code.
'''
#---------------------
def compute_L(z, y):
    #########################################
    ## INSERT YOUR CODE HERE (2 points)
    L = th.nn.CrossEntropyLoss(reduction='mean')(z, y)
    #########################################
    return L
    #-----------------
    '''
        TEST: Now you can test the correctness of your code above by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py:test_compute_L
        --- OR ----
        python3 -m nose -v test1.py:test_compute_L
        --- OR ----
        python -m nose -v test1.py:test_compute_L
        ---------------------------------------------------
    '''

#----------------------------------------------------
'''
    (Gradient Descent) Suppose we are given a softmax regression model with parameters (W and b) and we have a mini-batch of training data samples (x,y).  Suppose we have already computed the global gradients of the average loss L w.r.t. the weights W on the mini-batch of data samples. Assume that we have already created an optimizer for the parameter W and b. Please update the weights W and b using gradient descent. After the update, the global gradients of W and b should be set to all zeros.
    ---- Inputs: --------
        * optimizer: a PyTorch optimizer (such as SGD, ADAM, RMSProp) to handle the gradient descent for parameters in the model (W and b).
    ---- Hints: --------
        * Although the parameters W and b are NOT given explicitly in the input of this function, but we can assume the W and b are already properly configured in the optimizer. So the optimizer is configured to handle the parameters W and b.
        * Although the gradients of the parameters dL_dW and dL_db are NOT given explicitly in the input of this function, but we can assume that in the PyTorch tensors W and b, the gradients are already properly computed and are stored in W.grad (for dL_dW) and b.grad (for dL_db).
        * Although the learning rate is NOT given explicitly in the input of this function, but we can assume that the optimizer was already configured with the learning rate parameter.
        * This problem can be solved using 2 line(s) of code.
'''
#---------------------
def update_parameters(optimizer):
    #########################################
    ## INSERT YOUR CODE HERE (2 points)
    optimizer.step()
    optimizer.zero_grad()
    #########################################
    #-----------------
    '''
        TEST: Now you can test the correctness of your code above by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py:test_update_parameters
        --- OR ----
        python3 -m nose -v test1.py:test_update_parameters
        --- OR ----
        python -m nose -v test1.py:test_update_parameters
        ---------------------------------------------------
    '''

#----------------------------------------------------
'''
    (Training Softmax Regression) Given a training dataset X (features), Y (labels) in a data loader, train the softmax regression model using mini-batch stochastic gradient descent: iteratively update the weights W and biases b using the gradients on each mini-batch of random data samples.  We repeat n_epoch passes over all the training samples.
    ---- Inputs: --------
        * data_loader: the PyTorch loader of a dataset.
        * c: the number of classes in the classification task, an integer scalar.
        * p: the number of input features.
        * alpha: the step-size parameter of gradient descent, a float scalar.
        * n_epoch: the number of passes to go through the training dataset in the training process, an integer scalar.
    ---- Outputs: --------
        * W: the weight matrix of softmax regression, a float torch Tensor of shape (p by c).
        * b: the bias values of softmax regression, a float torch vector of length c.
    ---- Hints: --------
        * Step 1 Forward pass: compute the linear logits and loss.
        * Step 2 Back propagation: compute the gradients of W and b.
        * Step 3 Gradient descent: update the parameters W and b using gradient descent.
        * This problem can be solved using 4 line(s) of code.
'''
#---------------------
def train(data_loader, c, p, alpha=0.001, n_epoch=100):
    W = th.randn(p,c, requires_grad=True) # initialize W randomly using standard normal distribution
    b = th.zeros(c, requires_grad=True) # initialize b as all zeros
    optimizer = th.optim.SGD([W,b], lr=alpha) # SGD optimizer
    for _ in range(n_epoch): # iterate through the dataset n_epoch times
        for mini_batch in data_loader: # iterate through the dataset, with one mini-batch of random training samples (x,y) at a time
            x=mini_batch[0] # the feature vectors of the data samples in a mini-batch
            y=mini_batch[1] # the labels of the samples in a mini-batch
            #########################################
            ## INSERT YOUR CODE HERE (2 points)
            update_parameters(optimizer)
            z = compute_z(x, W, b)
            L = compute_L(z, y)
            L.backward()
            #########################################
    return W, b
    #-----------------
    '''
        TEST: Now you can test the correctness of your code above by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py:test_train
        --- OR ----
        python3 -m nose -v test1.py:test_train
        --- OR ----
        python -m nose -v test1.py:test_train
        ---------------------------------------------------
    '''

#----------------------------------------------------
'''
    (Using Softmax Regression)  Given a trained softmax regression model with parameters W and b. Suppose we have a mini-batch of test data samples. Please use the softmax regression model to predict the labels.
    ---- Inputs: --------
        * x: the feature vectors of a mini-batch of data samples, a float torch tensor of shape (batch_size, p).
        * W: the weight matrix of softmax regression, a float torch Tensor of shape (p by c).
        * b: the bias values of softmax regression, a float torch vector of length c.
    ---- Outputs: --------
        * y_predict: the predicted labels of a mini-batch of test data samples, a torch integer vector of length batch_size. y_predict[i] represents the predicted label on the i-th test sample in the mini-batch.
    ---- Hints: --------
        * This is a multi-class classification task, for each sample, the label should be predicted as the index of the largest value of each row of the linear logit z.
        * You could use the argmax() function in PyTorch to return the indices of the largest values in a tensor.
        * This problem can be solved using 2 line(s) of code.
'''
#---------------------
def predict(x, W, b):
    #########################################
    ## INSERT YOUR CODE HERE (4 points)
    z = compute_z(x, W, b)
    y_predict = th.argmax(z, 1)
    #########################################
    return y_predict
    #-----------------
    '''
        TEST: Now you can test the correctness of your code above by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py:test_predict
        --- OR ----
        python3 -m nose -v test1.py:test_predict
        --- OR ----
        python -m nose -v test1.py:test_predict
        ---------------------------------------------------
    '''

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

'''
    TEST problem 1:
        Now you can test the correctness of all the above functions by typing the following in the terminal:
        ---------------------------------------------------
        nosetests -v test1.py
        --- OR ----
        python3 -m nose -v test1.py
        --- OR ----
        python -m nose -v test1.py
        ---------------------------------------------------

        If your code passed all the tests, you will see the following message in the terminal:
        ----------- Problem 1 (12 points in total)--------------------- ... ok
        * (2 points) compute_z ... ok
        * (2 points) compute_L ... ok
        * (2 points) update_parameters ... ok
        * (2 points) train ... ok
        * (4 points) predict ... ok
        ----------------------------------------------------------------------
        Ran 5 tests in 1.489s

        OK
'''

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

#--------------------------------------------
'''
    List of All Variables

* n:  the number of data instance in the training set.
* p:  the number of input features.
* c:  the number of classes in the classification task, an integer scalar.
* batch_size:  the number of samples in a mini-batch, an integer scalar.
* x:  the feature vectors of a mini-batch of data samples, a float torch tensor of shape (batch_size, p).
* y:  the labels of a mini-batch of data samples, a torch integer vector of length batch_size. The value of each element can be 0,1,2, ..., or (c-1).
* W:  the weight matrix of softmax regression, a float torch Tensor of shape (p by c).
* b:  the bias values of softmax regression, a float torch vector of length c.
* z:  the linear logits on a mini-batch of data samples, a float torch tensor of shape (batch_size, c).
* a:  the softmax activations on a mini-batch of data samples, a float torch tensor of shape (batch_size, c).
* L:  the average multi-class cross entropy loss on a mini-batch of training samples, a torch float scalar.
* data_loader:  the PyTorch loader of a dataset.
* alpha:  the step-size parameter of gradient descent, a float scalar.
* n_epoch:  the number of passes to go through the training dataset in the training process, an integer scalar.
* y_predict:  the predicted labels of a mini-batch of test data samples, a torch integer vector of length batch_size. y_predict[i] represents the predicted label on the i-th test sample in the mini-batch.
* optimizer:  a PyTorch optimizer (such as SGD, ADAM, RMSProp) to handle the gradient descent for parameters in the model (W and b).

'''
#--------------------------------------------


import sys
import random
import numpy as np
from src.gamemaster import GAMEMASTER
from src.q_table import Q_TABLE
from src.q_agent import Q_AGENT
from src.utils import  load_input, load_qtable

def main():
	# コマンドライン引数
	args = sys.argv
	if len(args)<2:
		print('set dirname')
		print('>> main.py [dirname]')
		sys.exit()

	N, START_NODE, GOOL_NODE, R, G = load_input(args[1])
	epoch, q_table = load_qtable(args[1])
	q_agent = Q_AGENT()

	# G, Rの出力
	print('\n>> G')
	print('NODE |     R    |   g')
	for i,g in enumerate(G):
		print('%4d | %8f | '%(i+1, R[i]), g)

	# q_tableの出力
	print('\n>> q_table')
	for n, r in sorted(q_table.table.items()):
		print('%d -> %d | %f'%(n[0]+1, n[1]+1, r))

	# ルートの出力
	print('\n>> path')
	gamemaster = GAMEMASTER(q_agent, G, START_NODE, GOOL_NODE, R)
	gamemaster.start(q_table, isPrint=True, isTrain=False)

	print()

if __name__=='__main__':
	main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: TheCjw<thecjw@live.com>
# Created on 2016.11.08

__author__ = "TheCjw"

import argparse
import os
import platform
import subprocess
import sys
import time
from datetime import datetime

import frida

import colorlog
from colorlog import ColoredFormatter

handler = colorlog.StreamHandler()

formatter = ColoredFormatter(
    "%(log_color)s[%(asctime)s] [%(levelname)s]%(reset)s %(message)s",
    datefmt="%H:%M:%S",
    reset=True,
    log_colors={
        "DEBUG": "cyan",
        "INFO": "green",
        "WARNING": "yellow",
        "ERROR": "red",
        "CRITICAL": "red,bg_white",
    }
)

handler.setFormatter(formatter)

logger = colorlog.getLogger("loader")
logger.addHandler(handler)
logger.level = 10  # DEBUG

class MyArgParser(object):
    def __init__(self):

        self.frida_compile = self.__node_script_path__("frida-compile")
        self.temp_script_path = os.path.join(os.path.dirname(__file__), "out")

        parser = argparse.ArgumentParser(
            description="A frida script loader for Android/iOS app",
            usage="""{0} <command> [<args>]

""".format(os.path.basename(__file__)))

        parser.add_argument("command", help="Subcommand to run")

        if len(sys.argv) == 1:
            parser.print_help()
            sys.exit(1)

        args = parser.parse_args(sys.argv[1:2])
        if not hasattr(self, args.command):
            logger.error("Unrecognized command: {0}".format(args.command))
            parser.print_help()
            sys.exit(1)

        getattr(self, args.command)()

    @staticmethod
    def __node_script_path__(name):
        build_os = platform.system().lower()
        suffix = ".cmd" if build_os == "windows" else ""
        return os.path.abspath(os.path.join(sys.path[0], "node_modules",
                                            ".bin", name + suffix))

    @staticmethod
    def __get_application_name__(device, identifier):
        for p in device.enumerate_applications():
            if p.identifier == identifier:
                return p.name

    @staticmethod
    def __get_process_pid__(device, application_name):
        for p in device.enumerate_processes():
            if p.name == application_name:
                return p.pid
        return -1

    def __compile_javascript__(self, src, dst):
        """
        Using frida-compile convert ES6 script to ES5 script
        :param script_path:
        :param output_path:
        :return:
        """
        logger.info("Compiling {0} file with frida-compile.".format(os.path.basename(src)))
        subprocess.check_call([self.frida_compile, src, "-o", dst],
                              cwd=os.getcwd())

    def __run_and_inject__(self, package_name, script_path):
        print("[*] Staring at {0}".format(datetime.now().strftime("%H:%M:%S")))

        if os.path.isabs(script_path) is False:
            script_path = os.path.abspath(script_path)

        output_script = os.path.join(self.temp_script_path, os.path.basename(script_path))
        self.__compile_javascript__(script_path, output_script)

        script_content = open(output_script, encoding="utf-8").read()

        # Update some consts here.
        script_content = script_content.replace("__PACKAGE_NAME__", package_name)

        # FIXME: add iOS support sometime.
        device = frida.get_device_manager().enumerate_devices()[-1]

        # Kill running package.
        while True:
            pid = self.__get_process_pid__(device, package_name)
            if pid != -1:
                logger.info("killing {0}".format(pid))
                # os.system(r"adb shell am force-stop {0}".format(package))
                os.system(r"adb shell su -c \"pgrep {0} | xargs kill\"".format(package_name))
                time.sleep(0.1)
            else:
                break

        # TODO: Use PauseOnStart(Xposed Module) to suspend app at *attachBaseContext.
        os.system(r"adb shell monkey -p {0} -c android.intent.category.LAUNCHER 1".format(package_name))

        pid = -1
        for i in range(15):
            pid = self.__get_process_pid__(device, package_name)
            if pid != -1:
                break
            time.sleep(0.05)

        if pid == -1:
            logger.error("Run package {0} failed.".format(package_name))
            return

        logger.info("Injecting {0} to {1}({2})".format(os.path.basename(script_path),
                                                       package_name, pid))

        session = None
        try:
            session = frida.get_device_manager().enumerate_devices()[-1].attach(pid)
            script = session.create_script(script_content)
            script.load()
            sys.stdin.read()
        except KeyboardInterrupt:
            if session is not None:
                session.detach()
            logger.error("user aborted")

        print("[*] Shutting down at {0}".format(datetime.now().strftime("%H:%M:%S")))

    def run(self):
        """
        Spawn a new process with package name, then inject frida script.
        :return:
        """
        parser = argparse.ArgumentParser(
            description="Spawn a new process with package and inject script.")
        parser.add_argument("-p",
                            "--package",
                            type=str,
                            help="Package name of app",
                            required=True)
        parser.add_argument("-s",
                            "--script",
                            type=str,
                            help="Script to inject",
                            required=True)
        args = parser.parse_args(sys.argv[2:])
        self.__run_and_inject__(args.package, args.script)

def main():
    MyArgParser()

if __name__ == "__main__":
    main()


"""Detector functions with different imread methods"""

import ctypes
from darknet_libwrapper import *
from scipy.misc import imread
import cv2

def array_to_image(arr):
    arr = arr.transpose(2,0,1)
    c = arr.shape[0]
    h = arr.shape[1]
    w = arr.shape[2]
    arr = (arr/255.0).flatten()
    data = c_array(ctypes.c_float, arr)
    im = IMAGE(w,h,c,data)
    return im

def _detector(net, meta, image, thresh=.5, hier=.5, nms=.45):
    cuda_set_device(0)
    num = ctypes.c_int(0)
    num_ptr = ctypes.pointer(num)
    network_predict_image(net, image)
    dets = get_network_boxes(net, image.w, image.h, thresh, hier, None, 0, num_ptr)
    num = num_ptr[0]
    if (nms):
         do_nms_sort(dets, num, meta.classes, nms)

    res = []
    for j in range(num):
        for i in range(meta.classes):
            if dets[j].prob[i] > 0:
                b = dets[j].bbox
                # Notice: in Python3, mata.names[i] is bytes array from c_char_p instead of string
                res.append((meta.names[i], dets[j].prob[i], (b.x, b.y, b.w, b.h)))
    res = sorted(res, key=lambda x: -x[1])
    free_detections(dets, num)
    return res

# Darknet
net = load_network("cfg/yolov3.cfg", "yolov3.weights", 0)
meta = get_metadata("cfg/coco.data")

im = load_image_color('data/dog.jpg', 0, 0)
result = _detector(net, meta, im)
free_image(im)
print ('Darknet:\n', result)

# scipy
arr= imread('data/dog.jpg')
im = array_to_image(arr)
result = _detector(net, meta, im)
print ('Scipy:\n', result)

# OpenCV
#arr = cv2.imread('data/dog.jpg')
arr = cv2.imread('./1.png')
im = array_to_image(arr)
rgbgr_image(im)
result = _detector(net, meta, im)
print ('OpenCV:\n', result, len(result))


import numpy as np
from scipy.spatial import distance

from src import select_random

class Annotator:
    """
    Class containing methods for the explanatory_guided query selection strategy.
    """
    def select_from_worst_cluster(self, pd_points, clusters, train_idx, theta, rng, file=None):
        """
        Select index of the point to be labeled from the cluster containing largest number of wrong points.

        :param pd_points: Pandas DataFrame containing the features, the predictions and the true labels of the points
        :param clusters: The clusters (indexes of the points) found with kmedoids
        :param train_idx: The indexes of the train dataset (unlabeled points)
        :param theta: Parameter for the softmax function
        :param rng: RandomState object
        :param file: The output file

        :return: The wrongly classified points, the index of the closest wrong instance (in X)
        """
        # Find all the wrongly classified examples (model predictions vs true labels)
        wrong_points, clusters_lookup, lookup = find_wrong_points(pd_points, clusters)
        file.write("Number of wrong points: {}\n".format(len(wrong_points)))
        if not len(wrong_points):
            # If there are no more wrongly classified points, proceed with random sampling from train
            query_idx = select_random(train_idx, rng)
            return [], query_idx
        # Find the cluster with the most wrongly classified examples
        # max_key, max_value = max(lookup.items(), key=lambda x: len(x[1]))

        # Softmax
        # Using the number of wrongly classified points
        logits = [len(x) for x in lookup.values()]
        file.write("Logits using plain numbers")
        # Using a ratio of wrong points to the total number of points in known+train
        # logits = [len(x)/(pd_points.shape[0]) for x in lookup.values()]
        # file.write("Logits using ratio")

        exps = [np.exp(i * theta - max(logits)) for i in logits]
        softmax = [j / sum(exps) for j in exps]
        selected_cluster_key = rng.choice(list(lookup.keys()), p=softmax)
        selected_cluster_value = lookup.get(selected_cluster_key)
        if file is not None:
            file.write("Logits: {}, exps: {}, softmax: {}\n".format(logits, exps, softmax))
            file.write("Cluster lookup keys: {}\n".format(lookup.keys()))
            file.write("Selected_cluster_key: {}, value: {}\n".format(selected_cluster_key, selected_cluster_value))

        # Find the centroid of that custer, it's the first element in the list
        max_centroid = clusters_lookup[selected_cluster_key][0]
        # Drop the labels and predictions columns to measure distance
        pd_points_features = pd_points.copy()
        pd_points_features = pd_points_features.drop(columns=["labels", "predictions", "idx"])
        # Find the element with min proximity to the centroid for each wrongly classified point in that cluster
        closest_wrong_idx = min(selected_cluster_value, key=lambda x: distance.euclidean(
            pd_points_features.iloc[x], pd_points_features.iloc[max_centroid]))

        query_idx = int(pd_points.iloc[closest_wrong_idx].idx)
        return wrong_points, query_idx

    def select_closest(self, pd_points, clusters):
        """
        Select index of the point which lies closest to a centroid.

        :param pd_points: Pandas DataFrame containing the features, the predictions and the true labels of the points
        :param clusters:
        :return:
        """
        wrong_points, clusters_lookup, lookup = find_wrong_points(pd_points, clusters)
        if len(wrong_points) == 0:
            return [], None
        # Find the proximity to the closest centroid found with k-medoids for each wrongly classified point
        distances = dist_to_centroid(lookup, clusters_lookup, pd_points)

        closest_wrong_idx = min(distances, key=distances.get)
        # Sort them and return the wrongly classified example closest to a centorid
        query_idx = int(pd_points.iloc[closest_wrong_idx].idx)
        return wrong_points, query_idx

def find_wrong_points(pd_points, clusters):
    """
    Find wrongly classified points in the given data.

    :param pd_points: The data
    :param clusters: The clusters

    :return: The wrongly classified points, lookup for the clusters, and lookup for the wrong points
    """
    # Find the points where predictions are wrong
    wrong_points = pd_points[pd_points.labels != pd_points.predictions]
    clusters_lookup = create_clusters_lookup(clusters)
    lookup = create_lookup(wrong_points.index, clusters_lookup)

    return wrong_points, clusters_lookup, lookup

def create_clusters_lookup(clusters):
    """
    Create lookup for the clusters: the value for each key is an array of indexes of the points in the cluster.

    :param clusters: Clusters represented as arrays of indexes of points

    :return: The lookup
    """
    return {i: cluster for i, cluster in enumerate(clusters)}

def create_lookup(points, clusters_lookup):
    """
    Returns dictionary which has as keys the keys from the cluster_lookup, and the values are the wrong points in the
    corresponding cluster

    :param points: The data
    :param clusters_lookup: The lookup for the clusters

    :return: The lookup for the wrong points
    """
    lookup = {}
    for point in points:
        for key, value in clusters_lookup.items():
            if point in value:
                if key not in lookup:
                    lookup[key] = [point]
                    break
                else:
                    lookup[key].append(point)
                    break
    return lookup

def dist_to_centroid(lookup, clusters_lookup, pd_points):
    """
    Calculate distance from each wrongly classified point to the centroid of the cluster that it belongs to.

    :param lookup: Lookup for the wrong points
    :param clusters_lookup: Lookup for the clusters
    :param pd_points: The data

    :return: A dictionary containing the calculated distances for each wrongly classified point to the centroid
    """
    distances = {}
    # Remove the unnecessary columns (labels and predictions)
    pd_points_features = pd_points.drop(columns=["labels", "predictions", "idx"])
    for (key, value) in lookup.items():
        for element in value:
            centroid = clusters_lookup[key][0]
            # Calculate euclidean distance on the features
            distances[element] = distance.euclidean(pd_points_features.iloc[element], pd_points_features.iloc[centroid])
    return distances