from turtle import *

def move(xstart, ystart):
    penup()
    goto(xstart, ystart)
    pendown()

def replace_pos(x, y):
    penup()
    goto(int(xcor()) + x, int(ycor()) + y)
    pendown()

def move_and_paint(x, y):
    goto(int(xcor()) + x, int(ycor()) + y)

def polygon(num_count, side, color1, color2):
    pencolor(color1)
    fillcolor(color2)
    begin_fill()
    for count in range(num_count):
        left(360/num_count)
        forward(side)
    end_fill()

def frame(height):
    pensize(5)
    pencolor("brown")
    x = height / 2
    replace_pos(x * 1.5, 0)
    move_and_paint(0, x)
    move_and_paint(x * -3, 0)
    move_and_paint(0, x * -2)
    move_and_paint(x * 3, 0)
    move_and_paint(0, x)
    replace_pos(-2 * x, -x)

def square(side, color1, color2):
    pensize(1)
    begin_fill()
    polygon(4, side, color1, color2)
    end_fill()

def triangle(side, color1, color2):
    penup()
    forward(side/10)
    pendown()
    pensize(3)
    begin_fill()
    polygon(3, side + side/5, color1, color2)
    end_fill()

def window(side):
    penup()
    backward(side/10)
    right(90)
    forward(side/10)
    right(90)
    forward(side/10)
    pendown()
    polygon(4, side/8, "black", "cyan")

def base(size):
    penup()
    left(90)
    pendown()
    right(90)
    square(size, "brown", "darkorange")
    replace_pos(0, size)
    triangle(size, "brown", "yellow")

def house_line(count, side):
    for c in range(count):
        base(side/4)
        window(side)
        penup()
        backward(side)
        pendown()
        left(180)

def picture(height, xstart, ystart, forwardHeight):
    move(xstart, ystart)
    frame(height)
    left(90)
    penup()
    forward(forwardHeight)
    pendown()
    right(90)
    house_line(2, height)

speed(int(input("Уведіть швидкість малювання: ")))
side_for_picture = int(input("уведіть довжину від якої залежить height та width: "))
xstart = int(input("уведіть початковий X: "))
ystart = int(input("уведіть початковий Y: "))
picture(side_for_picture, xstart, ystart, side_for_picture/5)
#polygon(3, 70)
#picture(400, 0, 0, )
#triangle(100, "blue", "cyan")


# import the pygame module, so you can use it
import pygame, os.path, random
from pygame.locals import *

main_dir = os.path.split(os.path.abspath(__file__))[0]
transparent_color = (255, 0, 5)
screen_res = (640, 480)
SCREENRECT = pygame.Rect(0, 0, screen_res[0], screen_res[1])
BADGUY_RELOAD = 12

def load_image(file):
	'''loads an image, prepares it for play'''
	file = os.path.join(main_dir, 'images', file)
	surface = pygame.image.load(file)
	surface.set_colorkey(transparent_color)
	return surface.convert()

def load_images(*files):
	'''sends multiple images to load_image'''
	imgs = []
	for file in files:
		imgs.append(load_image(file))
	return imgs

class Player(pygame.sprite.Sprite):
	'''dats u'''
	speed = 10
	bounce = 24
	images = []
	def __init__(self):
		pygame.sprite.Sprite.__init__(self, self.containers)
		self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
		self.reloading = 0
		self.origtop = self.rect.top

	def move(self, direction):
		self.rect.move_ip(direction*self.speed, 0)
		self.rect = self.rect.clamp(SCREENRECT)
		self.rect.top = self.origtop - (self.rect.left//self.bounce%2)

class Badguy(pygame.sprite.Sprite):
	speed = 5
	animcycle = 12
	images = []
	def __init__(self):
		pygame.sprite.Sprite.__init__(self, self.containers)
		# pick a random badguy to be
		self.image = self.images[random.randint(0,4)-1]
		self.rect = self.image.get_rect()
		self.frame = 0
		self.direction = 1

	def update(self):
		self.rect.move_ip(self.direction*self.speed, 0)
		if not SCREENRECT.contains(self.rect):
			# classic centipede motion
			self.rect.top = self.rect.bottom + 5
			self.direction = -1 * self.direction
			self.rect = self.rect.clamp(SCREENRECT)
			if self.rect.bottom >= screen_res[1]:
				self.kill()

def main():
	pygame.init()

	# set resolution, decorate window
	screen = pygame.display.set_mode(screen_res)
	logo = load_image('logo32x32.png')
	pygame.display.set_icon(logo)
	pygame.display.set_caption('SPACE INVEIGLERS')

	running = True

	# load images, assign sprites
	background = load_image('background.png')
	Player.image = load_image('playerlg.png')
	Badguy.images = load_images('badguy1lg.png', 'badguy2lg.png', 'badguy3lg.png', 'badguy4lg.png')

	screen.blit(background, (0, 0))
	pygame.display.flip()

	# init game groups
	badguys = pygame.sprite.Group()
	all = pygame.sprite.RenderUpdates()

	# assign default groups to each sprite class
	Player.containers = all
	Badguy.containers = badguys, all
	badguyreload = BADGUY_RELOAD
	clock = pygame.time.Clock()

	#initialize our starting sprites
	player = Player()
	Badguy() #note, this 'lives' because it goes into a sprite group

	# main loop
	while player.alive():
		screen.blit(background, (0,0))
		#get input
		for event in pygame.event.get():
			if event.type == QUIT or \
				(event.type == KEYDOWN and event.key == K_ESCAPE):
					return
		keystate = pygame.key.get_pressed()

		# clear/erase the last drawn sprites
		all.clear(screen, background)

		#update all the sprites
		all.update()

		#handle player input
		direction = keystate[K_RIGHT] - keystate[K_LEFT]
		player.move(direction)

		# Create new badguy
		if badguyreload:
			badguyreload = badguyreload - 1
		elif not int(random.random() * 50):
			Badguy()
			badguyreload = BADGUY_RELOAD

		#draw the scene
		screen.blit(background, (0,0))
		dirty = all.draw(screen)
		pygame.display.update(dirty)

		#cap the framerate
		clock.tick(40)

# run the main function only if this module is executed as the main script
# (if you import this as a module then nothing is executed)
if __name__=="__main__":
	# call the main function
	main()


import re
import string
import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from sklearn.metrics.pairwise import cosine_similarity

# Download stopwords
nltk.download("stopwords")

# Load and preprocess data
data = pd.read_csv("novel_data.csv")
data["text"] = data["Title"] + " " + data["Description"]
data["text"] = data["text"].str.lower()

def preprocess_text(text):
    text = re.sub(r"\d+", "", text)  # remove numbers
    text = text.translate(str.maketrans(
        "", "", string.punctuation))  # remove punctuation
    text = text.strip()  # remove whitespace leading & trailing
    # remove multiple whitespace into single whitespace
    text = re.sub('\s+', ' ', text)
    text = re.sub(r"\b[a-zA-Z]\b", "", text)  # remove single char
    return text

for col in ['text']:
    data[col] = data[col].apply(preprocess_text)

stop_words = set(stopwords.words('indonesian') + stopwords.words('english'))

def stopwords_removal(words):
    return [word for word in words if word not in stop_words]

data['text'] = data['text'].apply(lambda x: x.split()).apply(stopwords_removal)
data['text'] = data['text'].apply(lambda x: ' '.join(x))

tagged_data = [TaggedDocument(words=doc.split(), tags=[str(i)])
               for i, doc in enumerate(data['text'])]

pvdbow_model = Doc2Vec(tagged_data, vector_size=100,
                       window=3, min_count=2, workers=6, dm=0)

data['pvdbow_vector'] = data['text'].apply(
    lambda x: pvdbow_model.infer_vector(x.split()))

# Create indices for titles
titles = data['Title']
indices = pd.Series(data.index, index=data['Title']).drop_duplicates()

def identify_input_type(input_text, data):
    """
    Identify whether the input text is a title or a description.
    """
    if input_text in data['Title'].values:
        return 'title'
    else:
        return 'description'

def preprocess_and_vectorize(text):
    """
    Preprocess the input text and convert it to a vector using the trained model.
    """
    processed_text = preprocess_text(text)
    processed_text = stopwords_removal(processed_text.split())
    return pvdbow_model.infer_vector(processed_text)

def rec_pvdbow_by_text(input_text, data=data):
    input_type = identify_input_type(input_text, data)
    recommendation = pd.DataFrame(
        columns=['Title', 'Description', 'Genre', 'Author', 'Cover', 'Score', 'Detail'])

    if input_type == 'title':
        idx = indices[input_text]
        pvdbow = cosine_similarity(
            [data['pvdbow_vector'].iloc[idx]], list(data['pvdbow_vector'])).flatten()
    else:
        input_vector = preprocess_and_vectorize(input_text)
        pvdbow = cosine_similarity(
            [input_vector], list(data['pvdbow_vector'])).flatten()

    sim_scores = list(enumerate(pvdbow))
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
    sim_scores = sim_scores[1:11]  # Get top 5 recommendations
    book_indices = [i[0] for i in sim_scores]

    for count, i in enumerate(book_indices):
        recommendation.at[count, 'Title'] = data['Title'].iloc[i]
        recommendation.at[count, 'Description'] = data['Description'].iloc[i]
        recommendation.at[count, 'Genre'] = data['Genre'].iloc[i]
        recommendation.at[count, 'Author'] = data['Author'].iloc[i]
        recommendation.at[count, 'Cover'] = data['Cover'].iloc[i]
        recommendation.at[count, 'Score'] = sim_scores[count][1]
        recommendation.at[count, 'Detail'] = data['Detail'].iloc[i]

    return recommendation


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import warnings
import time
import random

from math import sqrt
from pandas import read_csv,DataFrame
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras import backend
from keras.models import load_model

seq_len = 10
demo_day = 3

solar_data_for_valicsv =  read_csv("./process_data/data_for_real_time_prediction_new.csv")
solar_data_for_valicsv.drop(['Unnamed: 0'],axis=1, inplace=True)
df = DataFrame(solar_data_for_valicsv)
series = df.values
series = series.reshape(series.shape[0],)
result_realdata = np.array([])

for index in range(len(series) - (seq_len+1)):
	result_realdata = np.append(result_realdata , series[index: index + (seq_len+1)])
result_realdata = result_realdata.reshape(len(series)-(seq_len+1),(seq_len+1))
cut = round(0.9 * result_realdata.shape[0])
vali_data = result_realdata[int(cut):, -1]

data_num = np.loadtxt("./EMD_sequence/sub_num_real_time_new1.txt")

predicted_save = np.array([])
predicted_save_ELM = np.array([])

for run_time in range(int(data_num)):

    solar_data_for_modelcsv = read_csv("./process_data/smooth_data/smooth_data_real_time"+(str(run_time+1))+"_new1.csv")
    solar_data_for_y_test = read_csv("./EMD_sequence/series_sub_real_time"+str((run_time)+1)+"_new1.csv")
    solar_data_for_modelcsv.drop(['Unnamed: 0'],axis=1, inplace=True)
    solar_data_for_y_test.drop(['Unnamed: 0'],axis=1, inplace=True)
    solar_data_for_modelDF = DataFrame(solar_data_for_modelcsv)
    solar_data_for_y_testDF = DataFrame(solar_data_for_y_test)
    solar_data_for_modelval = solar_data_for_modelDF.values
    solar_data_for_y_testval = solar_data_for_y_testDF.values
    scaler = MinMaxScaler(feature_range=(-1, 1))
    solar_data_for_modelval = scaler.fit_transform(solar_data_for_modelval)
    solar_data_for_modelval = solar_data_for_modelval.reshape(solar_data_for_modelval.shape[0],)

    sequence_length = seq_len + 1
    result = np.array([])
    result_y_test = np.array([])

    for index in range(len(solar_data_for_modelval) - sequence_length):
    	result = np.append(result , solar_data_for_modelval[index: index + sequence_length])
    result = result.reshape(len(solar_data_for_modelval)-sequence_length,sequence_length)

    for index in range(len(solar_data_for_y_testval) - sequence_length):
    	result_y_test = np.append(result_y_test , solar_data_for_y_testval[index: index + sequence_length])
    result_y_test = result_y_test.reshape(len(solar_data_for_y_testval)-sequence_length,sequence_length)

    row = round(0.9 * result.shape[0])
    train = result[:int(row), :]
    np.random.shuffle(train)
    x_train = train[:, :-1]
    y_train = train[:, -1]
    x_test = result[int(row):, :-1]
    y_test = result_y_test[int(row):, -1]
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    model = load_model("./model/model_smooth"+str((run_time+1))+"_new1.h5")
    predicted = model.predict(x_test)

    predicted = np.reshape(predicted,(predicted.shape[0],1))
    predicted = scaler.inverse_transform(predicted)
    predicted = np.reshape(predicted,(predicted.shape[0],))

    if run_time < 1 :
    	predicted_save = np.append(predicted_save,predicted)

    else :
    	predicted_save = predicted_save + predicted

    rmselm = sqrt(mean_squared_error(y_test , predicted))
    print('RMSE FOR EMD-SSA-LSTM %ds sub-series: %f' % ((int(run_time)+1),rmselm))
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(y_test[-(57*demo_day):], label='True Data')
    plt.plot(predicted[-(57*demo_day):], label='Prediction')
    plt.legend()
    plt.savefig('./plot/EMD-SSA-LSTM-sub'+(str(run_time+1))+'.png')

rms = sqrt(mean_squared_error(vali_data, predicted_save))
print('RMSE FOR EMD-SSA-LSTM: %f' % (rms))

fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(vali_data[-(57*demo_day):], label='True Data')
plt.plot(predicted_save[-(57*demo_day):], label='Prediction')
plt.legend()
plt.savefig('./plot/EMD-SSA-LSTM total.png')

for run_time in range(int(data_num)):
    solar_datacsv = read_csv("./EMD_sequence/series_sub_real_time"+str((run_time)+1)+"_new1.csv")
    solar_datacsv.drop(['Unnamed: 0'],axis=1, inplace=True)
    solar_dataDF = DataFrame(solar_datacsv)
    solar_dataval = solar_dataDF.values
    scaler = MinMaxScaler(feature_range=(-1, 1))
    solar_dataval = scaler.fit_transform(solar_dataval)
    solar_dataval = solar_dataval.reshape(solar_dataval.shape[0],)
    sequence_length = seq_len + 1
    result = np.array([])

    for index in range(len(solar_dataval) - sequence_length):
    	result = np.append(result , solar_dataval[index: index + sequence_length])
    result = result.reshape(len(solar_dataval)-sequence_length,sequence_length)

    row = round(0.9 * result.shape[0])
    train = result[:int(row), :]
    np.random.shuffle(train)
    x_train = train[:, :-1]
    y_train = train[:, -1]
    x_test = result[int(row):, :-1]
    y_test = result[int(row):, -1]

    model = load_model("./model/model_ELM"+str((run_time)+1)+".h5")
    predicted = model.predict(x_test)

    predicted = np.reshape(predicted,(predicted.shape[0],1))
    predicted = scaler.inverse_transform(predicted)
    predicted = np.reshape(predicted,(predicted.shape[0],))

    y_test = np.reshape(y_test,(y_test.shape[0],1))
    y_test = scaler.inverse_transform(y_test)
    y_test = np.reshape(y_test,(y_test.shape[0],))

    if run_time < 1 :
        predicted_save_ELM = np.append(predicted_save_ELM,predicted)

    else :
    	predicted_save_ELM = predicted_save_ELM + predicted

    rmselm = sqrt(mean_squared_error(y_test , predicted))
    print('RMSE FOR EMD-ELM %ds sub-series: %f' % ((int(run_time)+1),rmselm))
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(y_test[-(57*demo_day):], label='True Data')
    plt.plot(predicted[-(57*demo_day):], label='Prediction')
    plt.legend()
    plt.savefig('./plot/EMD-ELM-sub'+(str(run_time+1))+'.png')

rms = sqrt(mean_squared_error(vali_data , predicted_save_ELM))
print('RMSE FOR EMD-ELM: %f' % (rms))

fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(vali_data[-(57*demo_day):], label='True Data')
plt.plot(predicted_save_ELM[-(57*demo_day):], label='Prediction')
plt.legend()
plt.savefig('./plot/EMD-ELM total.png')


from instagrapi import Client

cl = Client()
# cl.login("getcomicsx", "Hentaimanga4321")
ww=cl.media_pk_from_url("https://www.instagram.com/reel/ChhsGIMjIJC/?utm_source=ig_web_copy_link")
# xx=cl.photo_download(ww) //pic download without uname, password
# xx=cl.video_download(ww)
# pk = cl.story_pk_from_url("https://www.instagram.com/stories/missamberfields/2987568729286260276/")
# s = cl.story_info(pk)
# we=cl.story_download_by_url(s.video_url)
# xx=cl.story_download(pk)
# we=cl.album_download(ww) #album download
# we=igtv_download() # igtv download
we=cl.clip_download(ww)	 # reel donwload
print(we)


import numpy as np
import pandas as pd
df=pd.read_csv('PlayTennis.csv')
print(df)
def find_entropy(df):
    #identify the target class name
    Class=df.keys()[-1]
    #identify the class values
    values=df[Class].unique() #yes or no
    entropy=0
    for value in values:
        prob=df[Class].value_counts()[value]/len(df[Class]) #|c|/|D|
        entropy+=prob*np.log2(prob)
    return entropy
def find_entropy_attribute(df,attribute):
    Class=df.keys()[-1]
    target_values=df[Class].unique()
    #yes or no
    attribute_values=df[attribute].unique()
    #all possible attribute values like sunny,rain,outcast
    avg_entropy=0
    for value in attribute_values:
        #run with each possbile attribute values
        entropy=0
        for value1 in target_values:
            #possible values
            num=len(df[attribute][df[attribute]==value][df[Class]==value1])
            den=len(df[attribute][df[attribute]==value])
            prob=num/den
            entropy+=-prob*np.log2(prob+0.000001) #to avoid zero error,add small value
        avg_entropy+=(den/len(df))*entropy
    return np.float(avg_entropy)
def find_most_promissing(df):
  IG=[]
  for key in df.keys()[:-1]:
      IG.append(find_entropy(df)-find_entropy_attribute(df,key))
      #print(IG)
  return df.keys()[:-1][np.argmax(IG)]
def get_subtable(df,attribute,value):
  return df[df[attribute]==value].reset_index(drop=True)
def buildtree(df,tree=None):
  tree=None
  node=find_most_promissing(df) #outlook is assigned to node
  #print(node)
  attvalue=np.unique(df[node])
  #print(attvalue)
  Class=df.keys()[-1] #identify the class column
  #print(Class)
  if tree is None: #if tree is None assign outlook as parent
      tree={}
      tree[node]={}
  #print(tree)
  for value in attvalue: #each possible value of attribute,create separate table
      subtable=get_subtable(df,node,value)
      Clvalue,counts=np.unique(subtable[Class],return_counts=True)
      if len(counts)==1: #if all lable are same stop the recursion
          tree[node][value]=Clvalue[0]
      else:
          tree[node][value]=buildtree(subtable) #build the subtree for the sub data set
  return tree
tree=buildtree(df)
df1=pd.read_csv('newdata.csv')
def predict(inst,tree):
  for node in tree.keys():
      value=inst[node]
      tree=tree[node][value]
      prediction=0
      if type(tree) is dict:
          prediction=predict(inst,tree)
      else:
          prediction=tree
  return prediction
Y_label=[]
for i in range(len(df1)):
  inst=df1.iloc[i,:]
  prediction=predict(inst,tree)
  Y_label.append(prediction)
print(Y_label)


from sys import stdin
from collections import defaultdict

def get_state(board):
  scores = {c:defaultdict(int) for c in 'XO'}
  for i, line in enumerate(board):
    for j, char in enumerate(line):
      for p in scores:
        if char in p+'T':
          scores[p]['row'+str(i)] += 1
          scores[p]['col'+str(j)] += 1
          if i == j:
            scores[p]['ondiag'] += 1
          if i == 3-j:
            scores[p]['offdiag'] += 1
  mscores = [(max(d.values()), p) for p, d in scores.items() if d.values()]

  if mscores and max(mscores)[0] == 4:
    return max(mscores)[1] + ' won'

  if '.' in ''.join(board):
    return "Game has not completed"

  return "Draw"

cases = int(stdin.readline().strip())
for i in range(cases):
  board = [stdin.readline().strip() for j in range(4)]
  print("Case #{}: {}".format(i+1, get_state(board)))
  stdin.readline()


from string import punctuation
from string import *

sõnad = open("sõnad\lemmad.txt","r").read().splitlines()

tähed4 = []
tähed5 = []
tähed6 = []
tähed = ascii_lowercase + "öäüõ"
print(tähed)

for i in sõnad:

        if len(i) == 4:
            a = 0
            for j in i:
                if j in tähed:
                    a += 1
                if a == 4:
                    tähed4.append(i.lower())
        elif len(i) == 5:
            a = 0
            for j in i:
                if j in tähed:
                    a += 1
                if a == 5:
                    tähed5.append(i.lower())
        elif len(i) == 6:
            a = 0
            for j in i:
                if j in tähed:
                    a += 1
                if a == 6:
                    tähed6.append(i.lower())

with open("sonad4.txt", 'w', encoding="utf-8") as fp:
    for item in tähed4:
        # write each item on a new line
        fp.write("%s\n" % item)

with open("sonad5.txt", 'w', encoding="utf-8") as fp:
    for item in tähed5:
        # write each item on a new line
        fp.write("%s\n" % item)

with open("sonad6.txt", 'w', encoding="utf-8") as fp:
    for item in tähed6:
        # write each item on a new line
        fp.write("%s\n" % item)


# template for "Stopwatch: The Game"
import simplegui

# define global variables

num_game = 0
num_win = 0

#canvas variables
width = 300
height = 200

# drawcanvas variables
time_counter = 0
time_font_color = "White"
time_font_size = 36
time_coords = [120, height/2]
score = "0 / 0"
score_font_color = "White"
score_font_size = 18
score_coords = [240,20]

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(time_counter):
    minutes = time_counter / 600
    seconds = (time_counter /10) % 60
    tenths_seconds = time_counter % 10
    if seconds < 10:
        return str(minutes) + ":0" + str(seconds) + "." + str(tenths_seconds)
    return str(minutes) + ":" + str(seconds) + "." + str(tenths_seconds)

# define event handlers for buttons; "Start", "Stop", "Reset"
def start():
    timer.start()

def stop():
    global num_game, num_win, time_counter, score
    if timer.is_running() == True:
       timer.stop()

       num_game += 1

       score = str(num_win)+ " / " +str(num_game)

       if time_counter % 10 == 0:
          num_win += 1
       score = str(num_win)+ " / " +str(num_game)
    else:
       pass

def reset():
    global time_counter, score
    timer.stop()
    time_counter = 0
    score = "0 / 0"

# define event handler for timer with 0.1 sec interval
def tick():
    global time_counter
    time_counter += 1
    #print time_counter

# define draw handler
def draw(canvas):
    canvas.draw_text(format(time_counter), time_coords, time_font_size, time_font_color)
    canvas.draw_text(score, score_coords, score_font_size, score_font_color)

# create frame
frame = simplegui.create_frame("Stopwatch!", width, height)

# register event handlers
frame.add_button("Start", start, 200)
frame.add_button("Stop", stop, 200)
frame.add_button("Reset", reset, 200)
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100, tick)

# start frame
frame.start()
#timer.start()

# Please remember to review the grading rubric


#! /usr/bin/env python3

from __future__ import division
from cmath import pi
import rospy
import math

from MARS_msgs.msg import ParticleTelemetry

def particle_node():

    # Initiates the node
    rospy.init_node('particle_node', anonymous=True)

    # Defines the publishers needed to publish updated leader particle position
    pub = rospy.Publisher('uav0/particle_position', ParticleTelemetry, queue_size = 10)

    rate = rospy.Rate(10)

    # Defines the type of message to be sent
    msg = ParticleTelemetry()

    # Leader Particle Properties
    leader_velocity = 15 # m/s, velocity of particle along the path
    gamma_leader = 0

    # Time related variables
    start_time = rospy.get_time()
    curr_time = rospy.get_time()
    dt = 0.0

    while not rospy.is_shutdown():

        # Updates delta t every iteration
        dt = rospy.get_time() - curr_time
        curr_time = rospy.get_time()

        gamma_dot_leader = leader_velocity
        gamma_leader = gamma_leader + gamma_dot_leader*dt

        # Defining the messages
        msg.gamma = gamma_leader
        msg.gamma_dot = gamma_dot_leader

        # Publishing the message
        pub.publish(msg)

        rate.sleep()

if __name__ == '__main__':
    try:
        particle_node()
    except rospy.ROSInterruptException:
        pass


"""
Author: AruniRC
Date: Feb 2019
"""
import time
from src.utils import visualize_point_cloud_from_labels, visualize_point_cloud
import ipdb
import os
import os.path as osp
import data_utils
from data_utils.ShapeNetDataLoader import PartNormalDataset, SelfSupPartNormalDataset, ACDSelfSupDataset
from tensorboard_logger import configure, log_value
import itertools
import torch
from torch import nn
import datetime
import logging
from pathlib import Path
import sys
import importlib
import shutil
from tqdm import tqdm
import provider
import numpy as np
import sys, ipdb
from args_parser import parse_args
from testing import evaluation
from itertools import product

torch.backends.cudnn.enabled = False

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = BASE_DIR
sys.path.append(os.path.join(ROOT_DIR, 'models'))

seg_classes = {'Airplane': [0, 1, 2, 3], 'Bag': [4, 5], 'Cap': [6, 7], 'Car': [8, 9, 10, 11],
               'Chair': [12, 13, 14, 15], 'Earphone': [16, 17, 18], 'Guitar': [19, 20, 21], 'Knife': [22, 23],
               'Lamp': [24, 25, 26, 27], 'Laptop': [28, 29], 'Motorbike': [30, 31, 32, 33, 34, 35], 'Mug': [36, 37],
               'Pistol': [38, 39, 40], 'Rocket': [41, 42, 43], 'Skateboard': [44, 45, 46], 'Table': [47, 48, 49]}
classes = ['Airplane', 'Bag', 'Cap', 'Car', 'Chair', 'Earphone', 'Guitar', 'Knife', 'Lamp', 'Laptop', 'Motorbike', 'Mug', 'Pistol', 'Rocket', 'Skateboard', 'Table']
classes_parts = {0: [0, 1, 2, 3], 1: [4, 5], 2: [6, 7], 3: [8, 9, 10, 11],
                 4: [12, 13, 14, 15], 5: [16, 17, 18], 6: [19, 20, 21], 7: [22, 23],
                 8: [24, 25, 26, 27], 9: [28, 29], 10: [30, 31, 32, 33, 34, 35], 11: [36, 37],
                 12: [38, 39, 40], 13: [41, 42, 43], 14: [44, 45, 46], 15: [47, 48, 49]}

# ipdb.set_trace()

def to_categorical(y, num_classes):
    """ 1-hot encodes a tensor """
    new_y = torch.eye(num_classes)[y.cpu().data.numpy(),]
    if (y.is_cuda):
        return new_y.cuda()
    return new_y

def train_init_class(classifier, criterion, trainDataLoader, num_classes, num_part):
    """ Pre-train the classifier layer using logistic regression """
    optim = torch.optim.SGD(classifier.conv2.parameters(), lr=0.1, momentum=0.5)
    num_epoch = 500

    for epoch in range(num_epoch):
        print('Init Classifier: Epoch (%d/%d):' % (epoch + 1, num_epoch))
        mean_correct = []
        mean_loss = []
        for batch_id, (points, label, target) in enumerate(trainDataLoader):
            cur_batch_size, NUM_POINT, _ = points.size()
            points = points.data.numpy()
            points[:, :, 0:3] = provider.random_scale_point_cloud(points[:, :, 0:3])
            points[:, :, 0:3] = provider.shift_point_cloud(points[:, :, 0:3])
            points = torch.Tensor(points)
            points, label, target = points.float().cuda(), label.long().cuda(), target.long().cuda()
            points = points.transpose(2, 1)
            optim.zero_grad()

            classifier = classifier.eval()  # batch stats aren't updated

            '''applying supervised cross-entropy loss'''
            seg_pred, trans_feat, feat = classifier(points, to_categorical(label, num_classes))
            seg_pred = seg_pred.contiguous().view(-1, num_part)
            target = target.view(-1, 1)[:, 0]
            pred_choice = seg_pred.data.max(1)[1]
            correct = pred_choice.eq(target.data).cpu().sum()

            mean_correct.append(correct.item() / (cur_batch_size * NUM_POINT))

            loss = criterion(seg_pred, target, trans_feat)
            loss.backward()
            optim.step()
            mean_loss.append(loss.item())
            print('classifier: batch (%d/%s) Loss: %f Acc:%f' % (batch_id,
                                                                 len(trainDataLoader),
                                                                 loss.item(),
                                                                 mean_correct[-1]))

        log_value('init_cls_loss', np.mean(mean_loss), epoch)
        log_value('init_cls_acc', np.mean(mean_correct), epoch)
    classifier = classifier.train()

    return classifier

def main(args):
    metrics = {'best_acc': 0, 'best_epoch': 0,'best_class_avg_miou': 0, 'best_instance_avg_miou': 0, 'best_chamfer_loss': np.inf}

    def log_string(str):
        logger.info(str)
        print(str)

    '''CUDA ENV SETTINGS'''
    if args.gpu is not None:
        os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu

    if args.cudnn_off:
        torch.backends.cudnn.enabled = False  # needed on gypsum!

    # --------------------------------------------------------------------------
    '''CREATE DIR'''
    # --------------------------------------------------------------------------
    timestr = str(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M'))
    experiment_dir = Path('log/')
    experiment_dir.mkdir(exist_ok=True)
    experiment_dir = experiment_dir.joinpath('part_seg_shapenet')
    experiment_dir.mkdir(exist_ok=True)
    if args.log_dir is None:
        experiment_dir = experiment_dir.joinpath(timestr)
    else:
        # if args.k_shot > 0:
        dir_name = args.model + '_ShapeNet_' + \
                   '_k-%d_seed-%d_lr-%.6f_lr-step-%d_lr-decay-%.2f_wt-decay-%.6f_l2norm-%d' \
                   % (args.k_shot, args.seed, args.learning_rate,
                      args.step_size, args.lr_decay, args.decay_rate,
                      int(args.l2_norm))
        if args.normal:
            dir_name = dir_name + '_normals'
        if args.category:
            dir_name = dir_name + '_category-label'
        if args.selfsup:
            dir_name = dir_name + '_selfsup-%s_margin-%.2f_lambda-%.2f' \
                       % (args.ss_dataset, args.margin, args.lmbda)
        if args.anneal_lambda:
            dir_name = dir_name + '_anneal-lambda_step-%d_rate-%.2f' \
                       % (args.anneal_step, args.anneal_rate)

        if args.quantile or args.msc_iterations:
            dir_name = dir_name + '_quantile-{}_msc-its-{}_max-num-clusters-{}_alpha-{}_beta-{}'.format(args.quantile,
                                                                                args.msc_iterations,
                                                                                args.max_num_clusters, args.alpha, args.beta)

        experiment_dir = experiment_dir.joinpath(dir_name)
        # else:
        #     experiment_dir = experiment_dir.joinpath(args.log_dir)

    experiment_dir.mkdir(exist_ok=True)
    checkpoints_dir = experiment_dir.joinpath('checkpoints/')
    checkpoints_dir.mkdir(exist_ok=True)
    log_dir = experiment_dir.joinpath('logs/')
    log_dir.mkdir(exist_ok=True)
    # --------------------------------------------------------------------------
    '''LOG'''
    # --------------------------------------------------------------------------
    logger = logging.getLogger("Model")
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = logging.FileHandler('%s/%s.txt' % (log_dir, args.model))
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    log_string('PARAMETERS ...')
    log_string(args)
    configure(log_dir)                                             # tensorboard logdir

    # --------------------------------------------------------------------------
    '''DATA LOADERS'''
    # --------------------------------------------------------------------------
    root = 'ShapeSelfSup/dataset/shapenetcore_partanno_segmentation_benchmark_v0_normal'

    TRAIN_DATASET = PartNormalDataset(root=root, npoints=args.npoint, split=args.train_split, normal_channel=args.normal, k_shot=args.k_shot)
    trainDataLoader = torch.utils.data.DataLoader(TRAIN_DATASET, batch_size=args.batch_size, shuffle=True, num_workers=4)

    trainDataIterator = iter(trainDataLoader)

    TEST_DATASET = PartNormalDataset(root=root, npoints=args.npoint, split=args.eval_split, normal_channel=args.normal)

    log_string("The number of training data is: %d" % len(TRAIN_DATASET))

    num_classes = args.num_classes
    num_part = args.num_parts

    if args.selfsup:
        log_string('Use self-supervision - alternate batches')
        if not args.retain_overlaps:
            log_string('\tRemove overlaps between labeled and self-sup datasets')
            labeled_fns = list(itertools.chain(*TEST_DATASET.meta.values())) \
                          + list(itertools.chain(*TRAIN_DATASET.meta.values()))
        else:
            log_string('\tUse all files in self-sup dataset')
            labeled_fns = []
        if args.ss_dataset == 'dummy':
            log_string('Using "dummy" self-supervision dataset (rest of labeled ShapeNetSeg)')
            SELFSUP_DATASET = SelfSupPartNormalDataset(root=root, npoints=args.npoint,
                                                       split='train', normal_channel=args.normal,
                                                       k_shot=args.n_cls_selfsup, labeled_fns=labeled_fns)
        elif args.ss_dataset == 'acd':
            log_string('Using "ACD" self-supervision dataset (ShapeNet Seg)')
            ACD_ROOT = args.ss_path
            SELFSUP_DATASET = ACDSelfSupDataset(root=ACD_ROOT, npoints=args.npoint,
                                                normal_channel=args.normal,
                                                k_shot=args.n_cls_selfsup,
                                                exclude_fns=labeled_fns, prefetch=False)

        selfsupDataLoader = torch.utils.data.DataLoader(SELFSUP_DATASET,
                                                        batch_size=args.batch_size,
                                                        shuffle=True, num_workers=1)
        selfsupIterator = iter(selfsupDataLoader)

    '''MODEL LOADING'''

    MODEL = importlib.import_module(args.model)
    shutil.copy('ShapeSelfSup/models/%s.py' % args.model, str(experiment_dir))
    shutil.copy('ShapeSelfSup/models/pointnet_util.py', str(experiment_dir))
    if args.reconstruct:
        log_string('Reconstruction................................')
    if args.extra_layers:
        log_string('Extra Layers..................................')
    if 'dgcnn' in args.model:
        print('DGCNN params')
        classifier = MODEL.get_model(num_part, normal_channel=args.normal, k=args.dgcnn_k).cuda()
    else:
        classifier = MODEL.get_model(num_part, normal_channel=args.normal, reconstruct=args.reconstruct, extra_layers=args.extra_layers, num_charts=args.num_charts, num_points=args.num_points).cuda()

    criterion = MODEL.get_loss().cuda()

    if args.selfsup:
        selfsupCriterion = MODEL.get_selfsup_loss(margin=args.margin).cuda()
        log_string("The number of self-sup data is: %d" % len(SELFSUP_DATASET))
    else:
        log_string("No Self Supervision..........................................")

    def weights_init(m):
        classname = m.__class__.__name__
        if classname.find('Conv2d') != -1:
            torch.nn.init.xavier_normal_(m.weight.data)
            torch.nn.init.constant_(m.bias.data, 0.0)
        elif classname.find('Linear') != -1:
            torch.nn.init.xavier_normal_(m.weight.data)
            torch.nn.init.constant_(m.bias.data, 0.0)
    if torch.cuda.device_count() > 1:
        log_string("Let's use {} GPUs!".format(torch.cuda.device_count()))
        classifier = nn.DataParallel(classifier)

    if args.optimizer == 'Adam':
        optimizer = torch.optim.Adam(
            classifier.parameters(),
            lr=args.learning_rate,
            betas=(0.9, 0.999),
            eps=1e-08,
            weight_decay=args.decay_rate
            )
    else:
        optimizer = torch.optim.SGD(classifier.parameters(), lr=args.learning_rate, momentum=0.9)

    if args.pretrained_model is None:
        # Default: load saved checkpoint from experiment_dir or start from scratch
        try:
            checkpoint = torch.load(str(experiment_dir) + '/checkpoints/best_model.pth')
            start_epoch = checkpoint['epoch']
            classifier.load_state_dict(checkpoint['model_state_dict'])
            optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
            log_string('Use pretrained model from checkpoints')
        except:
            log_string('No existing model, starting training from scratch...')
            start_epoch = 0
            classifier = classifier.apply(weights_init)
    else:
        # Path to a pre-trained model is provided (self-sup)
        log_string('Loading pretrained model from %s' % args.pretrained_model)
        start_epoch = 0
        ckpt = torch.load(args.pretrained_model)
        classifier.load_state_dict(ckpt['model_state_dict'])
    def bn_momentum_adjust(m, momentum):
        if isinstance(m, torch.nn.BatchNorm2d) or isinstance(m, torch.nn.BatchNorm1d):
            m.momentum = momentum

    LEARNING_RATE_CLIP = 1e-5
    MOMENTUM_ORIGINAL = 0.1
    MOMENTUM_DECAY = 0.5
    MOMENTUM_DECAY_STEP = args.step_size

    #if torch.cuda.device_count() > 1:
    #    log_string("Let's use {} GPUs!".format(torch.cuda.device_count()))
    #    classifier = nn.DataParallel(classifier)
    if args.category:
        log_string("Using one hot")

    # --------------------------------------------------------------------------
    ''' MODEL TRAINING '''
    # --------------------------------------------------------------------------

    global_epoch = 0

    if args.pretrained_model is not None:
        if args.init_cls:
            # Initialize the last layer of loaded model using logistic regression
            classifier = train_init_class(classifier, criterion, trainDataLoader, num_classes, num_part)
    if args.if_cuboid:
        print('Using Cuboid as Primitive..................')
    else:
        print('Using Ellipsoid as Primitive...............')

    if args.include_convex_loss:
        print('Using Convex Fitting/Convex Loss with lambda - {}.........................'.format(args.lmbda))
    if args.include_intersect_loss:
        print('Using Intersection Loss with alpha - {}..................................'.format(args.alpha))
        if args.include_pruning:
            print('Pruning Ellipsoids...................................................')
    if args.include_entropy_loss:
        print('Using Entropy Loss with beta - {}........................................'.format(args.beta))
    print('Using Categorical Cross Entropy Loss for Semantic Segmentation')

    for epoch in range(start_epoch, args.epoch):
        log_string('Epoch %d (%d/%s):' % (global_epoch + 1, epoch + 1, args.epoch))

        '''Adjust learning rate and BN momentum'''
        lr = max(args.learning_rate * (args.lr_decay ** (epoch // args.step_size)), LEARNING_RATE_CLIP)
        log_string('Learning rate:%f' % lr)
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
        mean_correct = []
        momentum = MOMENTUM_ORIGINAL * (MOMENTUM_DECAY ** (epoch // MOMENTUM_DECAY_STEP))
        if momentum < 0.01:
            momentum = 0.01
        print('BN momentum updated to: %f' % momentum)
        classifier = classifier.apply(lambda x: bn_momentum_adjust(x, momentum))

        ''' Adjust (anneal) self-sup lambda '''
        if args.anneal_lambda:
            lmbda = args.lmbda * (args.anneal_rate ** (epoch // args.anneal_step))
        else:
            lmbda = args.lmbda

        '''learning one epoch'''
        num_iters = len(trainDataLoader)  # num iters in an epoch
        if args.selfsup:
            num_iters = len(selfsupDataLoader)  # calc an epoch based on self-sup dataset
        for i in tqdm(list(range(num_iters)), total=num_iters, smoothing=0.9, desc='Training'):
            # ------------------------------------------------------------------
            #   SUPERVISED LOSS
            # ------------------------------------------------------------------
            try:
                data = next(trainDataIterator)
            except StopIteration:
                # reached end of this dataloader
                trainDataIterator = iter(trainDataLoader)
                data = next(trainDataIterator)

            points, label, target = data

            class_list = [classes[label[idx, :].data] for idx in range(label.size()[0])]
            '''label_list = [label[label_id].item() for label_id in range(label.size()[0])]
            target_list = [torch.unique(target[idx, :]).data.tolist() for idx in range(target.size()[0])]
            for idx in range(len(label_list)):
                for item in target_list[idx]:
                    if item not in classes_parts[label_list[idx]]:
                        print(target_list[idx], '-', classes_parts[label_list[idx]])
                        print('incorrect-exiting................................ at its - ', i)
                        break
            '''

            cur_batch_size, NUM_POINT, _ = points.size()
            points = points.data.numpy()
            points[:, :, 0:3] = provider.random_scale_point_cloud(points[:, :, 0:3])
            points[:, :, 0:3] = provider.shift_point_cloud(points[:, :, 0:3])
            points = torch.Tensor(points)
            points, label, target = points.float().cuda(), label.long().cuda(), target.long().cuda()
            points = points.transpose(2, 1)
            if args.category:
                category_label = to_categorical(label, num_classes).contiguous()
            else:
                category_label = torch.zeros([label.shape[0], 1, num_classes]).cuda()

            optimizer.zero_grad()
            classifier.train()

            '''applying supervised cross-entropy loss'''
            try:                                                                  #iteration issue at 583 its. uneven distribution of datapoints among GPUs.
                seg_pred, trans_feat, feat, _, _ = classifier(points.contiguous(), category_label, include_convex_loss=False)
            except TypeError as t:
                continue
            seg_pred = seg_pred.contiguous().view(-1, num_part)
            target = target.view(-1, 1)[:, 0]
            pred_choice = seg_pred.data.max(1)[1]
            correct = pred_choice.eq(target.data).cpu().sum()

            mean_correct.append(correct.item() / (cur_batch_size * NUM_POINT))
            loss_sup = criterion(seg_pred, target, trans_feat)

            loss_sup.backward()
            optimizer.step()

            # ------------------------------------------------------------------
            #   SELF-SUPERVISED LOSS
            # ------------------------------------------------------------------
            if args.selfsup:
                try:
                    data_ss = next(selfsupIterator)
                except StopIteration:
                    # reached end of this dataloader
                    selfsupIterator = iter(selfsupDataLoader)
                    data_ss = next(selfsupIterator)

                points, chamfer_points, label, target = data_ss
                #points, label, target = data_ss
                points = points.data.numpy()
                points[:, :, 0:3] = provider.random_scale_point_cloud(points[:, :, 0:3])
                points[:, :, 0:3] = provider.shift_point_cloud(points[:, :, 0:3])
                points = torch.Tensor(points)
                ############################CHAMFER POINTS###############################################
                chamfer_points = chamfer_points.data.numpy()
                chamfer_points[:, :, 0:3] = provider.random_scale_point_cloud(chamfer_points[:, :, 0:3])
                chamfer_points[:, :, 0:3] = provider.shift_point_cloud(chamfer_points[:, :, 0:3])
                chamfer_points = torch.Tensor(chamfer_points)
                ############################CHAMFER POINTS###############################################
                points, chamfer_points, label, target = points.float().cuda(), chamfer_points.float().cuda(), label.long().cuda(), target.long().cuda()
                #points, label, target = points.float().cuda(), label.long().cuda(), target.long().cuda()
                points = points.transpose(2, 1)
                chamfer_points = chamfer_points.transpose(2, 1)
                # for self-sup category label is always unknown, so always zeros:
                category_label = torch.zeros([label.shape[0], 1, num_classes]).cuda()
                if args.normal:
                    # put dummy cols of zeros for normals in self-sup data
                    cur_batch_size, _, NUM_POINT = points.size()
                    points = points[:, 0:3, :]
                    points = torch.cat([points, torch.zeros([cur_batch_size, 3, NUM_POINT]).cuda()], 1)

                optimizer.zero_grad()
                classifier.train()

                '''applying self-supervised Ellipsoid Fitting (Convex) loss'''
                #quantile_list = [0.02, 0.03, 0.05]
                points = chamfer_points[:, :, np.random.choice(5000, 2048, replace=False)]
                #print(chamfer_points.shape)
                #ipdb.set_trace()
                _, _, feat, loss_self_sup, chamfer_loss = classifier(points, category_label, if_cuboid=args.if_cuboid, chamfer_points=chamfer_points, include_convex_loss=args.include_convex_loss, include_intersect_loss=args.include_intersect_loss, include_entropy_loss=args.include_entropy_loss, include_pruning=args.include_pruning, quantile=args.quantile, msc_iterations=args.msc_iterations, max_num_clusters=args.max_num_clusters, alpha=args.alpha, beta=args.beta, batch_id=i, epoch=epoch, class_list=class_list, evaluation=False)
                ss_loss = torch.mean(loss_self_sup) * lmbda
                #print('loss: ', ss_loss.requires_grad)
                if i % 100 == 0:
                    print('Final Loss: ', ss_loss.item())
                    sys.stdout.flush()
                ss_loss.backward()
                optimizer.step()

        # ----------------------------------------------------------------------
        #   Logging metrics after one epoch
        # ----------------------------------------------------------------------
        train_instance_acc = np.mean(mean_correct)
        log_string('Train accuracy is: %.5f' % train_instance_acc)
        log_string('Supervised loss is: %.5f' % loss_sup.data)
        # log_value('train_loss', loss_sup.data, epoch)

        if args.selfsup:
            log_string('Self-sup loss is: %.5f' % ss_loss.data)
            # log_value('selfsup_loss', ss_loss.data, epoch)

        # save every epoch
        savepath = str(checkpoints_dir) + ('/model_%03d.pth' % (epoch+1))
        log_string('Saving model at %s' % savepath)
        state = {
            'epoch': epoch,
            'train_acc': train_instance_acc,
            'model_state_dict': classifier.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
        }
        torch.save(state, savepath)
        log_string('Saved model.')
        log_value('train_acc', train_instance_acc, epoch)
        log_value('train_lr', lr, epoch)
        log_value('train_bn_momentum', momentum, epoch)
        log_value('selfsup_lambda', lmbda, epoch)

        global_epoch += 1

    # ----------------------------------------------------------------------
    #   Evaluation on test-set after completing training epochs
    # ----------------------------------------------------------------------
        return_metrics = evaluation(args, epoch, classifier, metrics)

if __name__ == '__main__':

    args = parse_args()
    main(args)


x=int(input("Введите целое X "))
x2 = x
count = 0
while (x2 > 1):
    x2 /= 10
    count += 1
#print(count)
summa = 0
x2=x
for i in range(0, count):
    step = int(x2 / 10**(count-1-i))
    #print(step)
    summa += step
    #print(summa)
    x2 -= step*10**(count-1-i)
    #print(x2)
print(summa)


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

"""
实现统计一篇英文文章内每个单词的出现频率，并返回出现频率最高的前10个单词及其出现次数

"""

import os
import re
from collections import Counter
from optparse import OptionParser

def word_count(filename, num=10):
    with open(filename, "r") as fd:
        all = Counter()
        for line in fd.readlines():
            count = Counter(re.split(r"[^a-zA-Z0-9-]+", line))
            print(count)
            all.update(count)

        all[''] =0

        return all.most_common(num)

if __name__ == "__main__":
    usage = """
    %prog file_name
    """

    parser = OptionParser(usage=usage)
    parser.add_option("--file", dest="filename", help="file to count the words")

    (options, args) = parser.parse_args()

    if not options.filename or not os.path.exists(options.filename):
        parser.print_help()
        exit(1)

    count = word_count(filename=options.filename)
    for k, v in count:
        print(k, v)


import os
import glob
import copy
import yaml
import io
import numpy as np
import argparse

from pypeit.scripts import scriptbase

from pypeit.pypeitsetup import PypeItSetup
from pypeit import inputfiles, msgs
from pypeit.scripts import run_pypeit
from pypeit.spectrographs.util import load_spectrograph
from pypeit import utils

from IPython import embed

class QLKeckDEIMOS(scriptbase.ScriptBase):

    @classmethod
    def name(cls):
        """
        Return the name of the executable.
        """
        return 'pypeit_ql_keck_deimos'

    @classmethod
    def get_parser(cls, width=None):
        import argparse
        parser = super().get_parser(description='Pypeit QL for Keck/DEIMOS',
                                    width=width, formatter=argparse.RawDescriptionHelpFormatter)
        parser = argparse.ArgumentParser(description='Script to run PypeIt in QuickLook on a set of '
                                                    'Keck/DEIMOS files',
                                        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        parser.add_argument('full_rawpath', type=str, help='Full path to the raw files')
        parser.add_argument('--redux_path', type=str,
                            help='Path to where reduction products lie')
        parser.add_argument('--root', type=str, help='Root of filenames, eg.  DE.2018')
        parser.add_argument('--calibs_only', default=False, action='store_true',
                            help='Run on calibs only')
        parser.add_argument('--science', type=str, help='Science frame filename')
        parser.add_argument('-b', '--box_radius', type=float,
                            help='Set the radius for the boxcar extraction (arcsec)')
        parser.add_argument('-d', '--det', type=int, default=0,
                            help='Detector number. Cannot use with --slit_spat')
        parser.add_argument('--ignore_headers', default=False, action='store_true',
                            help='Ignore bad headers?')
        parser.add_argument('--user_pixflat', type=str,
                            help='Use a user-supplied pixel flat (e.g. keck_lris_blue)')
        parser.add_argument('--maskID', type=int,
                            help='Reduce this slit as specified by the maskID value')
        parser.add_argument('--slit_spat', type=str,
                            help='Reduce only this slit on this detector DET:SPAT_ID, e.g. 0:175')

        return parser

    @staticmethod
    def main(pargs):

        raise IOError("RUN QL_MOS")
        spectrograph_name = 'keck_deimos'

        # Afternoon calibs
        if pargs.calibs_only:
            if pargs.root is None:
                msgs.error("Need to set --root when using --calibs_only")
            msgs.info("Processing calibrations only")
            process_calibs(pargs, spectrograph_name)
            return

        # Slurp the afternoon runs and grab the right PypeIt file
        calib_pypeit_file, ps_sci = get_science_setup(pargs, spectrograph_name)

        # Run on the science frame
        run_on_science(pargs, calib_pypeit_file, ps_sci)

def process_calibs(pargs, spectrograph_name:str):
    """
    Process the calibration files

    Args:
        pargs (argparse.ArgumentParser):
            Command line arguments
        spectrograph_name (str):
    """
    # Slurp
    output_path = pargs.redux_path

    # Run setup
    ps = PypeItSetup.from_file_root(os.path.join(pargs.full_rawpath, pargs.root),
                                        spectrograph_name,
                                        extension='')
    ps.run(setup_only=True, no_write_sorted=True)
    setups, indx = ps.fitstbl.get_configuration_names(return_index=True)

    # Restrict on detector -- May remove this
    ps.user_cfg = ['[rdx]', 'spectrograph = {}'.format(ps.spectrograph.name)]
    ps.user_cfg += ['detnum = {}'.format(pargs.det)]
    # Avoid crash in flat fielding from saturated slits
    ps.user_cfg += ['[calibrations]', '[[flatfield]]', 'saturated_slits = mask']
    # Other DEIMOS fiddling here (e.g. reduce edge_thresh value)

    # TODO -- Remove the science files!  We want calibs only

    # Write the PypeIt files
    pypeit_files = ps.fitstbl.write_pypeit(output_path=output_path,
                                          cfg_lines=ps.user_cfg,
                                          configs='all')

    # Loop on setups, rename + run calibs
    for pypeit_file, setup, ii in zip(pypeit_files, setups, indx):

        # Rename with _calib
        calib_pypeit_file = pypeit_file.replace('deimos_{}.pypeit'.format(setup),
                                                'deimos_calib_{}.pypeit'.format(setup))
        os.rename(pypeit_file, calib_pypeit_file)

        # Run me via the script
        redux_path = os.path.dirname(calib_pypeit_file)  # Path to PypeIt file
        run_pargs = run_pypeit.RunPypeIt.parse_args([calib_pypeit_file,
                                           '-r={}'.format(redux_path),
                                           '-c'])
        run_pypeit.RunPypeIt.main(run_pargs)

def get_science_setup(pargs, spectrograph_name:str):
    """
    Figure out the matching setup for the science file

    Args:
        pargs (argparse.ArgumentParser):
            Command line arguments

    Returns:
        tuple: int, :class:`pypeit.pypeitsetup.PypeItSetup`

    """
    # Load up the spectrograph
    spectrograph = load_spectrograph(spectrograph_name)

    # Check file exists
    science_file = os.path.join(pargs.full_rawpath, pargs.science)
    if not os.path.isfile(science_file):
        msgs.error("Your science filename {} does not exist. Check your path".format(science_file))

    # Run setup on the single science file
    ps_sci = PypeItSetup.from_file_root(science_file, spectrograph_name,
                                        extension='')
    ps_sci.run(setup_only=True, no_write_sorted=True)

    # Generate the setup dict and yamilfy (yes, this is necessary)
    setup_dict = {}
    for key in spectrograph.configuration_keys():
        setup_dict[key] = ps_sci.fitstbl[key][0]
    setup_dict = utils.yamlify(setup_dict)

    # Check against existing PypeIt files
    pypeit_files = glob.glob(os.path.join(pargs.redux_path, 'keck_deimos_*', 'keck_deimos_calib_*.pypeit'))
    mtch = []
    for pypeit_file in pypeit_files:
        # Read
        pypeitFile = inputfiles.PypeItFile.from_file(pypeit_file)

        # Check for a match
        match = True
        for key in spectrograph.configuration_keys():
            if setup_dict[key] != pypeitFile.setup[key]:
                match = False
        if match:
            mtch.append(pypeit_file)
    if len(mtch) != 1:
        msgs.error("Matched to zero or more than one setup.  Inconceivable!")

    return mtch[0], ps_sci

def run_on_science(pargs, calib_pypeit_file, ps_sci):
    """
    Process a science frame

    Args:
        pargs (argparse.ArgumentParser):
            Command line arguments
        calib_pypeit_file (str):
        ps_sci (:class:`pypeit.pypeitsetup.PypeItSetup`):
    """
    # Parse science file info
    science_file = os.path.join(pargs.full_rawpath, pargs.science)
    science_pypeit = calib_pypeit_file.replace('calib', 'science')

    calibPypeItFile = inputfiles.PypeItFile.from_file(calib_pypeit_file)

    # Add science file to data block?
    if science_file not in calibPypeItFile.filenames:
        new_row = {}
        for key in calibPypeItFile.data.keys():
            new_row[key] = ps_sci.fitstbl[key][0]
        new_row['filename'] = pargs.science

    # Generate data block
    # Remove any extraneous science files in the folder
    gd_files = (calibPypeItFile.data['filename'] == os.path.basename(science_file)) | (
        calibPypeItFile.data['frametype'] != 'science')
    cut_data = calibPypeItFile.data[gd_files]

    # Add to configs
    config_lines = calibPypeItFile.cfg_lines
    if pargs.slit_spat is not None:
        # Remove detnum
        for kk, item in enumerate(config_lines):
            if 'detnum' in item:
                config_lines.pop(kk)

        # Add in name, slitspatnum
        ridx = config_lines.index('[rdx]')
        config_lines.insert(ridx+1, '    slitspatnum = {0}'.format(pargs.slit_spat))

        # this is to avoid that the default detnum (which was introduced for mosaic)
        # will be passed to the reduction and crash it
        config_lines.insert(ridx+2, '    detnum = None')
    else:
        raise NotImplementedError('NOT READY:  118 of ql_deimos')

    # Generate PypeIt file
    pypeitFile = inputfiles.PypeItFile(config=config_lines,
                                       file_paths=calibPypeItFile.file_paths,
                                       data_table=cut_data,
                                       setup=calibPypeItFile.setup)
    pypeitFile.write(science_pypeit)

    # Run me!
    redux_path = os.path.dirname(science_pypeit)  # Path to PypeIt file
    run_pargs = run_pypeit.RunPypeIt.parse_args([science_pypeit,
                                   '-r={}'.format(redux_path),
                                   ])
    run_pypeit.RunPypeIt.main(run_pargs)


__author__ = 'Li Bai'
"""data description: whether data are fetched directly from Norway Meteo
website; the forecast data are updated every 6 hours a day for the next 48
hours; the parameters are variables

1)	'air_temperature_2m',
2)	'integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time',
3)	'precipitation_amount_acc',
4)	'relative_humidity_2m',
5)	'x_wind_10m',
6)	'y_wind_10m'

All the data will be processed in a way that they finally will be put into a
file of 12x31x24=8928 samples

reorganize the data in the fetched files; remove null data and fill with yesterday's data
"""

import pandas as pd
import datetime
import numpy as np
import os
import matplotlib.pyplot as plt

year=['2019','2020','2021']
month=["01","02","03","04","05","06","07","08","09","10","11","12"]
path_root="Bornholm_weather"
path_root_new='Bweather'

def path_change(path_root, year, month):
    addrs = []
    newpath = path_root + "/" + year + month
    if not os.path.exists(newpath):
        os.makedirs(newpath)
    for file in os.listdir(path_root):
            if file.endswith(year+month+".csv"):
                os.rename(path_root+"/"+file,
                          newpath+"/"+file)

                addrs.append(newpath+"/"+file)
    return addrs

def file_move(path_root, year, month):
    for ky in range(len(year)):
        for km in range(len(month)):
            path_change(path_root, year=year[ky], month=month[km])

# addrs=path_read(path_root)
# addrs_month=addrs[0]
# 50 columns: first column is the updated time and the others are for the 49
# hours including this one; 49 hours are selected because of accumulated data
# we have to convert them for single hours
#  every one should select updated hour[0,1,2,3] refers to 00 06 12 18 and
#  variables [0,1,2,3,4,5]
def file_month(addrs_month,  index_var, hour_update, names):

    var1 = pd.read_csv(addrs_month[index_var], sep=",")
    col0 = var1.columns[0]
    var1_new = var1.rename(columns={col0: 'time'})

    var1_new['time'] = [datetime.datetime.utcfromtimestamp(t) for t in var1_new[
        'time']]
    var1_new= var1_new.set_index('time')

    if names[index_var] in ['solarflux','precipitation']:

        cols_0_48=var1_new.iloc[:,0:-1].to_numpy()
        cols_1_49=var1_new.iloc[:,1:].to_numpy()

        var1_new_1=pd.DataFrame(columns=var1_new.columns[:-1],
                                index=var1_new.index)

        var1_new_1.iloc[:,0:]=cols_1_49-cols_0_48

        var1_new_x=var1_new_1.iloc[hour_update::4,:]
    else:
        var1_new_x=var1_new.iloc[hour_update::4,:-1]
    # with [:, idx:] here idx refers to the values of tomorrow.
    # update_hour=0, idx=24; update=6; idx=18:18+24 '
    # update_hour=12, idx=12:12+24; update_hour=24; idx=0:24
    # idx=24-update_hour: 24-update_hour+24
    return var1_new_x.iloc[:,(24-hour_update): (24-hour_update+24)]

def file_all(addrs, index_var, hour_update, names):
    dfs=[]
    for addrs_month in addrs:
        df=file_month(addrs_month,  index_var, hour_update, names)
        dfs.append(df)
    dfs=pd.concat(dfs)
    return dfs
# =======================================================================

# generate addrs
def addrs_gene(path_root):

    file_list=os.listdir(path_root)
    print(file_list)
    # names=['temperature','solarflux','precipitation','humidity','windx','windy']
    names=['integral_of_surface_downwelling_shortwave_flux_in_air_wrt_time',
     'air_temperature_2m', 'relative_humidity_2m',
     'precipitation_amount_acc', 'x_wind_10m',
     'y_wind_10m']
    years=['2019','2020','2021']
    months=['01', '02', '03','04', '05', '06','07', '08', '09','10', '11', '12']
    addrs=[]
    for year in years:
        for month in months:
            addrs_month=[]
            for name in names:
                file_name='Bornholm_'+name+'_'+year+month+'.csv'
                if file_name in file_list:
                    addr='Bornholm_weather/Bornholm_'+name+'_'+year+month+'.csv'
                    addrs_month.append(addr)
            if len(addrs_month)!=0:
                addrs.append(addrs_month)
    return addrs

def subtract_update_data(path_root, path_root_new, names):

    addrs = addrs_gene(path_root)
    print(addrs)
    # names=['solarflux',
    #  'temperature', 'humidity',
    #  'precipitation', 'windx',
    #  'windy']

    # names=['temperature','solarflux','precipitation','humidity','windx','windy']
    hours=['00','06','12','18']
    import os
    if not os.path.exists(path_root_new):
        os.makedirs(path_root_new)
    # every one should select updated hour[0,1,2,3] refers to 00 06 12 18 and
    #  variables [0,1,2,3,4,5] refers to names
    for hour_update in range(len(hours)):
        for index_var in range(6):
            dfs=file_all(addrs, index_var=index_var, hour_update=hour_update, names=names)
            dfs.to_csv(path_root_new+'/'+names[index_var] +'_'+hours[
                hour_update]+'.csv',
                       sep=',')
            # dfs.plot()

#
#
def path_gene(path_root_new, names):
    addrs = []
    for name in names:
        # if file.endswith("00.csv"):
        addrs.append(path_root_new + "/" + name+'_00.csv')
    return addrs
# ['./Bornholm_weather/humidity_00.csv',
#  './Bornholm_weather/precipitation_00.csv',
#  './Bornholm_weather/solarflux_00.csv',
#  './Bornholm_weather/temperature_00.csv',
#  './Bornholm_weather/windx_00.csv',
#  './Bornholm_weather/windy_00.csv']
# =================================================================================

def data_reshape_column(addrs_new, names):
    dfs=[]
    for namek in range(len(addrs_new)):
        var = pd.read_csv(addrs_new[namek], sep=",", index_col='time')
        var.index=pd.to_datetime(var.index)
        start_date=var.index[0]+datetime.timedelta(hours=24)
        end_date=var.index[-1]+datetime.timedelta(hours=47)
        dates=pd.date_range(start_date,end_date,freq='H')
        col_name=names[namek]
        df_var=pd.DataFrame(columns=['time',col_name])
        df_var['time']=dates
        df_var=df_var.set_index('time')
        print((var.iloc[:,0:].to_numpy()).shape)
        if col_name=='temperature':
            df_var[col_name]=((var.iloc[:,0:].to_numpy()).reshape(-1,1))-273.15
        else:
            df_var[col_name] = (var.iloc[:, 0:].to_numpy()).reshape(-1, 1)
        dfs.append(df_var)
    dfs=pd.concat(dfs,axis=1)
    return dfs

# ==============read data from each files in the directory of Nordhavn_weather and then put it into the Bweather as 00

# this is to read files from Nordhavn_weather and to save it to Bweather/Bornholm_weather00.csv

# followng alphabetic order
names = ['solarflux',
         'temperature', 'humidity',
         'precipitation', 'windx',
         'windy']
subtract_update_data(path_root, path_root_new, names)

addrs_new=path_gene(path_root_new, names)
dfs=data_reshape_column(addrs_new, names)
# dfs.to_csv('./Nweather/Nordhavn_weather_total.csv',
#                        sep=',')

def fill_nulls(dfs):
    dfs[dfs==-99.99]=np.nan
    dfs.loc[dfs['temperature']==-273.15-99.99,'temperature']=np.nan

    # all the data are missing for the same date; so we do it for all columns
    # together

    cols=dfs.columns
    for col in cols:
        dfs_null=dfs.loc[dfs[col].isna()==True]
        for idx in dfs_null.index:
            idx_yes=idx-datetime.timedelta(hours=24)
            dfs.loc[idx, col]=dfs.loc[idx_yes, col]
    return dfs

dfs=fill_nulls(dfs)
dfs.to_csv("Bornholm_weather00_full_2021"
           ".csv")

# # print(dfs.iloc[0,:]
# Out[8]:
# humidity           0.568547
# precipitation     -0.001953
# solarflux          0.000000
# temperature      277.342285
# windx              5.727576
# windy            -14.121002
# Name: 2019-01-01 00:00:00, dtype: float64)


import torch
import pytorch_lightning as pl
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint
import torch.nn.functional as F
from argparse import ArgumentParser
from torchvision.utils import make_grid
from utils import DiceLoss
import segmentation_models_pytorch as smp

class U2Net(pl.LightningModule):
    def __init__(self,
                 in_ch=3,
                 out_ch=1,
                 lr=1.0e-3,
                 weight_decay=3.0e-6,
                 ratio=0.9,
                 **kwargs,
                 ):
        super().__init__()

        self.save_hyperparameters()

        self.lr = lr
        self.weight_decay = weight_decay

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

        self.dice_loss = DiceLoss()
        self.ratio = ratio

        self.sample_imgs = torch.zeros(1)
        self.sample_masks = torch.zeros(1)
        self.rand_mask = torch.randint(16, (8,))

    def forward(self, x):
        x_hat = torch.sigmoid(self.model(x))
        return x_hat

    def training_step(self, batch, batch_idx):
        img, mask = batch
        mask_hat = self.forward(img)

        log_loss = F.binary_cross_entropy(mask_hat, mask)
        dice_loss = self.dice_loss(mask_hat, mask)
        train_loss = log_loss+dice_loss

        self.log('train_loss', log_loss, on_epoch=True, on_step=True)
        self.log('train_diceloss', dice_loss, on_epoch=True, on_step=True)
        self.log('train_dicemetric', 1-dice_loss, on_epoch=True, on_step=True)

        return train_loss

    def validation_step(self, batch, batch_idx):
        img, mask = batch
        mask_hat = self.forward(img)

        log_loss = F.binary_cross_entropy(mask_hat, mask)
        dice_loss = self.dice_loss(mask_hat, mask)
        val_loss = log_loss+dice_loss

        self.log('val_loss', val_loss, on_epoch=True, on_step=False)
        self.log('val_diceloss', dice_loss, on_epoch=True, on_step=False)
        self.log('val_dicemetric', 1-dice_loss, on_epoch=True, on_step=False)

        self.sample_imgs = img[self.rand_mask]
        self.sample_masks = torch.cat([mask[self.rand_mask],
                                       mask_hat[self.rand_mask]], dim=0)

    def on_validation_epoch_end(self) -> None:
        mask_grid = make_grid(self.sample_masks, 8)
        img_grid = make_grid(self.sample_imgs, 8)
        self.logger.experiment.add_image('gt and pred masks', mask_grid, self.current_epoch)
        self.logger.experiment.add_image('images', img_grid, self.current_epoch)

    def configure_optimizers(self):
        optimizer = torch.optim.Adam(self.parameters(), lr=self.lr, weight_decay=self.weight_decay)
        return [optimizer]

    @staticmethod
    def add_model_specific_args(parent_parser):
        parser = ArgumentParser(parents=[parent_parser], add_help=False)

        parser.add_argument("--in_ch", type=int, default=3)
        parser.add_argument("--out_ch", type=int, default=1)
        parser.add_argument("--ratio", type=float, default=0.9)

        parser.add_argument("--lr", type=float, default=1.0e-3)
        parser.add_argument("--weight_decay", type=float, default=3e-6)

        parser.add_argument("--data_dir", type=str, default=".")
        parser.add_argument("--image_size", type=int, default=256)
        parser.add_argument("--num_workers", type=int, default=-1)
        parser.add_argument("--batch_size", type=int, default=32)
        parser.add_argument("--pin_memory", action='store_true')
        parser.add_argument("--drop_last", action='store_false')
        parser.add_argument("--split", type=float, default=0.8)
        return parser

def cli_main(args=None):
    from datamodules import HuBMAPDataModule

    parser = ArgumentParser()

    parser.add_argument("--logdir", default="logs", type=str)
    parser.add_argument("--name", default="unet34", type=str)
    parser.add_argument("--chkpt_monitor", default="val_dicemetric", type=str)
    parser.add_argument("--mode", default="max", type=str)
    script_args, _ = parser.parse_known_args(args)

    dm_cls = HuBMAPDataModule

    logger = TensorBoardLogger(script_args.logdir, name=script_args.name)
    checkpoint = ModelCheckpoint(monitor=script_args.chkpt_monitor, mode='max',
                                 filename=script_args.name + '-{epoch:03d}-{' + script_args.chkpt_monitor + ':.5f}')
    parser = U2Net.add_model_specific_args(parser)
    parser = pl.Trainer.add_argparse_args(parser)
    args = parser.parse_args(args)

    dm = dm_cls.from_argparse_args(args)

    model = U2Net(**vars(args))
    # model = U2Net.load_from_checkpoint('./logs/u2net_256/version_0/checkpoints/u2net_256-epoch=305-val_dicemetric=0.96.ckpt')
    trainer = pl.Trainer.from_argparse_args(args, logger=logger, callbacks=[checkpoint])
    trainer.fit(model, datamodule=dm)
    return dm, model, trainer

if __name__ == "__main__":
    dm, model, trainer = cli_main()


# 분해합

n = int(input())

for i in range(1, n+1):
    tmp = list(map(int, str(i)))
    answer = i + sum(tmp)
    if answer == n:
        print(i)
        break
else:
    print(0)


import os

import torch
import numpy as np

import open3d as o3d
from open3d import geometry

from seg3d.utils.pointops_utils import get_voxel_centers

def draw_points(palette, data_dict, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    pcd = geometry.PointCloud()

    points = data_dict['points']
    if isinstance(points, torch.Tensor):
        points = points.cpu().numpy()

    points = points.copy()
    pcd.points = o3d.utility.Vector3dVector(points[:, :3])

    point_labels = data_dict['point_labels']
    if isinstance(point_labels, torch.Tensor):
        point_labels = point_labels.cpu().numpy()

    points_colors = np.zeros((point_labels.shape[0], 3), dtype=np.float32)
    for i in range(point_labels.shape[0]):
        if point_labels[i] == 255:
            continue
        points_colors[i] = np.array(palette[point_labels[i]])

    # normalize to [0, 1] for open3d drawing
    if not ((points_colors >= 0.0) & (points_colors <= 1.0)).all():
        points_colors /= 255.0
    pcd.colors = o3d.utility.Vector3dVector(points_colors)

    output_file = os.path.join(output_dir, data_dict['filename'] + '.pcd')
    o3d.io.write_point_cloud(output_file, pcd)

def draw_voxels(palette, voxel_size, pc_cloud_range, data_dict, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    pcd = geometry.PointCloud()

    voxel_coords = data_dict['voxel_coords']
    voxel_centers = get_voxel_centers(voxel_coords, 1.0, voxel_size, pc_cloud_range)

    points = voxel_centers.numpy().copy()
    pcd.points = o3d.utility.Vector3dVector(points[:, :3])

    voxel_labels = data_dict['voxel_labels']
    if isinstance(voxel_labels, torch.Tensor):
        voxel_labels = voxel_labels.cpu().numpy()

    voxel_colors = np.zeros((voxel_labels.shape[0], 3), dtype=np.float32)
    for i in range(voxel_labels.shape[0]):
        if voxel_labels[i] == 255:
            continue
        voxel_colors[i] = np.array(palette[voxel_labels[i]])

    # normalize to [0, 1] for open3d drawing
    if not ((voxel_colors >= 0.0) & (voxel_colors <= 1.0)).all():
        voxel_colors /= 255.0
    pcd.colors = o3d.utility.Vector3dVector(voxel_colors)

    output_file = os.path.join(output_dir, data_dict['filename'] + '.pcd')
    o3d.io.write_point_cloud(output_file, pcd)


from django.test import TestCase, RequestFactory
from django.db.models.query import QuerySet

from animals.models import Animal

class IndexViewTestCase(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.animal = Animal.objects.create(
            name='Parrot',
            predator='No',
            venomous='No',
            domestic='Yes'
        )

    def test_return_animal_characteristics(self):
        """check if the index page returns the animals characteristcs when searched"""

        response = self.client.get('/',
                                   {'buscar': 'Parrot'})
        animal_characteristics = response.context['characteristics']

        self.assertIs(type(response.context['characteristics']), QuerySet)
        self.assertEqual(animal_characteristics[0].name, 'Parrot')


# -*- coding: UTF-8 -*-
"""
title: 开密码锁
一个密码锁由 4 个环形拨轮组成，每个拨轮都有 10 个数字： '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转：例如把 '9' 变为 '0'，'0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。
锁的初始数字为 '0000' ，一个代表四个拨轮的数字的字符串。
列表 deadends 包含了一组死亡数字，一旦拨轮的数字和列表里的任何一个元素相同，这个锁将会被永久锁定，无法再被旋转。
字符串 target 代表可以解锁的数字，请给出解锁需要的最小旋转次数，如果无论如何不能解锁，返回 -1 。

示例 1:
输入：deadends = ["0201","0101","0102","1212","2002"], target = "0202"
输出：6
解释：
可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。
注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的，因为当拨动到 "0102" 时这个锁就会被锁定。

示例 2:
输入: deadends = ["8888"], target = "0009"
输出：1
解释：
把最后一位反向旋转一次即可 "0000" -> "0009"。

示例 3:
输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
输出：-1
解释：
无法旋转到目标数字且不被锁定。

示例 4:
输入: deadends = ["0000"], target = "8888"
输出：-1

提示：
1 <= deadends.length <= 500
deadends[i].length == 4
target.length == 4
target 不在 deadends 之中
target 和 deadends[i] 仅由若干位数字组成
"""
from collections import deque
from typing import List

class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
        """BFS"""
        start = '0000'
        if start == target:
            return 0
        dead_set = set(deadends)
        if start in dead_set:
            return -1
        queue = deque([(start, 0)])
        visited = {start}
        while queue:
            item, step = queue.popleft()
            for i in range(4):
                ch1 = str((int(item[i]) + 1) % 10)
                # 在Python中，-1 % 10 == 9
                ch2 = str((int(item[i]) - 1) % 10)
                for ch in [ch1, ch2]:
                    next_item = item[:i] + ch + item[i + 1:]
                    if next_item not in dead_set and next_item not in visited:
                        if next_item == target:
                            return step + 1
                        queue.append((next_item, step + 1))
                        visited.add(next_item)
        return -1

    def openLock_2(self, deadends: List[str], target: str) -> int:
        """双向BFS"""
        start = '0000'
        if start == target:
            return 0
        dead_set = set(deadends)
        if start in dead_set:
            return -1
        forward_queue, backward_queue = deque([start]), deque([target])
        forward_visited, backward_visited = {start: 0}, {target: 0}
        while forward_queue:
            if len(forward_queue) > len(backward_queue):
                forward_queue, backward_queue = backward_queue, forward_queue
                forward_visited, backward_visited = backward_visited, forward_visited
            for _ in range(len(forward_queue)):
                item = forward_queue.popleft()
                for i in range(4):
                    ch1 = str((int(item[i]) + 1) % 10)
                    # 在Python中，-1 % 10 == 9
                    ch2 = str((int(item[i]) - 1) % 10)
                    for ch in [ch1, ch2]:
                        next_item = item[:i] + ch + item[i + 1:]
                        if next_item not in dead_set and next_item not in forward_visited:
                            if next_item in backward_visited:
                                # forward_visited、backward_visited 中的层级均从0开始
                                return forward_visited[item] + backward_visited[next_item] + 1
                            forward_queue.append(next_item)
                            forward_visited[next_item] = forward_visited[item] + 1
        return -1

if __name__ == '__main__':
    print(Solution().openLock_2(deadends=["0201", "0101", "0102", "1212", "2002"], target="0202"))


import queue
import sys
import time
import matplotlib.pyplot as plt
from fastqueue.prototypes import *
from fastqueue import *

queue_size = 1000000
queue_structures = {
    "Python queue": (queue.Queue(), queue.Queue.put, queue.Queue.get),
    "Python Simple queue": (
        queue.SimpleQueue(),
        queue.SimpleQueue.put,
        queue.SimpleQueue.get,
    ),
    "Matt's Linked List queue": (LLQueue(), LLQueue.enqueue, LLQueue.dequeue),
    "Matt's Contiguous queue": (ContQueue(), ContQueue.enqueue, ContQueue.dequeue),
    "Matt's C queue": (Queue(), Queue.enqueue, Queue.dequeue),
    "Matt's C Contiguous queue": (QueueC(), QueueC.enqueue, QueueC.dequeue),
}
queue_types = queue_structures.keys()
queue_times = []

for q in queue_types:
    enqueue = queue_structures[q][1]
    dequeue = queue_structures[q][2]
    start = time.time()
    for j in range(queue_size):
        enqueue(queue_structures[q][0], j)
    assert [dequeue(queue_structures[q][0]) for _ in range(queue_size)] == list(
        range(queue_size)
    )
    queue_times.append(time.time() - start)
queue_types, queue_times = zip(
    *sorted(zip(queue_types, queue_times), key=lambda x: x[1], reverse=True)
)
fig = plt.figure(figsize=(15, 7))
plt.bar(queue_types, queue_times, color=["y", "r", "g", "c", "m", "b"], width=0.5)
for i, v in enumerate(queue_times):
    plt.text(i, v, str(round(v, 5)), ha="center", family="sans-serif")
plt.xlabel("Queue Type")
plt.ylabel("Time")
plt.title(f"Queue Analysis : {sys.platform}")
plt.savefig(f"Queue_types_{sys.platform}.png")
print("Queue times Graphed")


import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LeakyReLU
import matplotlib as mpl
from matplotlib import pyplot as plt

# 1. Data
x_train = np.array([range(10)]).T
y_train = np.array([[1,2,3,4,5,6,7,8,9,10],
                    [1+0.1*i for i in range(10)],
                    [9-i for i in range(10)]]).T

# 2. Model Build
model=Sequential()
model.add(Dense(16,input_dim=1))
model.add(Dense(8))
model.add(Dense(4))
model.add(Dense(2))
model.add(Dense(3))

# 3. Compile, fitting
model.compile(loss="mse",optimizer='adam')
model.fit(x_train,y_train,batch_size=10,epochs=1000)

# 4. Model evaluation
loss=model.evaluate(x_train,y_train) # 트레이닝 데이터를 평가에 쓰면 안된다! 따로 evaluate data set을 만들어야 한다.
print(f'loss : {loss}')
result=model.predict([[9]])
print(f'[[9]]의 예측값 : {result}')

# etc. ploting

xx=np.array([np.arange(0,11,0.1)]).T
yy=model.predict(xx).T
for i in range(len(yy)):
    plt.plot(xx,yy[i])
plt.grid()
plt.show()


from collections import deque

n, x, y = map(int, input().split())

ans = [0] * (n+1)

g = [[i+1, i-1] for i in range(n+1)]
#g[0].clear() pypyにclearなし
g[1].pop(1)
g[n].pop(0)

g[x].append(y)
g[y].append(x)

for i in range(1,n+1):
    q = deque()
    time = 0
    visit = [False] * (n+1)
    q.append((i, time))

    while(len(q) > 0):
        item = q.popleft()

        if visit[item[0]] == False:
            visit[item[0]] = True
            ans[item[1]] += 1
            for k in g[item[0]]:
                q.append((k, item[1]+1))

for i in range(1,n):
    print(ans[i]//2)


from django.core.management.base import BaseCommand, CommandError
from django.template import loader, TemplateDoesNotExist

from beautifultable import BeautifulTable
from inbox import settings as inbox_settings
from inbox.constants import MessageMedium
from inbox.models import MessageLog

class Command(BaseCommand):
    help = 'Use inbox config and determine if necessary templates are available.'

    # def add_arguments(self, parser):
    #     parser.add_argument('poll_ids', nargs='+', type=int)

    def handle(self, *args, **options):

        used_template_names = []
        message_groups = []
        for message_group in inbox_settings.get_config()['MESSAGE_GROUPS']:
            for k, v in message_group['preference_defaults'].items():

                for message_key in message_group['message_keys']:
                    template_names = MessageLog._get_subject_template_names(message_key, None, True)
                    template_names.extend(MessageLog._get_body_template_names(message_key, None, True))

                    if v is not None:
                        template_names.extend(MessageLog._get_subject_template_names(message_key, MessageMedium.get(k.upper()), True))
                        template_names.extend(MessageLog._get_body_template_names(message_key, MessageMedium.get(k.upper()), True))

                    for template_name, required in template_names:
                        if template_name in used_template_names:
                            continue

                        used_template_names.append(template_name)

                        try:
                            loader.get_template(template_name)
                        except TemplateDoesNotExist:
                            message_groups.append({
                                               'file': template_name,
                                               'key': message_key,
                                               'medium': k.lower(),
                                               'required': required,
                                               'found': False
                                                  })
                        else:
                            message_groups.append({
                                               'file': template_name,
                                               'key': message_key,
                                               'medium': k.lower(),
                                               'required': required,
                                               'found': True
                                                  })

        table = BeautifulTable()
        table.column_headers = ['File', 'Required', 'Found']
        table.column_alignments['File'] = BeautifulTable.ALIGN_LEFT

        table_optional = BeautifulTable()
        table_optional.column_headers = ['File (Optional)', 'Required', 'Found']
        table_optional.column_alignments['File (Optional)'] = BeautifulTable.ALIGN_LEFT

        for mg in message_groups:
            if mg['required'] and not mg['found']:
                table.append_row([
                    self.style.ERROR(mg['file']),
                    self.style.ERROR('Yes'),
                    self.style.ERROR('No')
                ])
            elif not mg['required'] and not mg['found']:
                found_txt = 'Yes'
                if not mg['found']:
                    found_txt = 'No'
                required_txt = 'Yes'
                if not mg['required']:
                    required_txt = 'No'
                table_optional.append_row([mg['file'], required_txt, found_txt])
            else:
                found_txt = 'Yes'
                if not mg['found']:
                    found_txt = 'No'
                required_txt = 'Yes'
                if not mg['required']:
                    required_txt = 'No'

                if mg['required']:
                    table.append_row([
                        self.style.SUCCESS(mg['file']),
                        self.style.SUCCESS(required_txt),
                        self.style.SUCCESS(found_txt)
                    ])
                else:
                    table_optional.append_row([
                        self.style.SUCCESS(mg['file']),
                        self.style.SUCCESS(required_txt),
                        self.style.SUCCESS(found_txt)
                    ])

        final_table = BeautifulTable()
        final_table.column_headers = ['File', 'Required', 'Found']
        final_table.column_alignments['File'] = BeautifulTable.ALIGN_LEFT

        for row in table:
            final_table.append_row(row)

        final_table.append_row([
            'File (Optional)', 'Required', 'Found'
        ])

        for row in table_optional:
            final_table.append_row(row)

        self.stdout.write(str(final_table))


x = 1
lista = []
while x > 0:
    n = int(input("Digite um número: "))
    if n != 0:
        lista.append(n)
    else:
        x = 0

lista.reverse()

x = 0

while x < len(lista):
    print(lista[x])
    x += 1


# Making JSON file
import json
import os

# a data that will be written in json file
data = {
    'employee': [
        {'NIP':'1001', 'name':'Anis Yuliana Phasya', 'salary':6000000},
        {'NIP':'1002', 'name':'Rizki Sadewa', 'salary':120000000},
        {'NIP':'1003', 'name':'Abimanyu', 'salary':8000000}
    ]
}

# change the dictionary above to string with json format
json_str = json.dumps(data)
print(json_str)

# making JSON file
f = open("D:\Rizky's File\Tutorial\Coding\Python\CrashCourse\data.json", 'w')
f.writelines(json_str)
f.close()

# checking file existance of JSON
print(os.path.exists("D:\Rizky's File\Tutorial\Coding\Python\CrashCourse\data.json"))


import re
from Parsers.Schedule import Schedule
from Parsers.Common import LessonTypes

delimiter = ','
subdelimeter = r'\s*;\s*'

class Row:
    counter = -1
    objects = []

    def __init__(self, key: str, independent: bool = True, skip: int = 0):
        Row.counter += 1 + skip
        self.row = Row.counter
        self.key = key
        self.independent = independent
        Row.objects.append(self)

Days = Row('days')
Time = Row('time')

Rooms = Row('rooms', skip=1)
RoomCapacity = Row('roomcap', False)

Instructors = Row('teachers', skip=1)
BadDays = Row('baddays', False)
BadSlots = Row('badslots', False)

Groups = Row('groups', skip=1)
StudentsN = Row('studentsN', False)

Grades = Row('spec', skip=1)
GradeGroups = Row('gradegroups', False)

Course = Row('course', skip=1)
LessonType = Row('type', False)
GradeOrGroups = Row('grg', False)
Instructor = Row('ins', False)
LessonsN = Row('lesn', False)

# Wrap In Quotes.
def wiq(s: str) -> str:
    return '"' + s + '"'

# Wrap In Square Brackets.
def wisb(s: str) -> str:
    return '[' + s + ']'

# Make JSON key.
def mjsonk(name: str, values: list) -> str:
    return wiq(name) + ':' + wisb(','.join(values))

def BuildOneValueKey(name: str, values: list) -> str:
    temp = []
    for v in values:
        temp.append(wisb(wiq(v)))
    return mjsonk(name, temp)

def BuildTwoValueKey(name: str, values1: list, values2: list) -> str:
    temp = []
    for i in range(len(values1)):
        temp.append(wisb(wiq(values1[i]) + ',' + wiq(values2[i])))
    return mjsonk(name, temp)

# Mistakes in input file.
class CSVException(Exception):
    pass

def DefCSVException(row: int):
    raise CSVException('Input file has incorrect format in row ' + str(row + 1) + '.')

def ParseLine(line: str, row: int) -> list:
    temp = line.strip().split(delimiter)[1:]
    i = len(temp) - 1
    try:
        while temp[i] == '':
            i -= 1
    except IndexError:
        DefCSVException(row)
    temp = temp[:i + 1]
    if '' in temp:
        DefCSVException(row)
    return temp

def ParseLineWithBound(line: str, l: int) -> list:
    return line.strip().split(delimiter)[1:l + 1]

def ParseCSV(path: str) -> dict:
    with open(path, encoding='utf-8') as f:
        inp = f.readlines()
    info = dict()
    L = 0
    for r in Row.objects:
        if r.independent:
            info[r.key] = ParseLine(inp[r.row], r.row)
            L = len(info[r.key])
            if L == 0:
                DefCSVException(r.row)
        else:
            info[r.key] = ParseLineWithBound(inp[r.row], L)
            if len(info[r.key]) != L:
                DefCSVException(r.row)
    return info

def CheckIntList(ints: list, errmesfunct):
    for i in range(len(ints)):
        try:
            a = int(ints[i])
        except ValueError:
            raise CSVException(errmesfunct(i))
        if a <= 0:
            raise CSVException(errmesfunct(i))

def CheckPresenceInList(suspect: list, where: list, errmesfunct):
    for i in range(len(suspect)):
        if not (suspect[i] in where):
            raise CSVException(errmesfunct(i))

def ParseGroups(suspect: list, groups: list, errmesfunct_no_groups, errmesfunct) -> list:
    out = []
    for i in range(len(suspect)):
        s = suspect[i]
        if s == '':
            raise CSVException(errmesfunct_no_groups(i))
        s = re.split(subdelimeter, s)
        for g in s:
            if not (g in groups):
                raise CSVException(errmesfunct(i, g))
        out.append(s)
    return out

def CreateDSAndJSON(path_to_csv: str, path_to_json: str) -> Schedule:
    # Get info.
    info = ParseCSV(path_to_csv)
    # Name it and do further parsing.
    days = info[Days.key]
    times = info[Time.key]

    rooms = info[Rooms.key]
    cap = info[RoomCapacity.key]
    CheckIntList(cap, lambda x: 'Room ' + rooms[x] + ' has an incorrect capacity.')

    ins = info[Instructors.key]
    # bad_days = info[BadDays.key]
    # bad_slots = info[BadSlots.key]

    groups = info[Groups.key]
    stud_n = info[StudentsN.key]
    CheckIntList(stud_n, lambda x: 'Group ' + groups[x] + ' has an incorrect number of students.')

    grades = info[Grades.key]
    gradegrp = ParseGroups(info[GradeGroups.key], groups,
                           lambda x: 'Grade ' + grades[x] + ' has no groups.',
                           lambda x, y: 'Grade ' + grades[x] + ' has a nonexistent group ' + y + '.')

    course = info[Course.key]
    typ = info[LessonType.key]
    CheckPresenceInList(typ, LessonTypes, lambda x: 'Course ' + course[x] + ' has an incorrect lesson type ' +
                                                    typ[x] + '.')
    whom = ParseGroups(info[GradeOrGroups.key], groups + grades,
                           lambda x: 'Course ' + course[x] + ' has no groups or grade.',
                           lambda x, y: 'Course ' + course[x] + ' has a nonexistent group or grade ' + y + '.')
    who = info[Instructor.key]
    CheckPresenceInList(who, ins, lambda x: 'Course ' + course[x] + ' has a nonexistent instructor ' + who[x] + '.')
    week_n = info[LessonsN.key]
    CheckIntList(week_n, lambda x: 'Course ' + course[x] + ' has an incorrect number of lessons.')
    week_n = [int(n) for n in week_n]
    # Init table
    gradesdict = dict()
    for i in range(len(grades)):
        gradesdict[grades[i]] = gradegrp[i]
    table = Schedule(days, times, gradesdict, list(set(course)), ins, rooms)
    CheckPresenceInList(groups, table.allGroups, lambda x: 'Group ' + groups[x] + ' has not a grade.')
    # End of parsing.
    # Convert received data into JSON.
    out = []
    # Build lessons.
    temp = []
    for i in range(len(course)):
        fp = '[' + wiq(course[i]) + ',' + wiq(typ[i]) + ','
        lp = ',' + wiq(who[i]) + ']'
        r = range(week_n[i])
        for g in whom[i]:
            s = fp + wiq(g) + lp
            for _ in r:
                temp.append(s)
    out.append(mjsonk('lessons', temp))
    # Build days.
    out.append(BuildOneValueKey('days', days))
    # Build times.
    out.append(BuildOneValueKey('time_slots', times))
    # Build rooms.
    out.append(BuildTwoValueKey('auditoriums', rooms, cap))
    # Add grades to group list.
    for i in range(len(grades)):
        p = 0
        for g in gradegrp[i]:
            j = groups.index(g)
            p += int(stud_n[j])
        groups.append(grades[i])
        stud_n.append(str(p))
    # Build groups.
    out.append(BuildTwoValueKey('student_groups', groups, stud_n))
    # Write JSON.
    with open(path_to_json, 'w', encoding='utf-8') as f:
        f.write('{' + ','.join(out) + '}')
    return table

# table = CreateDSAndJSON('SampleData.csv', 'InputJSON.json')
# table.addDataFromJSON('OutputJSON.json')
# for s in table.slots:
#     print(s)


import math
from sys import stdin, exit

N = int(stdin.readline())
*coins, = map(int, stdin.readline().split())

# coinを大きい順に並び替える
coins.sort(key=lambda x: -x)

x_coin = coins[0]
y_coin = coins[1]
z_coin = coins[2]

result = math.inf

for x in range(N//x_coin, -1, -1):
    for y in range(N//y_coin, -1, -1):
        if (N - (x_coin*x + y_coin*y)) % z_coin == 0:
            z = (N - (x_coin*x + y_coin*y)) // z_coin
            if x_coin*x + y_coin*y + z_coin*z == N and z >= 0:
                result = min(x + y + z, result)
                break

    for z in range(N//z_coin, -1, -1):
        if (N - (x_coin*x + z_coin*z)) % y_coin == 0:
            y = (N - (x_coin*x + z_coin*z)) // y_coin
            if x_coin*x + y_coin*y + z_coin*z == N and y >= 0:
                result = min(x + y + z, result)
                break

print(result)


#!/usr/bin/env python

"""
Abstraction of an openshift image stream, as defined in:

https://docs.openshift.com/container-platform/4.4/rest_api/image_apis/imagestream-image-openshift-io-v1.html
"""

import logging

from typing import Tuple

from docker_registry_client_async import ImageName, JsonBytes

LOGGER = logging.getLogger(__name__)

class ImageStream(JsonBytes):
    """
    OpenShift image stream.
    """

    def get_name(self) -> str:
        """
        Retrieves the unique name within a namespace.

        Returns:
            The unique name within a namespace
        """
        return self.get_json()["metadata"]["name"]

    def get_tags(self) -> Tuple[str, ImageName]:
        """
        Retrieves the mapping of arbitrary string values to specific image locators.

        Yields:
            str: The arbitrary string value.
            ImageName: The specific image locator.
        """
        for tag in self.get_json()["spec"]["tags"]:
            if tag.get("from", []).get("kind", []) == "DockerImage":
                if "name" in tag:
                    name = f"{self.get_name()}-{tag['name']}"
                else:
                    name = self.get_name()
                yield name, ImageName.parse(tag["from"]["name"])


#!/usr/bin/env python3

# This code originated as a project for the COMP 520 class at McGill
# University in Winter 2015. Any subsequent COMP 520 student who is
# viewing this code must follow the course rules and report any viewing
# and/or use of the code.

import os
import re

DISCLAIMER = '''\
This code originated as a project for the COMP 520 class at McGill
University in Winter 2015. Any subsequent COMP 520 student who is
viewing this code must follow the course rules and report any viewing
and/or use of the code.'''

PY_OR_SHELL_DISCLAIMER = '\n'.join(('# ' + line) for line in DISCLAIMER.split('\n')) + '\n\n'
JAVA_OR_GO_DISCLAIMER = '/* ' + '\n * '.join(DISCLAIMER.split('\n')) + ' */\n\n'

SHEBANG_REGEX = re.compile(r'(^#!.*\n\n?)', re.MULTILINE)

def main(root):
    for (directory, subdirs, files) in os.walk(root):
        if os.path.split(directory)[1] == '.git':
            del subdirs[:]
            continue

        for fname in files:
            if fname.endswith('.py') or fname.endswith('.sh'):
                prepend_to_file(PY_OR_SHELL_DISCLAIMER, os.path.join(directory, fname))
            elif fname.endswith('.java') or fname.endswith('.go'):
                prepend_to_file(JAVA_OR_GO_DISCLAIMER, os.path.join(directory, fname))
            else:
                print('Ignoring file', os.path.join(os.path.relpath(directory, root), fname))

def prepend_to_file(message, filename):
    with open(filename, 'r') as f:
        contents = f.read()
        content_newlines = f.newlines

    shebang_match = SHEBANG_REGEX.match(contents)

    if shebang_match:
        shebang, contents = contents[:shebang_match.end()], contents[shebang_match.end():]
    else:
        shebang = None

    if contents.startswith(message):
        return

    with open(filename, 'w', newline=content_newlines or None) as f:
        if shebang:
            f.write(shebang)
        f.write(message)
        f.write(contents)

if __name__ == '__main__':
    main(os.getcwd())


import sys
sys.setrecursionlimit(10**6)

def dfs(x, y):
    if x == M - 1 and y == N - 1:
        return 1
    if dp[x][y] != -1:
        return dp[x][y]
    dp[x][y] = 0
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < M and 0 <= ny < N:
            if mapp[nx][ny] < mapp[x][y]:
                dp[x][y] = dp[x][y] + dfs(nx, ny)
    return dp[x][y]

if __name__ == '__main__':

    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]

    M, N = map(int, sys.stdin.readline().split())
    mapp = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
    dp = [[-1 for _ in range(N)] for __ in range(M)]

    print(dfs(0,0))