import sys, os, glob, regex, argparse, logging, uuid
from enum import Enum
from operator import attrgetter
import pygogo as gogo

# Declare our crucial regular expressions to enable us to parse:
parens_check_regex = r'^\(.*\)$'
nest_extract_regex = r'\((?>[^()]+|(?R))*\)'

# Define our pre-testing depth & underlying structure:
depth_level = -1
in_debug_mode = False
test_case_filepaths = []
test_case_numbers = []
segment_list = []
parent_guids_list = []
test_bits = []
parent_guids_by_depth_dict = {}

class ExecutionType(Enum):
	SINGLE = 1
	ALL = 2

class Segment():
	def __init__(self, name, depth, parent):
		self.id = str(uuid.uuid4())
		self.name = name
		self.depth = depth
		self.parent = parent
		self.is_root = True if self.depth == 0 else False
		self.has_processed = False

def configure_parser(parser):
	parser.add_argument('-t', '--test-number', type=int, help='number of the specific test to run')
	parser.add_argument('-a', '--alphabetical-order', help='sort test output alphabetically', action='store_true')
	parser.add_argument('-d', '--debug', help='print full debug statements', action='store_true')

def check_folder_validity():
	# Compile all test case names from the 'tests' subfolder:
	for filepath in glob.glob("tests/*.txt"):
		test_case_filepaths.append(os.path.basename(filepath))

	is_valid = True

	# Check files for correct `#_` format:
	for filename in test_case_filepaths:
		if not filename.startswith('_') and filename.count('_') > 1:
			test_case_numbers.append(filename.split('_')[0])
		else:
			is_valid = False
			break

	# Check for test case number uniqueness:
	if is_valid:
		is_valid = True if len(set(test_case_numbers)) == len(test_case_numbers) else False

	# Check that each test case file starts with a number:
	if is_valid:
		for number in test_case_numbers:
			if not number.isdigit():
				is_valid = False
				break

	return is_valid

def check_test_validity(master_string):
	has_valid_bookends = bool(regex.match(parens_check_regex, master_string))
	has_valid_parens_count = True if master_string.count('(') == master_string.count(')') else False
	has_empty_parens = False if master_string.find('()') == -1 else True

	if in_debug_mode:
		logger.debug("Has Valid Bookends?: " + str(has_valid_bookends))
		logger.debug("Has Even Parentheses?: " + str(has_valid_parens_count))
		logger.debug("Has Empty Parentheses?: " + str(has_empty_parens))

	return True if has_valid_bookends and has_valid_parens_count and not has_empty_parens else False

def gather_segments(string, depth_level, test_bits):
	regex_find_count = len(regex.findall(nest_extract_regex, string))
	recursion_anchor = parent_guids_by_depth_dict[depth_level] if depth_level in parent_guids_by_depth_dict else len(parent_guids_list)
	depth_level += 1

	for test_string in regex.findall(nest_extract_regex, string):
		# Calculate total number of sections from regex 'findall' match:
		if regex_find_count > 1:
			parent_guid = parent_guids_list[recursion_anchor - regex_find_count]
			regex_find_count -= regex_find_count
		else:
			if not depth_level == 0:
				parent_guid = parent_guids_list[recursion_anchor - 1]
			else:
				parent_guid = None

		# Strip away parenthetical bookends:
		test_string = test_string[1:len(test_string) - 1]

		# Split out regex bits between parentheses for this section of the depth level:
		depth_bits = regex.split(nest_extract_regex, test_string)

		# Reassign new 'findall' matches back to testing string for later recursive use:
		test_string = str(regex.findall(nest_extract_regex, test_string))

		if in_debug_mode:
			logger.debug("Depth " + str(depth_level) + " Bits: " + str(depth_bits))
			logger.debug("Inner Extract: " + str(test_string))

		# For each depth bit,
		for idx, section in enumerate(depth_bits):
			last_guid = None

			# Keep but don't calculate any empty sections (since it infers a parent
			# from the previous bit):
			for bit in section.split(','):
				if not bit == '':
					segment = Segment(bit, depth_level, parent_guid)
					last_guid = segment.id

					segment_list.append(segment)

					if in_debug_mode:
						logger.debug("Last Segment Details: " + segment.id + ", " + segment.name +
							", " + str(segment.parent))

			# Add our parent GUID to the list to tie back to later if it's not empty
			# or out-of-range:
			if last_guid is not None and not (idx + 1) == len(depth_bits):
				parent_guids_list.append(last_guid)

				if in_debug_mode:
					logger.debug("Appending Parent GUID: " + last_guid)

		# Add a bookmark for coming back at a later recursion:
		parent_guids_by_depth_dict[depth_level] = len(parent_guids_list)

		# Recurse between each parenthetical section to reconstruct a Segment tree:
		gather_segments(test_string, depth_level, test_bits)

def print_segments(segment_list):
	for segment in segment_list:
		if segment.has_processed == False:
			segment_output_name = ('-' * segment.depth)
			segment_output_name += (" " + segment.name) if segment.depth else segment.name

			logger.info(segment_output_name)
			segment.has_processed = True

			for potential_child in segment_list:
				iterate_child_segments(segment_list, potential_child, segment)

def iterate_child_segments(segment_list, potential_child, segment):
	# No need to re-process any children already accounted for:
	if potential_child.has_processed == False:
		if segment.id == potential_child.parent:
			child_output_name = ('-' * potential_child.depth) + " " + potential_child.name
			logger.info(child_output_name)
			potential_child.has_processed = True

			# Check back through to see if this child has any children of its own:
			for child in segment_list:
				iterate_child_segments(segment_list, child, potential_child)

def display_output():
	if in_debug_mode:
		segment_index = 1

		# In debug mode, show each segment gathered by the end with all related data:
		for segment in segment_list:
			logger.debug("Segment #" + str(segment_index) + ": " + segment.id + ", " + segment.name + ", " +
				str(segment.depth) + ", " + str(segment.parent) + ", " + str(segment.is_root))
			segment_index += 1

		parent_guid_index = 1

		# In debug mode, show each parent GUID gathered by the end with all related data:
		for guid in parent_guids_list:
			logger.debug("Parent GUID #" + str(parent_guid_index) + ": " + guid)
			parent_guid_index += 1

	# Sort the list alphabetically before visually recreating the tree if flag is set:
	if args['alphabetical_order']:
		segment_list.sort(key=attrgetter('depth', 'name'))

	print_segments(segment_list)

def execute_test_case(case_filepath):
	with open(case_filepath) as file:
		master_string = file.readline()

	# Strip out any erroneous whitespace from the input:
	master_string = ''.join(master_string.split())

	logger.info(" ------> Executing: " + case_filepath + " <------ ")

	# Check whether the test string given is even valid before starting:
	is_valid_test = check_test_validity(master_string)

	if is_valid_test:
		gather_segments(master_string, depth_level, test_bits)
		display_output()
	else:
		logger.info("Test to execute was invalid, skipping.")

def reset_state():
	# Reset structural variables between case runs when in ExecutionType.ALL mode:
	depth_level = -1
	del segment_list[:]
	del parent_guids_list[:]
	del test_bits[:]

	for key,value in parent_guids_by_depth_dict.items():
		parent_guids_by_depth_dict.pop(key)

if __name__ == "__main__":
	# Configure argument parser & gather any command-line arguments:
	parser = argparse.ArgumentParser(description='Automated tool to print string details by depth.')
	configure_parser(parser)
	args = vars(parser.parse_args())

	# Configure our pygogo logger to prettify our console output:
	log_format = '%(asctime)s - %(levelname)s: %(message)s'
	formatter = logging.Formatter(log_format)
	logger = gogo.Gogo(
		'examples.fmt',
		low_formatter=formatter,
		high_formatter=formatter).logger

	# Configure our execution type (full-suite vs. single-run):
	execution_type = ExecutionType.ALL if not args['test_number'] else ExecutionType.SINGLE

	# Activate debug mode via command-line flag;
	in_debug_mode = True if args['debug'] else False

	is_valid_folder_structure = check_folder_validity()

	if is_valid_folder_structure:
		if execution_type == ExecutionType.SINGLE:
			test_case_number = args['test_number']

			case_filepath = None

			for path in test_case_filepaths:
				if path.startswith(str(test_case_number) + '_'):
					case_filepath = path
					break

			if case_filepath:
				execute_test_case('tests/' + case_filepath)
			else:
				logger.info("Test case not found, aborting.")
		else:
			for case_filepath in test_case_filepaths:
				execute_test_case('tests/' + case_filepath)
				reset_state()
	else:
		logger.info("Test case folder is structured incorrectly, aborting.")


# Dictionary Comprehension
# Wrapping up the section to understand how dictionaries work

numbers = dict(first=1, second=2, third=3)
squared_numbers = {key: value ** 2 for key, value in numbers.items()}
print(squared_numbers)

# Ex 2 , Takes the  keys in the list then sets their value to **2
second = {num: num ** 2 for num in [1, 2, 3, 4, 5]}

print(second)

str1 = "ABC"
str2 = "123"

# Example three takes character in a string and matches it to another string
combo = {str1[i]: str2[i] for i in range(0, len(str1))}
print(combo)


#Time Complexity : O(N)
#Space Complexity: O(H)
#Yes it ran on leetcode

class Solution(object):

    def sumNumbers(self, root):
        global res
        res = 0
        if root == None:
            return 0
        self.helper(root, 0)
        return res

    def helper(self, root, currsum):
        global res
        if root == None:
            return 0
        currsum = currsum * 10 + root.val
        if root.left == None and root.right == None:
            res += currsum
        left = self.helper(root.left, currsum)
        right = self.helper(root.right, currsum)


'''
Branch : CE
Div : A
Sem : 5

Authors:
IU1941050060 : Raj Madhu
IU1941050035 : Mitansh Gor
IU1941050052 : Manav S Patel

'''

import pygame,sys,random

from pygame.constants import GL_MULTISAMPLEBUFFERS

#this fn will draw 2 floors which will move one after other to show cont. motion
def draw_floor():
    screen.blit(floor_surface,(floor_x_pos,532))
    screen.blit(floor_surface,(floor_x_pos+420,532))

def create_pipe():
    random_pipe_pos=random.choice(pipe_height)
    bottom_pipe=pipe_surface.get_rect(midtop=(600,random_pipe_pos))
    top_pipe=pipe_surface.get_rect(midbottom=(600,random_pipe_pos-300))
    #returns tuple
    return bottom_pipe,top_pipe

def move_pipes(pipes):
    for pipe in pipes:
        #moves to left
        pipe.centerx-=5
    # return pipe list of pipes that are not seen
    visible_pipes=[pipe for pipe in pipes if pipe.right>-50]
    return visible_pipes

def draw_pipes(pipes):
    for pipe in pipes:
        if pipe.bottom>=700:
            screen.blit(pipe_surface,pipe)
        else:
            flip_pipe=pygame.transform.flip(pipe_surface,False,True)  #we don't want to flip in x direction so false and for y, true
            screen.blit(flip_pipe,pipe)

def check_collision(pipes):
    global can_score
    for pipe in pipes:
        if bird_rect.colliderect(pipe):
            # print("collision")
            death_sound.play()
            can_score=True
            return False
    #check for bird moving in the clouds
    if bird_rect.top <=-200 or bird_rect.bottom >=532:
        # print("collision")
        #can_score = True
        return False
    #return true to game_active variable if there are no colisions
    return True

def rotate_bird(bird):
    # rotozoom can scale and rotate surface
    new_bird=pygame.transform.rotozoom(bird,-bird_movement*3,1)
    return new_bird

def bird_animation():
    new_bird=bird_frames[bird_index]
    #take centery from previous bird position
    new_bird_rect=new_bird.get_rect(center=(100,bird_rect.centery))
    return new_bird,new_bird_rect

def score_display(game_state):

    if game_state=='main_game':
        score_surface=game_font.render(str(int(score)),True,(255,255,255))
        score_rect=score_surface.get_rect(center=(210,80))
        screen.blit(score_surface,score_rect)

    #if game over then also show highscore
    if game_state=='game_over':
        score_surface=game_font.render(f'Score: {int(score)}',True,(255,255,255))
        score_rect=score_surface.get_rect(center=(210,80))
        screen.blit(score_surface,score_rect)

        high_score_surface=game_font.render(f'High score: {int(high_score)}',True,(0,0,0))
        high_score_rect=high_score_surface.get_rect(center=(210,500))
        screen.blit(high_score_surface,high_score_rect)

def update_score(score,high_score):
    if score>high_score:
        high_score=score
    return high_score

def pipe_score_check():
    global score,can_score

    if pipe_list:
        for pipe in pipe_list:
            if 95<pipe.centerx<105 and can_score==True:
                score+=1
                score_sound.play()
                can_score=False
            if pipe.centerx<0:
                can_score=True

#pygame.mixer.pre_init(frequency=44100,size=16,channels=1,buffer=512)

# initializing pygame
pygame.init()

# creating black screen (width x height)
screen=pygame.display.set_mode((420,700))
# screen=pygame.display.set_mode((576,1024))

# clock needed to limit frame rates
clock=pygame.time.Clock()
# Game font
game_font=pygame.font.Font('04B_19.TTF',40)

#Game variables
gravity=0.25
bird_movement=0
game_active=True
score=0
high_score=0
can_score=True

#setting up background variable
bg_surface=pygame.image.load('assets/background-day.png').convert()  #convert turns the images into a file which is easier to understand for pygame
# resizing background image
bg_surface = pygame.transform.scale(bg_surface, (int(bg_surface.get_width() * 1.5), int(bg_surface.get_height() * 1.5)))

floor_surface=pygame.image.load('assets/base.png').convert()
floor_surface = pygame.transform.scale(floor_surface, (int(floor_surface.get_width() * 1.5), int(floor_surface.get_height() * 1.5)))
# variable to change the frame x position, so it looks like its moving
floor_x_pos=0

# BIRD MOVEMENT

bird_downflap=pygame.image.load('assets/bluebird-downflap.png').convert_alpha() #convert alpha to remove black bg
bird_downflap = pygame.transform.scale(bird_downflap, (int(bird_downflap.get_width() * 1.5), int(bird_downflap.get_height() * 1.5)))

bird_midflap=pygame.image.load('assets/bluebird-midflap.png').convert_alpha()
bird_midflap = pygame.transform.scale(bird_midflap, (int(bird_midflap.get_width() * 1.5), int(bird_midflap.get_height() * 1.5)))

bird_upflap=pygame.image.load('assets/bluebird-upflap.png').convert_alpha()
bird_upflap = pygame.transform.scale(bird_upflap, (int(bird_upflap.get_width() * 1.5), int(bird_upflap.get_height() * 1.5)))

bird_frames=[bird_downflap,bird_midflap,bird_upflap]
bird_index=0
bird_surface=bird_frames[bird_index]
# get a imaginary rectangle around image which help in detecting colision
bird_rect=bird_surface.get_rect(center=(100,300))

BIRDFLAP=pygame.USEREVENT + 1  # +1 for second event
pygame.time.set_timer(BIRDFLAP,200)
# bird_surface=pygame.image.load('assets/bluebird-midflap.png').convert_alpha()
# bird_surface = pygame.transform.scale(bird_surface, (int(bird_surface.get_width() * 1.5), int(bird_surface.get_height() * 1.5)))
# bird_rect=bird_surface.get_rect(center=(100,300))

pipe_surface=pygame.image.load('assets/pipe-green.png').convert()
pipe_surface = pygame.transform.scale(pipe_surface, (int(pipe_surface.get_width() * 1.5), int(pipe_surface.get_height() * 1.5)))
# This list contains lots of rectangle that are moving left and new pipes are created after small time intervals
pipe_list=[]
#timer
SPAWNPIPE=pygame.USEREVENT
# event will be triggered every 1.2 sec
pygame.time.set_timer(SPAWNPIPE,1200)
#pipe height for random to choose from
pipe_height=[250,400,500]

#images to display when game gets over
game_over_surface=pygame.image.load('assets/message.png').convert_alpha()
game_over_surface = pygame.transform.scale(game_over_surface, (int(game_over_surface.get_width() * 1.2), int(game_over_surface.get_height() * 1.2)))
game_over_rect=game_over_surface.get_rect(center=(210,280))

# add sound effect
flap_sound=pygame.mixer.Sound('sound/sfx_wing.wav')
death_sound=pygame.mixer.Sound('sound/sfx_hit.wav')
score_sound=pygame.mixer.Sound('sound/sfx_point.wav')
score_sound_countdown=100

while True:

    # looks for every event in the game
    for event in pygame.event.get():
        # quit event type
        if event.type==pygame.QUIT:
            pygame.quit()
            #shuting down the game
            sys.exit()

        if event.type==pygame.KEYDOWN:
            # checking keyboard input
            if event.key==pygame.K_SPACE and game_active==True:
                # print("jump")
                #reseting movement so jump height remains same
                bird_movement=0
                bird_movement-=7
                flap_sound.play()

            # if collision occurs
            if event.key==pygame.K_SPACE and game_active==False:
                game_active=True
                #clearing  pipes if game over
                pipe_list.clear()
                #recenter and reset bird for new game
                bird_rect.center=(100,300)
                bird_movement=0
                score=0

        #PIPES
        if event.type==SPAWNPIPE:
            # print("pipe")
            # pipe_list.append(create_pipe())
            pipe_list.extend(create_pipe())
            # print(pipe_list)

        if event.type==BIRDFLAP:
            if bird_index>2:
                bird_index+=1
            else:
                bird_index=0

            bird_surface,bird_rect=bird_animation()

    #adding backgroung image
    screen.blit(bg_surface,(0,0))

    # if game is active, then only show bird and pipes
    if game_active==True:
        #BIRD
        #changing bird position
        bird_movement+=gravity
        rotated_bird=rotate_bird(bird_surface)
        #moving bird rectangle downwards (falling)
        bird_rect.centery+=bird_movement
        screen.blit(rotated_bird,bird_rect)
        game_active=check_collision(pipe_list)

        #PIPES
        pipe_list=move_pipes(pipe_list)
        draw_pipes(pipe_list)
        # score+=0.01

        #SCORES
        pipe_score_check()
        score_display('main_game')
        # score_sound_countdown-=1
        # if score_sound_countdown<=0:
        #     score_sound.play()
        #     score_sound_countdown=100

    else:
        screen.blit(game_over_surface,game_over_rect)
        high_score=update_score(score,high_score)
        score_display('game_over')

    #FLOOR
    floor_x_pos-=1
    draw_floor()
    if floor_x_pos<=-420: #to move the floor indefinetely
        floor_x_pos=0

    #takes everything drawn above and keeps continuosly updating it
    pygame.display.update()
    # 120 frames per second
    clock.tick(120)


# coding: utf-8

# In[1]:

"""speed test per duo align
attualmente metterci O(1s) pare esagerato, c'è un collo di bottiglia? va fatto in C?
vedere i contributi delle singole parti
"""

import numpy as np
import os
import random
from collections import defaultdict
from matrix_test import *

# In[2]:

###params

fullPath = "../full"

option = 'loc' # loc or glob
align = 'both' #both, nuconly, bearonly

testversion = 'speed_test'

# In[3]:

RNAdata= defaultdict(list)
##generating sequence/bear data
for file in os.listdir(fullPath):
    expectedOutput = "../fullresults/{}_full_test_results.tsv".format(file.split(".")[0]) ##questa parte al momento
    #non fa nulla
    if os.path.isfile(expectedOutput) or file.startswith('.'):
        print("ignoring {}: already present in fullresults/".format(file))
        continue #ignora se è già stato processato
    #file contiene solo il filename, non il path
    with open(os.path.join(fullPath, file)) as f:
        RF = file.split(".")[0]
        seqs = []
        bears = []
        line=f.readline()
        while(line):
            if line.startswith('>'):
                ID = line.strip()
                line=f.readline()
                seq = line.strip()
                line=f.readline()
                line=f.readline()
                bear = line.strip()
                seqs.append(seq)
                bears.append(bear)

                #print(ID)
            else:line=f.readline()
        RNAdata[RF].append(seqs)
        RNAdata[RF].append(bears)
print(RNAdata.keys())

#print(RNAdata['RF00142'])
rfams = {k:v for k,v in RNAdata.items()}

# In[ ]:

#import all PSSMs
import pickle
b = open('../src/rfam_PSSM_bear_gaps_SUBS.pickle', 'rb')
PSSMs_bear = pickle.load(b)

n = open('../src/rfam_PSSM_nt_gaps_SUBS.pickle', 'rb')
PSSMs_nt = pickle.load(n)

l = open('../src/rfam_list.pickle','rb')
rfam_list = pickle.load(l)
###lista ordinata di PSSM (stesso ordine delle BEAR|NUCpssm)

b.close()
n.close()
l.close()

# In[ ]:
BEAR = "abcdefghi=lmnopqrstuvwxyz^!\"#$%&\'()+234567890>[]:ABCDEFGHIJKLMNOPQRSTUVW{YZ~?_|/\\}@-"
nt = "ACUG-BSWRVKDHNMY"

t = open('../better_time_test.tsv', 'w')
giafatto = []
header = "LPSSM\tLSEQ\ttinit\ttfill\tttrace\tttot"
t.write(header)
for rf_ in rfam_list:
    pssmn = PSSMs_nt[rfam_list.index(rf_)]
    pssmb = PSSMs_bear[rfam_list.index(rf_)]
    LPSSM = pssmn.shape[1]

    for targetrf in rfams:
        for seq,bear in zip( rfams[targetrf][0], rfams[targetrf][1]):
            rna = [seq,bear]
            LSEQ = len(seq)
            if (LPSSM, LSEQ) in giafatto:
                continue

            rnamap = [[nt.index(x) for x in rna[0]],[BEAR.index(x) for x in rna[1]]] # to convert chars in indexes
            _,_,_, score, posIdxs,t0,t1,t2,ttot = time_duo_align(PSSMn=pssmn, PSSMb=pssmb, rna=rna, option=option, align=align)

            print(LPSSM, LSEQ)
            giafatto.append((LPSSM,LSEQ))
            row = "\n{}\t{}\t{}\t{}\t{}\t{}".format(LPSSM,LSEQ,t0,t1,t2,ttot)
            t.write(row)
            break
        break
    break

t.close()

# In[ ]:

# In[ ]:


from xai.brain.wordbase.adjectives._august import _AUGUST

#calss header
class _AUGUSTS(_AUGUST, ):
	def __init__(self,):
		_AUGUST.__init__(self)
		self.name = "AUGUSTS"
		self.specie = 'adjectives'
		self.basic = "august"
		self.jsondata = {}


#!/usr/bin/env python
# encoding: utf-8

import os
import numpy as np
from scipy import misc
import pdb
import matplotlib as mpl
mpl.use('Agg')

import torch
from torch.autograd import Variable
from util.DataAugmentation import FaceIdPoseDataset, Resize, RandomCrop
from util.SaveFeature import SaveFeature
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.nn as nn
def Extract_Feature(Model, args):

    save_dir = '{}/{}/Feature'.format(args.output, args.snapshot)

    if not os.path.isdir(save_dir): os.makedirs(save_dir)

    if args.cuda:
        Model.cuda()
    Model.eval()

    count = 0
    # Load augmented data
    #transformed_dataset = FaceIdPoseDataset(args.test_csv_file, args.data_place,
     #                                       transform = transforms.Compose([Resize((256,256)), RandomCrop((224,224))]))
    transformed_dataset = FaceIdPoseDataset(args.test_csv_file, args.data_place,
                                            transforms.Compose([transforms.Resize(256),
                                                                transforms.CenterCrop(224),
                                                                transforms.ToTensor()
                                                                ])
                                            )
    dataloader = DataLoader(transformed_dataset, batch_size=args.Test_Batch, shuffle=False,num_workers=4)

    for i, batch_data in enumerate(dataloader):
        batch_image = torch.FloatTensor(batch_data[0].float())
        minibatch_size = len(batch_image)

        if args.cuda:
            batch_image = batch_image.cuda()
        #batch_image = Variable(batch_image, volatile=True)
        batchImageName = batch_data[1]
        module=list(Model.children())[:-1]
        feature_extractor=nn.Sequential(*module)
        for p in feature_extractor.parameters():
            p.requires_grad = False
        features = feature_extractor(batch_image)
        features = features.data.cpu().numpy()
        SaveFeature(features, batchImageName, save_dir, args)
        count += minibatch_size
        print("Finish Processing {} images...".format(count))


import json
import requests

accessToken = "" #put your access token here between the quotes.

def setHeaders():
	accessToken_hdr = 'Bearer ' + accessToken
	spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'}
	return spark_header

def getRooms(theHeader):
	uri = 'https://api.ciscospark.com/v1/rooms'
	resp = requests.get(uri, headers=theHeader)
	return resp.json()

header=setHeaders()
value=getRooms(header)
print(json.dumps(value, indent=4, separators=(',', ': ')))


import csv
from fuzzywuzzy import fuzz

with open('greedy.csv') as f:
	reader = csv.reader(f)
	text = ' '.join(row[1] for row in reader)

word = input()
text = text.split()
text = list(set(text))
text.sort(key=lambda x: fuzz.ratio(x, word))
text.reverse()
print(text[:10])


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

from .signal import Signal
from typing import List

class Appliance:

    def __str__(self):
        return f"{self.__class__.__name__}: {self.nickname}"

    def __init__(self, data: dict):
        self.id = data["id"]
        self.model = data["model"]
        self.nickname = data["nickname"]
        self.image = data["image"]
        self.type = data["type"]
        self.settings = data["settings"]
        self.aircon = data["aircon"]
        self.signals: List = [Signal(**signal) for signal in data["signals"]]

    def signal(self, name: str) -> Signal:
        result = list(filter(lambda x: name == x.name, self.signals))

        if not len(result):
            raise ValueError(name)

        return result[0]

    def signals(self) -> List[Signal]:
        return self.signals


'''
재석과 광희는 계단 오르기 시합을 하였다.
재석과 광희는 아래와 같은 속도로 올라 간다.
재석
한층을 올라 가는데 7초가 소요 된다.
5층 마다 한층 올라 가는데 걸리는 시간이 1초씩 증가 한다.
광희
한층을 올라 가는데 5초가 소요 된다.
4층 마다 한층 올라 가는데 걸리는 시간이 3초씩 증가 한다.
'''

floor = int(input("층을 입력하세요:"))
js = 0
gh = 0
j_speed = 7
g_speed = 5

# 1층에서 15층까지 올라가면 총 14개의 층을 오르는 것이다.
# for문에서 i가 의미하는 것은 몇층인지가 아닌, 오른 층의 개수이다.
for i in range(1, floor):
    if i % 5 == 0:   # 5개의 층을 올랐을 때 1초씩 증가됨
        j_speed += 1
    if i % 4 == 0:   # 4개의 층을 올랐을 때 3초씩 증가됨
        g_speed += 3

    js += j_speed
    gh += g_speed

print("재석 : %d초" % js)
print("광희 : %d초" % gh)


import sphere
import unittest

class sphereTest(unittest.TestCase):
    def test_surface_area(self):
        assert(sphere.surface_area(0) == 0)
        assert(round(sphere.surface_area(5), 2) == 314.16)

    def test_volume(self):
        assert(sphere.volume(0) == 0)
        assert(round(sphere.volume(5), 2) == 523.6)

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


# http://en.wikipedia.org/wiki/Knuth%E2%80%93Bendix_completion_algorithm
import sys

class knuth_bendix:
    def __init__(self,relators,MAX_DEPTH):
        self.MAX_DEPTH = MAX_DEPTH
        self.reductions = set()
        for rel in relators:
            p = rel[0]*rel[1]
            q = rel[2]*rel[3]
            self.add_red(p,q)
        self.update_reds()
        self.expand_reds()
        self.show_reds()

    # add the reduction p -> q in sorted order (q < p)
    def add_red(self,p,q):
        if p == q:
            return
        assert(p != '')
        if len(q) < len(p) or (len(q) == len(p) and q < p):
            self.reductions.add((p,q))
        else:
            self.reductions.add((q,p))

    # reduce the word "a" using ONLY given reduction "red"
    def reduce_given(self,a,red):
        # first, guarantee termination.
        assert(red[0] != red[1])
        assert(red[0] != '')
        assert(red[0] not in red[1])
        while red[0] in a:
            idx = a.index(red[0])
            a = a[:idx] + red[1] + a[idx + len(red[0]):]
        return a

    # reduce the word "a" using all known rules, EXCEPT itself
    def reduce_almost_all(self,a):
        for red in self.reductions:
            if red[0] == a:
                continue
            a = self.reduce_given(a,red)
        return a

    # reduce the word "a" using all known rules
    def reduce_all(self,a):
        changes_made = True
        while changes_made:
            changes_made = False
            for red in self.reductions:
                change = self.reduce_given(a,red)
                if a != change:
                    changes_made = True
                    a = change
        return a

    # for outside world's use
    def simplify(self,a):
        return self.reduce_all(a)

    # replaces all current reductions with any other reductions possible.
    def update_reds(self):
        changes_made = True
        while changes_made:
            changes_made = False
            reductions_copy = self.reductions.copy()
            for red in reductions_copy:
                red1_reduced = self.reduce_all(red[1])
                red0_reduced = self.reduce_almost_all(red[0])
                if red1_reduced != red[1] or red0_reduced != red[0]:
                    changes_made = True
                self.reductions.remove(red)
                self.add_red(red0_reduced,red1_reduced)

    def expand_reds(self):
        have_checked = {}
        self.more_to_check = True
        self.iters = 0
        while self.more_to_check:
            self.more_to_check = False
            self.iters += 1
            if self.iters > self.MAX_DEPTH:
                sys.stderr.write('Reached maximum iteration depth, quitting\n')
                quit()
            reductions_copy = self.reductions.copy()
            for red_1 in reductions_copy:
                for red_2 in reductions_copy:
                    if (red_1,red_2) in have_checked or red_1 == red_2:
                        continue
                    have_checked[(red_1,red_2)] = True
                    p1 = red_1[0]
                    q1 = red_1[1]
                    p2 = red_2[0]
                    q2 = red_2[1]
                    does_overlap = self.overlap(p1,p2)
                    A,B,C = None,None,None
                    if does_overlap:
                        (A,B,C) = does_overlap
                    elif p2 in p1:
                        idx = p1.index(p2)
                        (A,B,C) = (p1[:idx], p2, p1[idx:])
                    if A:
                        ABC = A + B + C
                        r1 = self.reduce_given(ABC,(p1,q1))
                        r2 = self.reduce_given(ABC,(p2,q2))
                        self.add_red(r1,r2)
                        self.more_to_check = True
            self.update_reds()

    def overlap(self,a,b):
        for i in range(len(b))[::-1]:
            if a[-i:] == b[:i]:
                return (a[:-i], b[:i], b[i:])
        return False

    def show_reds(self):
        max_len = 0
        for red in self.reductions:
            max_len = max(len(red[0]),max_len)
        for red in self.reductions:
            print ('"' + red[0] + '" ' + '-'*(max_len - len(red[0]) + 1)
             + '-> ' + '"' + red[1] + '"')


##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""This is the standard, placeful Translation Domain for TTW development.

"""
__docformat__ = 'restructuredtext'

import re

import zope.component
from BTrees.OOBTree import OOBTree
from zope.container.btree import BTreeContainer
from zope.container.contained import Contained
from zope.i18n import interpolate
from zope.i18n.interfaces import INegotiator
from zope.i18n.interfaces import ITranslationDomain
from zope.i18n.simpletranslationdomain import SimpleTranslationDomain
from zope.interface import implementer

from zope.app.i18n.interfaces import ILocalTranslationDomain
from zope.app.i18n.interfaces import NotYetImplementedError

try:
    unicode
except NameError:
    unicode = str

@implementer(ILocalTranslationDomain)
class TranslationDomain(BTreeContainer, SimpleTranslationDomain, Contained):

    def __init__(self):
        super().__init__()
        self._catalogs = OOBTree()
        self.domain = '<domain not activated>'

    def _registerMessageCatalog(self, language, catalog_name):
        if language not in self._catalogs.keys():
            self._catalogs[language] = []

        mc = self._catalogs[language]
        mc.append(catalog_name)

    def _unregisterMessageCatalog(self, language, catalog_name):
        self._catalogs[language].remove(catalog_name)

    def __setitem__(self, name, object):
        'See IWriteContainer'
        super().__setitem__(name, object)
        self._registerMessageCatalog(object.language, name)

    def __delitem__(self, name):
        'See IWriteContainer'
        object = self[name]
        super().__delitem__(name)
        self._unregisterMessageCatalog(object.language, name)

    def translate(self, msgid, mapping=None, context=None,
                  target_language=None, default=None, msgid_plural=None,
                  default_plural=None, number=None):
        """See interface `ITranslationDomain`"""
        if any((default_plural, msgid_plural, number)):
            raise NotYetImplementedError

        if target_language is None and context is not None:
            avail_langs = self.getAvailableLanguages()
            # Let's negotiate the language to translate to. :)
            negotiator = zope.component.getUtility(INegotiator, context=self)
            target_language = negotiator.getLanguage(avail_langs, context)

        # Get the translation. Default is the source text itself.
        if target_language is not None:
            catalog_names = self._catalogs.get(target_language, [])
        else:
            catalog_names = []

        for name in catalog_names:
            catalog = super().__getitem__(name)
            # TODO: handle msgid_plural
            text = catalog.queryMessage(msgid)
            if text is not None:
                break
        else:
            # If nothing found, delegate to a translation server higher up the
            # tree.
            domain = zope.component.queryNextUtility(self, ITranslationDomain,
                                                     self.domain)
            if domain is not None:
                # TODO: handle msgid_plural
                return domain.translate(msgid, mapping, context,
                                        target_language, default=default)
            if default is None:
                default = unicode(msgid)
            # TODO: handle msgid_plural/default_plural
            text = default

        # Now we need to do the interpolation
        return interpolate(text, mapping)

    def getMessageIds(self, filter='%'):
        'See `IWriteTranslationDomain`'
        filter = filter.replace('%', '.*')
        filter_re = re.compile(filter)

        msgids = {}
        for language in self.getAvailableLanguages():
            for name in self._catalogs[language]:
                for msgid in self[name].getMessageIds():
                    if filter_re.match(msgid):
                        msgids[msgid] = None
        return msgids.keys()

    def getMessages(self):
        'See `IWriteTranslationDomain`'
        messages = []
        languages = self.getAvailableLanguages()
        for language in languages:
            for name in self._catalogs[language]:
                messages += self[name].getMessages()
        return messages

    def getMessage(self, msgid, language):
        'See `IWriteTranslationDomain`'
        for name in self._catalogs.get(language, []):
            try:
                return self[name].getFullMessage(msgid)
            except BaseException:
                pass
        return None

    def getAllLanguages(self):
        'See `IWriteTranslationDomain`'
        return sorted(self._catalogs)

    def getAvailableLanguages(self):
        'See `IWriteTranslationDomain`'
        return self.getAllLanguages()

    def addMessage(self, msgid, msg, language, mod_time=None):
        'See `IWriteTranslationDomain`'
        if language not in self._catalogs:
            if language not in self.getAllLanguages():
                self.addLanguage(language)

        catalog_name = self._catalogs[language][0]
        catalog = self[catalog_name]
        catalog.setMessage(msgid, msg, mod_time)

    def updateMessage(self, msgid, msg, language, mod_time=None):
        'See `IWriteTranslationDomain`'
        catalog_name = self._catalogs[language][0]
        catalog = self[catalog_name]
        catalog.setMessage(msgid, msg, mod_time)

    def deleteMessage(self, msgid, language):
        'See `IWriteTranslationDomain`'
        catalog_name = self._catalogs[language][0]
        catalog = self[catalog_name]
        catalog.deleteMessage(msgid)

    def addLanguage(self, language):
        'See `IWriteTranslationDomain`'
        catalog = zope.component.createObject('zope.app.MessageCatalog',
                                              language)
        catalog.domain = self.domain
        self[language] = catalog

    def deleteLanguage(self, language):
        'See `IWriteTranslationDomain`'
        # Delete all catalogs from the data storage
        for name in self._catalogs[language]:
            if name in self:
                del self[name]
        # Now delete the specifc catalog registry for this language
        del self._catalogs[language]

    def getMessagesMapping(self, languages, foreign_messages):
        'See `ISyncTranslationDomain`'
        mapping = {}
        # Get all relevant local messages
        local_messages = []
        for language in languages:
            for name in self._catalogs.get(language, []):
                local_messages += self[name].getMessages()

        for fmsg in foreign_messages:
            ident = (fmsg['msgid'], fmsg['language'])
            mapping[ident] = (fmsg, self.getMessage(*ident))

        for lmsg in local_messages:
            ident = (lmsg['msgid'], lmsg['language'])
            if ident not in mapping.keys():
                mapping[ident] = (None, lmsg)

        return mapping

    def synchronize(self, messages_mapping):
        'See `ISyncTranslationDomain`'

        for value in messages_mapping.values():
            fmsg = value[0]
            lmsg = value[1]
            if fmsg is None:
                self.deleteMessage(lmsg['msgid'], lmsg['language'])
            elif lmsg is None:
                self.addMessage(fmsg['msgid'],
                                fmsg['msgstr'], fmsg['language'],
                                fmsg['mod_time'])
            elif fmsg['mod_time'] > lmsg['mod_time']:
                self.updateMessage(fmsg['msgid'],
                                   fmsg['msgstr'], fmsg['language'],
                                   fmsg['mod_time'])

def setDomainOnActivation(domain, event):
    """Set the permission id upon registration activation.

    Let's see how this notifier can be used. First we need to create an event
    using the permission instance and a registration stub:

    >>> class Registration:
    ...     def __init__(self, obj, name):
    ...         self.component = obj
    ...         self.name = name

    >>> domain1 = TranslationDomain()
    >>> domain1.domain
    '<domain not activated>'

    >>> import zope.interface.interfaces
    >>> event = zope.interface.interfaces.Registered(
    ...     Registration(domain1, 'domain1'))

    Now we pass the event into this function, and the id of the domain should
    be set to 'domain1'.

    >>> setDomainOnActivation(domain1, event)
    >>> domain1.domain
    'domain1'
    """
    domain.domain = event.object.name

def unsetDomainOnDeactivation(domain, event):
    """Unset the permission id up registration deactivation.

    Let's see how this notifier can be used. First we need to create an event
    using the permission instance and a registration stub:

    >>> class Registration:
    ...     def __init__(self, obj, name):
    ...         self.component = obj
    ...         self.name = name

    >>> domain1 = TranslationDomain()
    >>> domain1.domain = 'domain1'

    >>> import zope.interface.interfaces
    >>> event = zope.interface.interfaces.Unregistered(
    ...     Registration(domain1, 'domain1'))

    Now we pass the event into this function, and the id of the role should be
    set to '<domain not activated>'.

    >>> unsetDomainOnDeactivation(domain1, event)
    >>> domain1.domain
    '<domain not activated>'
    """
    domain.domain = '<domain not activated>'


import pygame

pygame.init()

white=(255,255,255)
black=(0,0,0)
red=(255,0,0)

gameDisplay = pygame.display.set_mode((800,600))

pygame.display.set_caption('First Game')

gameExit= False

lead_x = 300
lead_y = 300
lead_x_change = 0
lead_y_change = 0

clock = pygame.time.Clock()	#returns pygame clock object

while not gameExit:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			gameExit = True
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_LEFT:
				lead_x_change -= 2
			elif event.key == pygame.K_RIGHT:
				lead_x_change += 2
			elif event.key == pygame.K_UP:
				lead_y_change -= 2
			elif event.key == pygame.K_DOWN:
				lead_y_change += 2
		elif event.type == pygame.KEYUP:		#key is released
			if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
				lead_x_change = 0
			elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
				lead_y_change = 0

	lead_x +=lead_x_change
	lead_y +=lead_y_change
	gameDisplay.fill(white)
	pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])
	pygame.display.update()

	clock.tick(10)		#frames per second 30 most suitable

pygame.quit()
quit()


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 11:14:51 2017

@author: SH-NoteBook
"""

#200103~20170531 2 5 8 11 월 말 리밸런싱
#12 month forward 당기순이익 있는건 그대로 쓰고 없다면 trailing 당기순이익 사용
#당기순이익이나 자기자본, 현금배당이 NAN인것들 제외
#==============================================================================
# MSCI Value = > Trailing PBR 역수, PBR 12m forward 역수, 배당수익률 역수
# 양끝 5% 제거하지 않음~!, pbr, per, div 각각 독립적으로 z-score 구해서 산술평균
# 각 size 별 z_score 상위 30 % 골라서 투자
#==============================================================================
import pandas as pd
import numpy as np

#raw_data_=pd.read_excel('exercise_v02.xlsx',sheetname='Raw_data1',header=None)
#raw_data=pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='Raw_data1',header=None)  # 편입시장
#size = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='시가총액1',header=None)  #시가총액
#ni = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='당기순이익MAIN1',header=None)  # 당기순이익
#ni_12m_fw = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='월별당기순이익CON1',header=None)  # 당기순이익
#rtn = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='수익률1',header=None)  #수익률
#equity = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='자본총계1',header=None)  #자본총걔
#size_FIF_wisefn = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='유통주식수x수정주가1',header=None)  #free floating 시가총액
#cash_div = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='현금배당액1',header=None)
#sector = pd.read_excel('msci_rawdata_kospi_20170531_25811.xlsm',sheetname='업종1',header=None)
#
#raw_data.to_pickle('raw_data')
#size.to_pickle('size')
#ni.to_pickle('ni')
#rtn.to_pickle('rtn')
#equity.to_pickle('equity')
#cash_div.to_pickle('cash_div')
#size_FIF_wisefn.to_pickle('size_FIF_wisefn')
#ni_12m_fw.to_pickle('ni_12m_fw')
#sector.to_pickle('sector')

#kospi_quarter = pd.read_pickle('kospi_quarter')
raw_data = pd.read_pickle('raw_data')
size = pd.read_pickle('size')  #시가총액
ni = pd.read_pickle('ni') # 당기순이익
ni_12m_fw = pd.read_pickle('ni_12m_fw')
rtn = pd.read_pickle('rtn')
equity = pd.read_pickle('equity') #자본총계
cash_div = pd.read_pickle('cash_div')
size_FIF_wisefn=pd.read_pickle('size_FIF_wisefn') #시가총액
sector=pd.read_pickle('sector')

raw_data_kq = pd.read_pickle('raw_data_kq')
size_kq = pd.read_pickle('size_kq')  #시가총액
ni_kq = pd.read_pickle('ni_kq') # 당기순이익
ni_12m_fw_kq = pd.read_pickle('ni_12m_fw_kq')
rtn_kq = pd.read_pickle('rtn_kq')
equity_kq = pd.read_pickle('equity_kq') #자본총계
cash_div_kq = pd.read_pickle('cash_div_kq')
size_FIF_wisefn_kq=pd.read_pickle('size_FIF_wisefn_kq') #시가총액
sector_kq=pd.read_pickle('sector_kq') #시가총액

#소형주 + KOSDAQ 하기 위해 새로운 rawdata 생성(primary key 때문에)
raw_data_sum=pd.concat([raw_data,raw_data_kq],axis=0,ignore_index=True)
rtn_sum=pd.concat([rtn,rtn_kq],axis=0,ignore_index=True)
size_sum=pd.concat([size,size_kq],axis=0,ignore_index=True)
ni_12m_fw_sum = pd.concat([ni_12m_fw,ni_12m_fw_kq],axis=0,ignore_index=True)
ni_sum=pd.concat([ni,ni_kq],axis=0,ignore_index=True)
equity_sum=pd.concat([equity,equity_kq],axis=0,ignore_index=True)
size_FIF_wisefn_sum=pd.concat([size_FIF_wisefn,size_FIF_wisefn_kq],axis=0,ignore_index=True)
cash_div_sum=pd.concat([cash_div,cash_div_kq],axis=0,ignore_index=True)
sector_sum=pd.concat([sector,sector_kq],axis=0,ignore_index=True)
#size_FIF=pd.read_pickle('size_FIF')  #자기주식 제외 시가총액
#size_FIF_insider=pd.read_pickle('size_FIF_insider') #자기주식, 최대주주 주식 제외 시가총
#size_FIF_wisefn = pd.read_excel('msci_rawdata.xlsx',sheetname='유통주식수x수정주가1',header=None) # wisefn에서 산출해주는 유통비율 이용
#size_FIF_wisefn.to_pickle('size_FIF_wisefn')

turnover = pd.DataFrame(np.zeros((1,1)))
return_data = np.zeros((5,66))
return_data = pd.DataFrame(return_data)
data_name=pd.DataFrame(np.zeros((1000,66)))
kosdaq_count = pd.DataFrame(np.zeros((1,66)))
# 매 분기 수익률을 기록하기 위해 quarter_data를 만듬
quarter_data = pd.DataFrame(np.zeros((1000,198)))
sector_data = pd.DataFrame(np.zeros((1000,132)))
group_data = pd.DataFrame(np.zeros((1000,132)))
for n in range(3,69):
    #66마지막 분기
    data_big = raw_data_sum[(raw_data_sum[n] == 1)|(raw_data_sum[n] == 2)|(raw_data_sum[n] == 3)|(raw_data_sum[n] == 'KOSDAQ')]
    data_big = data_big.loc[:,[1,n]]
    #ni_12m_fw_sum 쓰면 fwd per, 그냥 ni_sum 쓰면 trailing
    data = pd.concat([data_big, size_FIF_wisefn_sum[n], equity_sum[n], ni_12m_fw_sum[n],cash_div_sum[n],size_sum[n],rtn_sum[n-3],sector_sum[n]],axis=1,join='inner',ignore_index=True)
    data.columns = ['name','group','size_FIF_wisefn','equity','ni_12fw','cash_div','size','return','sector']
    data=data[data['size']>100000000000]
    #상폐, 지주사전환, 분할상장 때문에 생기는 수익률 0 제거
    data=data[data['return']!=0]
    result_temp = data
    samsung = pd.DataFrame(data.loc[390,:]).transpose()
    #만약 삼전의 재무재표중 없는게 있다면 14 column을 맞추기 위해 0을 넣어버림
#    if (np.isnan(result_temp.loc[390]['equity']))|(np.isnan(result_temp.loc[390]['ni_12fw']))|(np.isnan(result_temp.loc[390]['cash_div'])):
#        samsung = pd.DataFrame(result_temp.loc[390,:]).transpose()
#        samsung['1/pbr'] = 0
#        samsung['1/per'] = 0
#        samsung['div_yield'] = 0
#        samsung['pbr_z'] = 0
#        samsung['per_z'] = 0
#        samsung['div_z'] = 0
#        samsung['z_score'] = 0

    data = data[data['equity'].notnull()]
    data = data[data['ni_12fw'].notnull()]
    data = data[data['cash_div'].notnull()]

    # per, pbr, div_yield 구할때는 전체 시가총액을 사용,
    # 시총비중 구할떄는 free-float
    data['size_FIF_wisefn']=data['size_FIF_wisefn']/1000    #size 단위 thousand
    data['1/pbr']=data['equity']/data['size']
    data['1/per']=data['ni_12fw']/data['size']
    data['div_yield']=data['cash_div']/data['size']

    # inf, -inf 값들을 NAN 값으로 변경 (그래야 한번에 제거 가능)
    data = data.replace([np.inf, -np.inf],np.nan)

    # Null 값 제거
    data_per = data[data['1/per'].notnull()]
    data_pbr = data[data['1/pbr'].notnull()]
    data_div = data[data['div_yield'].notnull()]

    #양 끝 5% 구함
#    market_capital=np.sum(data['size'])
#    pbr_min=np.percentile(data_pbr['1/pbr'],5)
#    pbr_max=np.percentile(data_pbr['1/pbr'],95)
#    per_min=np.percentile(data_per['1/per'],5)
#    per_max=np.percentile(data_per['1/per'],95)
#    div_min=np.percentile(data_div['div_yield'],5)
#    div_max=np.percentile(data_div['div_yield'],95)

    #양끝단  5% 제거
#    data_pbr = data_pbr[(data_pbr['1/pbr']>pbr_min)&(data_pbr['1/pbr']<pbr_max)]
#    data_per = data_per[(data_per['1/per']>per_min)&(data_per['1/per']<per_max)]
#    data_div = data_div[(data_div['div_yield']>div_min)&(data_div['div_yield']<div_max)]

    # 시가총액비중 구함
    data_pbr_cap = np.sum(data_pbr['size_FIF_wisefn'])
    data_per_cap = np.sum(data_per['size_FIF_wisefn'])
    data_div_cap = np.sum(data_div['size_FIF_wisefn'])

    data_pbr = data_pbr.assign(market_weight=data_pbr['size_FIF_wisefn']/data_pbr_cap)
    data_per = data_per.assign(market_weight=data_per['size_FIF_wisefn']/data_per_cap)
    data_div = data_div.assign(market_weight=data_div['size_FIF_wisefn']/data_div_cap)

    # 시총가중 평균
    mu_inv_pbr=np.sum(data_pbr['1/pbr']*data_pbr['market_weight'])
    mu_inv_per=np.sum(data_per['1/per']*data_per['market_weight'])
    mu_inv_div=np.sum(data_div['div_yield']*data_div['market_weight'])

    # 시총 가중 표준편자
    std_inv_pbr=np.sqrt(np.sum(np.square(data_pbr['1/pbr']-mu_inv_pbr)*data_pbr['market_weight']))
    std_inv_per=np.sqrt(np.sum(np.square(data_per['1/per']-mu_inv_per)*data_per['market_weight']))
    std_inv_div=np.sqrt(np.sum(np.square(data_div['div_yield']-mu_inv_div)*data_div['market_weight']))

    data1=(data_pbr['1/pbr']-mu_inv_pbr)/std_inv_pbr
    data1.name= 'pbr_z'
    data2=(data_per['1/per']-mu_inv_per)/std_inv_per
    data2.name= 'per_z'
    data3=(data_div['div_yield']-mu_inv_div)/std_inv_div
    data3.name= 'div_z'

    result = pd.concat([data, data1, data2, data3], axis = 1)

    # np.nanmean : nan 값 포함해서 평균 내기!!
    result = result.assign(z_score=np.nanmean(result.iloc[:,[12,13,14]],axis=1))
#    result_temp = result

    # z_score > 0 인것이 가치주라고 msci에서 하고있음
    result =result[result['z_score'].notnull()]

    #상위 65%로 결정하면 삼성전자가 n=64,65,66일때 모두 포함이 된다.
#    z_score1_max=np.percentile(result['z_score'],50)
#    result =result[result['z_score']>z_score1_max]
    result=result.assign(rnk=result['z_score'].rank(method='first',ascending=False))

#    result = pd.concat([result,pd.DataFrame(result_temp.loc[390,:]).transpose()],axis=0)
    #어쨋든 삼전이 탈락했다면
#    if np.sum(result['name']=="삼성전자")!=1:
#        samsung['1/pbr'] = 0
#        samsung['1/per'] = 0
#        samsung['div_yield'] = 0
#        samsung['pbr_z'] = 0
#        samsung['per_z'] = 0
#        samsung['div_z'] = 0
#        samsung['z_score'] = 0
#        result = pd.concat([result,samsung],axis=0)

    #중복 rows 1개 빼고 다 제거
    result = result.drop_duplicates()
    result = result[result['rnk']<201]

#    result = pd.concat([result,rtn_sum[n-3]],axis=1,join='inner',ignore_index=True) #수익률 매칭

#대형주+중형주+소형주+KOSDAQ

    #코스닥이 몇종목 포함되었는지 기록
    try :
        kosdaq_number = result['group']=='KOSDAQ'
    except :
        kosdaq_number = result['group']==0
    kosdaq_number2 = pd.DataFrame(kosdaq_number.cumsum(axis=0))
    len3 = len(kosdaq_number2)
    kosdaq_count.iloc[0,n-3] = kosdaq_number2.iloc[len3-1,0]

    #n=33 일때 국민은행 같은게 지주사로 전환되면서 수익률이 0으로 나와버림 NAN이랑은 다른개념
    #사전에 공시가 되기 때문에 거를수 있을거라 판단해서 제외
    #일딴 여기서 제거해보고 , z 값 산출 전에 제거하는법 생각
#    result = result[result[15]!=0]
    #매 분기 수익률을 기록
    quarter_data[[3*(n-3),3*(n-3)+1,3*(n-3)+2]] = result.iloc[:,[0,1,7]].reset_index(drop=True)
    market_capital=np.sum(result['size_FIF_wisefn'])
    result=result.assign(market_weight2=result['size_FIF_wisefn']/market_capital)

    #동일가중
    return_data.iloc[0,n-3]=np.mean(result['return'])
#시총가중
#    return_data.iloc[0,n-3]=np.sum(result[14]*result['market_weight2'])
    data_name[n-3]=result['name'].reset_index(drop=True)
    #섹터별 비중 구함
    sector_data[[2*(n-3),2*(n-3)+1]]=result.groupby('sector').size().reset_index(drop=False)
    group_data[[2*(n-3),2*(n-3)+1]]=result.groupby('group').size().reset_index(drop=False)
#    return_data.iloc[0,n-3]=np.sum(result[13]*result[14])
    if n == 68 :
        pass
    return_final=np.product(return_data,axis=1)

    # 삼성전자가 몇분기동안 포함되었는지 확인
np.sum(np.sum(data_name=="삼성전자"))

average_return = np.mean(return_data,axis=1)
std_return = np.std(return_data,axis=1)
average_return/std_return
#turnover
for n in range(3,68):

    len1 = len(data_name[data_name[n-2].notnull()])
    aaa=data_name.loc[:,[n-3,n-2]]
    bbb=pd.DataFrame(aaa.stack().value_counts())
    len2=len(bbb[bbb[0]==2])
    data_name.loc[999,n-2]=(len1-len2)/len1
    qqqqq=data_name.iloc[999,1:]
    turnover=np.mean(qqqqq)

#승률
#diff = return_data - np.tile(kospi_quarter,(5,1))
#column_lengh = len(diff.columns)
#diff = diff>0
#true == 1 , False == 0 으로 판단하기 때문에 다 더하면 가장 끝 column에 0보다 큰 것들 갯수가 남음
#diff = diff.cumsum(axis=1)
#win_rate = diff[column_lengh-1]/column_lengh

#섹터별 비중구하기 마지막
#초기 기준이 되는 full index 설정
sector_data_temp = sector_data.set_index([0],drop=False)
#초기값 설정
sector_data_count = sector_data_temp.iloc[0:10,1]
sector_data_sum = np.sum(sector_data_count)
sector_data_count = sector_data_count/sector_data_sum

#sector 저장
for n in range(1,66):
    sector_data_temp = sector_data.set_index([2*(n)],drop=False)
    sector_row_lengh = len(sector_data[2*n][sector_data[2*n].notnull()])
    sector_data_count = pd.concat([sector_data_count,sector_data_temp.iloc[0:sector_row_lengh,2*(n)+1]],axis=1)
    sector_data_sum = np.sum(sector_data_count[2*n+1],axis=0)
    sector_data_count[2*n+1] = sector_data_count[2*n+1]/sector_data_sum

#그룹별 비중구하기 마지막
#초기 기준이 되는 full 그룹 설정
group_data_temp = group_data.set_index([0],drop=False)
#초기값 설정
group_data_count = group_data_temp.iloc[0:4,1]
group_data_sum = np.sum(group_data_count)
group_data_count = group_data_count/group_data_sum

#group 저장
for n in range(1,66):
    group_data_temp = group_data.set_index([2*(n)],drop=False)
    group_row_lengh = len(group_data[2*n][group_data[2*n].notnull()])
    group_data_count = pd.concat([group_data_count,group_data_temp.iloc[0:group_row_lengh,2*(n)+1]],axis=1)
    group_data_sum = np.sum(group_data_count[2*n+1],axis=0)
    group_data_count[2*n+1] = group_data_count[2*n+1]/group_data_sum


size = int(input())
num_list = list(map(int,input().split()))

num_div = 0
all_even = True
while all_even:
    for i in range(size):
        if num_list[i]%2 == 1:
            all_even = False
            break
        else:
            num_list[i] //= 2
    if all_even:
        num_div += 1
print(num_div)


from tkinter import *
import random
import copy

class Cell:

    def __init__(self, infect_time, state, age, gender):
        self.infect_time = infect_time
        self.state = state
        self.age = age
        self.gender = gender

    def getinfect_time(self):
        return self.infect_time

    def setinfect_time(self, time):
        self.infect_time = time

    def getstate(self):
        return self.state

    def setstate(self, state):
        self.state = state

    def getage(self):
        return self.age

    def setage(self, age):
        self.age = age

    def getgender(self):
        return self.gender

    def setgender(self, gender):
        self.gender = gender

cell = [[0 for row in range(-1, 61)] for col in range(-1, 81)]
firstGen = [[0 for row in range(-1, 61)] for col in range(-1, 81)]
temporary = [[0 for row in range(-1, 61)] for col in range(-1, 81)]

aleatory_cells = [Cell(1, 2, 15, 0), Cell(0, 0, 22, 0), Cell(1, 1, 52, 0), Cell(0, 0, 59, 0), Cell(0, 0, 26, 0),
                      Cell(0, 1, 17, 1), Cell(0, 0, 19, 1), Cell(0, 0, 57, 1), Cell(0, 0, 61, 1), Cell(0, 0, 28, 1),
                      Cell(0, 0, 33, 0), Cell(1, 2, 45, 0), Cell(1, 1, 29, 0), Cell(0, 0, 45, 0), Cell(0, 0, 25, 0),
                      Cell(0, 0, 35, 1), Cell(0, 0, 43, 1), Cell(0, 0, 36, 1), Cell(0, 0, 13, 1), Cell(0, 0, 24, 1)]

def make_frames():
    processing()
    paint_cells()
    root.after(1000, make_frames)

def put_cells():
    # state: 0 = susceptible, 1 = infected, 2 = developing symptoms
    # age: groups; 15 - 24; 25 - 49; 50 - 69
    # man = 0  woman = 1

    for y in range(-1, 61):
        for x in range(-1, 81):
            firstGen[x][y] = random.choice(aleatory_cells)
            temporary[x][y] = 0
            cell[x][y] = canvas.create_oval((x * 10, y * 10, x * 10 + 10, y * 10 + 10), outline="gray50", fill="black")

def processing():
    cells_state_0 = 0
    cells_state_1 = 0
    cells_state_2 = 0
    N_young = 0
    young_woman_infected = 0
    young_man_infected = 0

    for y in range(0, 60):
        for x in range(0, 80):
            infected_neighbors_state1 = search_neigh_state1(x, y)
            infected_neighbors_state2 = search_neigh_state2(x, y)
            if 16 <= firstGen[x][y].getage() <= 25:
                N_young += 1
                if (firstGen[x][y].getgender() == 1) and (firstGen[x][y].getstate() == 1 or firstGen[x][y].getstate() == 2):
                    young_woman_infected += 1
                if (firstGen[x][y].getgender() == 0) and (firstGen[x][y].getstate() == 1 or firstGen[x][y].getstate() == 2):
                    young_man_infected += 1

            if firstGen[x][y].getinfect_time() > 12:
                temporary[x][y] = random.choice(aleatory_cells)

            else:
                if firstGen[x][y].getstate() == 0:
                    cells_state_0 += 1
                    if (infected_neighbors_state1 > 3 or infected_neighbors_state2 > 2) and \
                            (16 < firstGen[x][y].getage() > 25):
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setstate(1)
                    elif infected_neighbors_state1 > 4 or infected_neighbors_state2 > 3:
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setstate(1)
                    else:
                        temporary[x][y] = copy.copy(firstGen[x][y])

                elif firstGen[x][y].getstate() == 1:
                    cells_state_1 += 1
                    if firstGen[x][y].getinfect_time() == 5:
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setstate(2)
                        temporary[x][y].setinfect_time(firstGen[x][y].getinfect_time() + 1)
                    else:
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setinfect_time(temporary[x][y].getinfect_time() + 1)

                elif firstGen[x][y].getstate() == 2:
                    cells_state_2 += 1
                    if firstGen[x][y].getinfect_time() > 8:
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setstate(1)
                        temporary[x][y].setinfect_time(temporary[x][y].getinfect_time() + 1)
                    else:
                        temporary[x][y] = copy.copy(firstGen[x][y])
                        temporary[x][y].setinfect_time(temporary[x][y].getinfect_time() + 1)

    archive = open("info.txt", "a")
    archive2 = open("info.txt", "r")
    content = archive2.readlines()
    number_of_lines = len(content)
    archive.write("mounth: %d" % ((number_of_lines / 8) + 1) + "\n")
    print((number_of_lines / 8) + 1)
    archive.write("cells susceptible: %d" % cells_state_0 + "\n")
    archive.write("cells infected: %d" % cells_state_1 + "\n")
    archive.write("cells with symptoms: %d" % cells_state_2 + "\n")
    archive.write("young: %d " % N_young + "\n")
    archive.write("young woman infected: %d " % young_woman_infected + "\n")
    archive.write("young man infected: %d " % young_man_infected + "\n")
    archive.write("----------------------------" + "\n")

    for y in range(0, 60):
        for x in range(0, 80):
            firstGen[x][y] = temporary[x][y]

def search_neigh_state1(a, b):
    neigh_state1 = 0

    if firstGen[a - 1][b + 1].getstate() == 1:
        neigh_state1 += 1

    if firstGen[a][b + 1].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a + 1][b + 1].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a - 1][b].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a + 1][b].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a - 1][b - 1].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a][b - 1].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    if firstGen[a + 1][b - 1].getstate() == 1:
        neigh_state1 = neigh_state1 + 1

    return neigh_state1

def search_neigh_state2(a, b):
    neigh_state2 = 0

    if firstGen[a - 1][b + 1].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a][b + 1].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a + 1][b + 1].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a - 1][b].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a + 1][b].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a - 1][b - 1].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a][b - 1].getstate() == 2:
        neigh_state2 += 1

    if firstGen[a + 1][b - 1].getstate() == 2:
        neigh_state2 += 1

    return neigh_state2

def paint_cells():
    for y in range(60):
        for x in range(80):
            if firstGen[x][y].getstate() == 0:
                canvas.itemconfig(cell[x][y], fill="black")
            if firstGen[x][y].getstate() == 1:
                canvas.itemconfig(cell[x][y], fill="yellow")
            if firstGen[x][y].getstate() == 2:
                canvas.itemconfig(cell[x][y], fill="red")

root = Tk()
canvas = Canvas(root, width=800, height=600, highlightthickness=0, bd=0, bg='black')
canvas.pack()
put_cells()

make_frames()
root.mainloop()


import cv2
import numpy as np
import imutils

#cv2.ocl.setUseOpenCL(False)
#where is the image stored
image=cv2.imread('target.jpg')

#range of BGR values. cuz apparently opencv represents images as Np arrays in reverse order?
D_PRINT = True
def dprint(s):
    if D_PRINT:
        print(s)

mapping = {'red': ([17,15,100],[50,56,200])}

color2detect = 'red'
boundaries = mapping[color2detect]

#cv2.imshow('image',image)
lower=np.array(boundaries[0], dtype = "uint8")
upper=np.array(boundaries[1],dtype = "uint8")
mask=cv2.inRange(image, lower, upper) # binary mask of white n black pixel
#cv2.imshow('mask',mask)
result=cv2.bitwise_and(image, image, mask=mask)
#cv2.imshow('images',np.hstack([image,result]))
cv2.waitKey(0)
result=np.array(result)
#cv2.imshow('result2',result)
contours=cv2.findContours(mask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
dims = ()
for c in contours:
    peri = cv2.arcLength(c,True)
    approx = cv2.approxPolyDP(c,0.04*peri,True)

    x,y,w,h=cv2.boundingRect(np.float32(approx)) #returns rectangle object with xy cor of top left corner n width n height parameter
    if w >= 100 and h >= 80:
        dims= (x,y)
        break

dprint(dims)

# if w==3 and h==3:
#     al_Cor=(x+0.5*w,y+0.5*h)
#     get_loc= 3
#     get_dir= 4
# dprint(al_Cor)
# dprint(get_loc)
# dprint(get_dir)


from __future__ import annotations

import io
import logging
import os
import pathlib
import shutil
import tarfile
import tempfile
import time
from typing import cast
from typing import IO

from comicapi.archivers import Archiver

logger = logging.getLogger(__name__)

class TarArchiver(Archiver):

    """TAR implementation"""

    def __init__(self) -> None:
        super().__init__()
        # tar archives take filenames literally `./ComicInfo.xml` is not `ComicInfo.xml`
        self.path_norm: dict[str, str] = {}

    # @todo: Implement Comment? tar files do not have native comments
    def get_comment(self) -> str:
        return ""

    def set_comment(self, comment: str) -> bool:
        return False

    def read_file(self, archive_file: str) -> bytes:
        archive_file = str(pathlib.PurePosixPath(archive_file))
        if not self.path_norm:
            self.get_filename_list()
        if archive_file in self.path_norm:
            archive_file = self.path_norm[archive_file]

        try:
            with tarfile.TarFile(self.path, mode="r", encoding="utf-8") as tf:
                with cast(IO[bytes], tf.extractfile(archive_file)) as file:
                    data = file.read()
        except (tarfile.TarError, OSError) as e:
            logger.error("Error reading tar archive [%s]: %s :: %s", e, self.path, archive_file)
            raise
        return data

    def remove_file(self, archive_file: str) -> bool:
        return self.rebuild([archive_file])

    def write_file(self, archive_file: str, data: bytes) -> bool:
        # At the moment, no other option but to rebuild the whole
        # archive w/o the indicated file. Very sucky, but maybe
        # another solution can be found
        files = self.get_filename_list()
        if archive_file in files:
            if not self.rebuild([archive_file]):
                return False

        try:
            archive_file = str(pathlib.PurePosixPath(archive_file))
            # now just add the archive file as a new one
            with tarfile.TarFile(self.path, mode="a", encoding="utf-8") as tf:
                tfi = tarfile.TarInfo(archive_file)
                tfi.size = len(data)
                tfi.mtime = int(time.time())
                tf.addfile(tfi, io.BytesIO(data))
            return True
        except (tarfile.TarError, OSError) as e:
            logger.error("Error writing tar archive [%s]: %s :: %s", e, self.path, archive_file)
            return False

    def get_filename_list(self) -> list[str]:
        try:
            with tarfile.TarFile(self.path, mode="r", encoding="utf-8") as tf:
                namelist = []
                for name in tf.getnames():
                    new_name = pathlib.PurePosixPath(name)
                    namelist.append(str(new_name))
                    self.path_norm[str(new_name)] = name

            return namelist
        except (tarfile.TarError, OSError) as e:
            logger.error("Error listing files in tar archive [%s]: %s", e, self.path)

            return []

    def rebuild(self, exclude_list: list[str]) -> bool:
        """tar helper func

        This recreates the tar archive, without the files in the exclude_list
        """
        try:
            with tarfile.TarFile(
                fileobj=tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False),
                mode="w",
                encoding="utf-8",
            ) as tout:
                with tarfile.TarFile(self.path, mode="r", encoding="utf-8") as tin:
                    for item in tin.getmembers():
                        buffer = tin.extractfile(item)
                        if str(pathlib.PurePosixPath(item.name)) not in exclude_list:
                            tout.addfile(item, buffer)

                # replace with the new file
                self.path.unlink(missing_ok=True)
                tout.close()  # Required on windows

                shutil.move(str(tout.name), self.path)

        except (OSError, tarfile.TarError) as e:
            logger.error("Error rebuilding tar file [%s]: %s", e, self.path)
            return False
        return True

    def copy_from_archive(self, other_archive: Archiver) -> bool:
        # Replace the current tar with one copied from another archive
        try:
            with tarfile.TarFile(self.path, mode="w", encoding="utf-8") as tout:
                for fname in other_archive.get_filename_list():
                    data = other_archive.read_file(fname)
                    if data is not None:
                        # All archives should use `/` as the directory separator
                        tfi = tarfile.TarInfo(str(pathlib.PurePosixPath(fname)))
                        tfi.size = len(data)
                        tfi.mtime = int(time.time())
                        tout.addfile(tfi, io.BytesIO(data))

        except Exception as e:
            logger.error("Error while copying to tar archive [%s]: from %s to %s", e, other_archive.path, self.path)
            return False
        else:
            return True

    def is_writable(self) -> bool:
        """
        Retuns True if the current archive is writeable
        Should always return a boolean. Failures should return False.
        """
        return True

    def extension(self) -> str:
        """
        Returns the extension that this archiver should use eg ".cbz".
        Should always return a string. Failures should return the empty string.
        """
        return ".cbt"

    def name(self) -> str:
        """
        Returns the name of this archiver for display purposes eg "CBZ".
        Should always return a string. Failures should return the empty string.
        """
        return "TAR"

    @classmethod
    def is_valid(cls, path: pathlib.Path) -> bool:
        """
        Returns True if the given path can be opened by this archiver.
        Should always return a boolean. Failures should return False.
        """
        return tarfile.is_tarfile(path)


# coding: utf-8

"""
    Cisco Firepower Management Center Open API Specification

    **Specifies the REST URLs and methods supported in the Cisco Firepower Management Center API. Refer to the version specific [REST API Quick Start Guide](https://www.cisco.com/c/en/us/support/security/defense-center/products-programming-reference-guides-list.html) for additional information.**  # noqa: E501

    OpenAPI spec version: 1.0.0
    Contact: tac@cisco.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six

class IOspfv3NeighborProperties(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'neighbor_cost': 'IOspfv3NeighborCost',
        'neighbor_priority': 'IOspfv3NeighborPriority'
    }

    attribute_map = {
        'neighbor_cost': 'neighborCost',
        'neighbor_priority': 'neighborPriority'
    }

    def __init__(self, neighbor_cost=None, neighbor_priority=None):  # noqa: E501
        """IOspfv3NeighborProperties - a model defined in Swagger"""  # noqa: E501

        self._neighbor_cost = None
        self._neighbor_priority = None
        self.discriminator = None

        if neighbor_cost is not None:
            self.neighbor_cost = neighbor_cost
        if neighbor_priority is not None:
            self.neighbor_priority = neighbor_priority

    @property
    def neighbor_cost(self):
        """Gets the neighbor_cost of this IOspfv3NeighborProperties.  # noqa: E501

        :return: The neighbor_cost of this IOspfv3NeighborProperties.  # noqa: E501
        :rtype: IOspfv3NeighborCost
        """
        return self._neighbor_cost

    @neighbor_cost.setter
    def neighbor_cost(self, neighbor_cost):
        """Sets the neighbor_cost of this IOspfv3NeighborProperties.

        :param neighbor_cost: The neighbor_cost of this IOspfv3NeighborProperties.  # noqa: E501
        :type: IOspfv3NeighborCost
        """

        self._neighbor_cost = neighbor_cost

    @property
    def neighbor_priority(self):
        """Gets the neighbor_priority of this IOspfv3NeighborProperties.  # noqa: E501

        :return: The neighbor_priority of this IOspfv3NeighborProperties.  # noqa: E501
        :rtype: IOspfv3NeighborPriority
        """
        return self._neighbor_priority

    @neighbor_priority.setter
    def neighbor_priority(self, neighbor_priority):
        """Sets the neighbor_priority of this IOspfv3NeighborProperties.

        :param neighbor_priority: The neighbor_priority of this IOspfv3NeighborProperties.  # noqa: E501
        :type: IOspfv3NeighborPriority
        """

        self._neighbor_priority = neighbor_priority

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(IOspfv3NeighborProperties, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, IOspfv3NeighborProperties):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

import sys
import re

out_file = sys.argv[1]

prefix = [
    '(learned[0-9]+ )+',
    'we can conclude that',
    'we have that',
    'in conclusion,',
    ]

def strip_prefix(line):
    for p in prefix:
        res = re.search(p, line)
        if res is not None:
            line = re.split(p, line)[-1].strip()
            break
    return line

def convert_relis_sentence(sentence):
    ans = None
    segs = re.search(r"the answer to the question given the context is(.*)", sentence)
    if segs is not None:
        segs = segs.groups()
        ans = segs[0].strip()
    return ans

all_lines = []
with open(out_file, "r", encoding="utf8") as fr:
    for line in fr:
        e = line.strip()
        if len(e) > 0 and e[-1] == ".":
            all_lines.append(e[:-1])
        else:
            all_lines.append(e)

hypothesis = []
cnt = 0
fail_cnt = 0

for i, line in enumerate(all_lines):
    cnt += 1
    strip_line = strip_prefix(line)
    ans = convert_relis_sentence(strip_line)
    if ans is not None:
        hypothesis.append(ans)
    else:
        hypothesis.append("failed")
        fail_cnt += 1
        print("Failed:id:{}, line:{}".format(i+1, line))

with open(f"{out_file}.extracted.txt", "w", encoding="utf8") as fw:
    for eg in hypothesis:
        print(eg, file=fw)

print(f"failed = {fail_cnt}, total = {cnt}")


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

from PyQt4.QtCore import QRectF
from PyQt4.QtGui import QApplication, QGraphicsView, QGraphicsScene

from widgets.itens import ItemMovel

app = QApplication([])
view = QGraphicsView()
scene = QGraphicsScene()
view.setScene(scene)
a = ItemMovel()
scene.addItem(a)
view.show()
a.setTamanho(QRectF(0,0,100,100))
app.exec_()


import wx
import time
import os
from PIL import Image as img
# import sys
# import string

title = 'SpreadMaster'

class SpreadFrame(wx.Frame):
    ################################
    # CONFIG
    ################################
    title = 'SpreadMaster'
    version = '1.0.2'
    description = 'Oldalpárok vágása JPG formátumú képekből...'
    author = 'Tóth József'
    email = 'tothjx@gmail.com'
    separator = '----------------------------------------------------------------'
    label_source_dir = 'Eredeti file-ok útvonala a file-rendszerben (forráskönyvtár):'
    label_target_dir = 'Vágott file-ok útvonala a file-rendszerben (célkönyvtár):'
    label_log_box = 'Elvégzett műveletek naplózása:'
    label_about = 'névjegy...'
    label_clipboard = 'napló másolása...'
    label_help = 'súgó...'
    label_close = 'bezárás...'
    label_crop = 'vágás...'.upper()
    label_version_number = 'verziószám'
    label_further_info = 'további információ'
    label_author = 'szerző'
    source_dir_default = 'C:\\out\\original\\'
    target_dir_default = 'C:\\out\\crop\\'
    msg_dir_src = 'Eredeti file-okat tartalmazó könyvtár kiválasztása...'
    msg_dir_tar = 'Vágott file-okat tartalmazó könyvtár kiválasztása...'
    msg_set_source_dir = 'Eredeti file-ok könyvtára beállítva:'
    msg_set_target_dir = 'Vágott file-ok könyvtára beállítva:'
    msg_all_images_num = 'A könyvtárban összesen %s file található...'
    msg_no_images = 'A választott forráskönyvtárban nem találhatóak file-ok. Kérem válasszon másik könyvtárat!'
    msg_target_not_empty = 'Figyelem, a kiválasztott célkönyvtár nem üres! Célszerű vágás előtt törölni a benne lévő file-okat. Ha a törlés elmarad, a program, a már létező file-okat kérdés nélkül felülírja.'
    msg_target_empty = 'A kiválasztott célkönyvtár üres, tárolásra alkalmas.'
    msg_orig_spread = 'Eredeti oldalpár'
    msg_left_saved = 'Bal oldal mentve'
    msg_right_saved = 'Jobb oldal mentve'
    msg_final_success = 'A képek vágása befejeződött, a darabolt oldalak a %s könyvtárban elérhetőek.'
    msg_clipboard_success = 'A napló tartalmának vágólapra másolása sikerült.'
    msg_clipboard_error = 'A napló tartalmának vágólapra másolása NEM sikerült.'
    log_txt_default = 'Napló indítása...\n'
    files = []
    help_text = 'A program használatához ki kell választani a forrás- és célkönyvtárakat. A forráskönyvtárban kell elhelyezni az oldalpárokat tartalmazó JPG formátumú képeket. Nagyon fontos: a program jelenleg csak ezt a formátumot támogatja.' + \
            '\n' + 'A könyvtár-választó szövegmezők mögött van egy gomb, amivel ki lehet tallózni a kívánt könyvtárakat. Ha a forráskönyvtár üres, azt a program jelzi a nagy mezőben, ahol naplóz minden műveletet (ezeket érdemes figyelemmel követni). Ha a kiválasztott célkönyvtárban vannak file-ok, arra a program a napló szövegében figyelmeztet, de a vágás elvégezhető. A már létező file-ok automatikusan felülírásra kerülnek.' + \
            '\n\n' + 'Ha a könyvtárak rendben vannak, a művelet a VÁGÁS... feliratú gombbal indítható. A sikeres futásról a naplóban lehet tájékozódni. A vágás és mentés után a vágott képek file-neve megegyezik az eredeti file-névvel, annyi kitétellel, hogy a bal oldalt tartalmazó kép neve kiegészül egy 1-essel, míg a jobb oldali egy 2-essel.' + \
            '\n\n' + 'És végül: a napló másolása gomb használata akkor lehet hasznos, ha valami hiba történik a futtatás során. A napló tartalma a vágólapra másolódik, és levélben elküldhető. Ennek segítségével tudom a hibát lokalizálni majd javítani.'

    def __init__(self, *args, **kw):
        wx.Frame.__init__(self,*args, **kw)
        if title in vars():
            self.title = title
        ################################
        # PANEL
        ################################
        self.set_dirs()
        self.set_panel()
        self.log_init()

        # Set event handlers
        # self.button.Bind(wx.EVT_BUTTON, self.OnButton)

    def set_dirs(self):
        sd = self.source_dir_default
        td = self.target_dir_default
        source_dir_exists = os.path.isdir(sd)
        target_dir_exists = os.path.isdir(td)
        if source_dir_exists == False:
            os.makedirs(sd)

        if target_dir_exists == False:
            os.makedirs(td)

    # SET PANEL
    def set_panel(self):
        self.panel = wx.Panel(self)

        ################################
        # LABELS
        ################################
        self.label_source = wx.StaticText(self.panel, label=self.label_source_dir, pos=(15, 15))
        self.label_target = wx.StaticText(self.panel, label=self.label_target_dir, pos=(15, 45))
        self.label_log_box = wx.StaticText(self.panel, label=self.label_log_box, pos=(15, 75))

        # self.txt_source = wx.TextCtrl(self.panel, value=self.source_dir, size=(250, -1), pos=(250, 10))
        # self.txt_target = wx.TextCtrl(self.panel, value=self.target_dir, size=(250, -1), pos=(250, 40))

        ################################
        # DIRECTORY PICKER CONTROLS
        ################################
        self.source_dir = wx.DirPickerCtrl(self.panel, style=wx.DIRP_USE_TEXTCTRL, path=self.source_dir_default,
            message=self.msg_dir_src, size=(400, -1), pos=(350, 10))
        self.target_dir = wx.DirPickerCtrl(self.panel, style=wx.DIRP_USE_TEXTCTRL, path=self.target_dir_default,
            message=self.msg_dir_tar, size=(400, -1), pos=(350, 40))

        ################################
        # LOG FIELD
        ################################
        init_log_msg = self.ts() + ': ' + self.log_txt_default
        self.console = wx.TextCtrl(self.panel, value = init_log_msg,
            size=(750, 390), pos=(15, 100), style= wx.TE_MULTILINE)

        ################################
        # BUTTONS
        ################################
        self.button_help = wx.Button(self.panel, label=self.label_help, size=(120, 40), pos=(15, 505))
        self.button_about = wx.Button(self.panel, label=self.label_about, size=(120, 40), pos=(150, 505))
        self.button_clipboard = wx.Button(self.panel, label=self.label_clipboard, size=(120, 40), pos=(285, 505))
        self.button_close = wx.Button(self.panel, label=self.label_close, size=(120, 40), pos=(420, 505))
        self.button_crop = wx.Button(self.panel, label=self.label_crop, size=(160, 40), pos=(605, 505))

        ################################
        # SIZER
        ################################
        self.windowSizer = wx.BoxSizer()
        self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)
        self.sizer = wx.wxEVT_SIZE
        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.border)

        ################################
        # FONT
        ################################
        self.button_crop.SetForegroundColour(wx.RED)
        cfont = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        #self.label_source.SetFont(cfont)
        #self.label_target.SetFont(cfont)
        #self.label_log_box.SetFont(cfont)
        self.button_crop.SetFont(cfont)
        self.button_about.SetFont(cfont)
        self.button_help.SetFont(cfont)
        self.button_close.SetFont(cfont)
        self.button_clipboard.SetFont(cfont)

        ################################
        # BIND
        ################################
        self.source_dir.Bind(wx.EVT_DIRPICKER_CHANGED, lambda evt: self.on_source_dir(evt))
        self.target_dir.Bind(wx.EVT_DIRPICKER_CHANGED, lambda evt: self.on_target_dir(evt))
        self.button_about.Bind(wx.EVT_BUTTON, self.on_about)
        self.button_clipboard.Bind(wx.EVT_BUTTON, self.on_clipboard)
        self.button_help.Bind(wx.EVT_BUTTON, self.on_help)
        self.button_close.Bind(wx.EVT_BUTTON, self.on_close)
        self.button_crop.Bind(wx.EVT_BUTTON, self.on_crop)

    # SIMPLE LINE FOR LOG
    def log(self, str):
        self.console.AppendText(self.ts() + ': ' + str + '\n')

    # SEPARATOR FOR LOG
    def log_separator(self):
        self.console.AppendText(self.separator + '\n')

    # TIMESTAMP FOR LOG
    def ts(self):
        return time.strftime('%Y.%m.%d %H:%M:%S')

    # LOG INIT
    def log_init(self):
        self.log_separator()
        self.on_source_dir()
        self.on_target_dir()

    # GET SOURCE DIRECTORY
    def get_source_dir(self):
        return self.get_correct_path(self.source_dir.GetPath())

    # GET TARGET DIRECTORY
    def get_target_dir(self):
        return self.get_correct_path(self.target_dir.GetPath())

    # CHANGE SOURCE DIRECTORY
    def on_source_dir(self, evt = None):
        self.files = []
        self.files = self.get_files(self.get_source_dir())
        self.log(self.msg_set_source_dir + ' ' + self.get_source_dir())
        self.log_source_dir()
        self.log_separator()

    # CHANGE TARGET DIRECTORY
    def on_target_dir(self, evt = None):
        self.log(self.msg_set_target_dir + ' ' + self.get_target_dir())
        self.log_target_dir()
        self.log_separator()

    # ABOUT BUTTON EVENT
    def on_about(self, e):
        version = self.label_version_number + ': ' + self.version
        info = self.title + \
            '\n' + self.description + \
            '\n' + self.label_author + ': ' + self.author + \
            '\n' + version + \
            '\n\n' + self.label_further_info + ': ' + self.email
        wx.MessageBox(info, self.title, wx.OK | wx.ICON_INFORMATION)

    def on_help(self, evt):
        wx.MessageBox(self.help_text, self.label_help, wx.OK | wx.ICON_INFORMATION)

    # CLIPBOARD BUTTON EVENT
    def on_clipboard(self, e):
        text = self.console.GetValue()
        clipdata = wx.TextDataObject()
        clipdata.SetText(text)
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(clipdata)
            wx.TheClipboard.Close()
            self.log(self.msg_clipboard_success)
        else:
            self.log(self.msg_clipboard_error)
        self.log_separator()

    # CLOSE BUTTON EVENT
    def on_close(self, e):
        self.Destroy()

    # CROP BUTTON EVENT
    def on_crop(self, e):
        self.files = self.get_files(self.get_source_dir())
        if len(self.files) <= 0:
           self.log(self.msg_no_images)
        else:
            for image in self.files:
                image_actual = img.open(self.get_source_dir() + image)
                self.crop_image(image_actual)

            self.log(self.msg_final_success % self.get_target_dir())
        self.log_separator()

    # GET CORRECT PATH WITH 2 BACKSLASHES IN END OF PATH
    def get_correct_path(self, cstr):
        end_of_str = cstr[-2:]
        if '\\' not in end_of_str:
            return cstr + '\\'
        else:
            return cstr

    # GET SOURCE FILENAMES
    def get_files(self, path):
        files = []
        for name in os.listdir(path):
            if os.path.isfile(os.path.join(path, name)):
                files.append(name)

        return files

    # SET FONT COLOR
    def sfc(self, err = 0):
        if err == 1:
            # ERROR -> RED
            self.console.SetForegroundColour(wx.RED)
        else:
            # NORMAL - BLACK
            self.console.SetForegroundColour(wx.BLACK)

    # LOG CAHNGE SOURCE DIR
    def log_source_dir(self):
        if len(self.files) > 0:
            self.log(self.msg_all_images_num % len(self.files))
        else:
            self.log(self.msg_no_images)

    # LOG CHANGE TARGET DIR
    def log_target_dir(self):
        target_files = self.get_files(self.get_target_dir())

        if len(target_files) > 0:
            self.log(self.msg_target_not_empty)
        else:
            self.log(self.msg_target_empty)

    # REAL CROPPING
    def crop_image(self, image):
        # LOG
        self.log(self.msg_orig_spread + ': ' + str(image.filename) + ' (' + str(image.width) + 'x' + str(image.height) + ')')

        # ATTRIBUTES
        w = image.width
        h = image.height
        w2 = abs(w / 2)
        filename = image.filename.replace(self.get_source_dir(), '')
        filename_left = filename.replace('.jpg', '_1.jpg')
        filename_right = filename.replace('.jpg', '_2.jpg')

        # crop(left, upper, right, lower)
        # NEW IMAGES
        img_left = image.crop((0, 0, w2, h))
        img_right = image.crop((w2, 0, w, h))

        # SAVING
        img_left.save(self.get_target_dir() + filename_left)
        img_right.save(self.get_target_dir() + filename_right)

        # LOG
        self.log(self.msg_left_saved + ': ' + self.get_target_dir() + filename_left + ' (' + str(img_left.width) + 'x' + str(img_left.height) + ' pixel)')
        self.log(self.msg_right_saved + ': ' + self.get_target_dir() + filename_right + ' (' + str(img_right.width) + 'x' + str(img_right.height) + ' pixel)')
        self.log_separator()

if __name__ == '__main__':
    app = wx.App(False)
    frame = SpreadFrame(None, title = title, size=(800, 600))
    frame.Show()
    app.MainLoop()


from unittest import TestCase

from greedy.dijkstra.dijkstra import IO

class TestIO(TestCase):
  def test_read_file_input1(self):
    io = IO()
    graph1 = io.read_file_input('../data/data1')
    assert len(graph1.nodes) == 4
    assert graph1.dijkstra(1)['result'][4] == 5

    graph2 = io.read_file_input('../data/data2')
    assert len(graph2.nodes) == 5
    assert graph2.dijkstra(1)['result'][5] == 8


'''
Created on October, 2018
by: Meshal
'''

import numpy as np
import tensorflow as tf
import scipy.io
from CATA import CAttAE, parameters
import argparse
import h5py

###################################################
# Load all needed data files
def load_data(sparse, data_name):
    data = {}
    if (data_name == 'a'):
        variables = scipy.io.loadmat(data_dir + "mult_nor.mat")
        data["content"] = variables['X']
    elif (data_name == 't'):
        f = h5py.File(data_dir + "mult_nor.mat",'r')
        d = f.get('X')
        d = np.array(d).T
        data["content"] = d

    if (sparse):
        for data_num in range(1,4):
            data["train_users"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-train-1-users.dat")
            data["train_items"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-train-1-items.dat")
            data["test_users"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-test-1-users.dat")
    else:
        for data_num in range(1,4):
            data["train_users"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-train-10-users.dat")
            data["train_items"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-train-10-items.dat")
            data["test_users"+str(data_num)] = load_file(data_dir+str(data_num)+"/cf-test-10-users.dat")

    return data

def load_file(path):
    arr = []
    for line in open(path):
        a = line.strip().split()
        if a[0]==0:
            l = []
        else:
            l = [int(x) for x in a[1:]]
        arr.append(l)
    return arr
###################################################
# parse boolean argument
def str2bool(a):
    if a.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif a.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')
###################################################
# Main
###################################################
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--data_name", type=str, help="Dataset name: a or t (default: a)", default='a')
parser.add_argument("-s", "--sparse", type=str2bool, help="Sparse or Dense option (default: sparse)", default=True)
parser.add_argument("-pretrain", "--pretrain", type=str2bool, help="Pretrain the attentive autoencoder? (default: No)", default=False)
parser.add_argument("-o", "--output_name", type=str, help="CATA.mat name",  default='CATA')
parser.add_argument("-e", "--epochs", type=int, help="Number of epochs to pretrain the attentive autoencoder (default: 150)", default=150)
parser.add_argument("-pe", "--pmf_epochs", type=int, help="Number of epochs for pmf (default: 100)", default=100)
parser.add_argument("-l", "--latent_size", type=int, help="Size of latent space (default: 50)", default=50)
parser.add_argument("-u", "--lambda_u", type=float, help="Value of user regularizer (default: 10)", default=10)
parser.add_argument("-v", "--lambda_v", type=float, help="Value of item regularizer (default: 0.1)", default=0.1)

args = parser.parse_args()
np.random.seed(0)
tf.set_random_seed(0)

sparse = args.sparse
data_name = args.data_name
output_name = args.output_name
pretrain = args.pretrain
pretraining_epochs = args.epochs
pmf_epochs = args.pmf_epochs
lambda_u = args.lambda_u
lambda_v = args.lambda_v
latent_size = args.latent_size

print ("=======================================")
print ("               CATA                    ")
print ("=======================================")
if (data_name == 'a'):
    num_users = 5551
    num_items = 16980
    data_dir = "data/citeulike-a/"
    print ("Dataset name: Citeulike-a    #users: 5551    #items:16980")
    print ("Sparse settings? ", sparse)
    print ("Output file name? ", output_name)
elif (data_name == 't'):
    num_users = 7947
    num_items = 25975
    data_dir = "data/citeulike-t/"
    print ("Dataset name: Citeulike-t    #users: 7947    #items:25975")
    print ("Sparse settings,p=1? ", sparse)
    print ("Output file name? ", output_name)

data = load_data(sparse, data_name)
input_size = len(data["content"][0])
print ("Input Dimension: ", input_size)
print ("pre-train? ", pretrain)
print ("pre-training epochs: ", pretraining_epochs)
print ("pmf epochs: ", pmf_epochs)
print ("lambda u: ", lambda_u, "lambda v: ", lambda_v)
print ("Size of latent space:", latent_size)
print ("---------------------------------------")

parameters(num_users, num_items, pmf_epochs, pretraining_epochs, lambda_u, lambda_v, latent_size)
CAttAE(X=data["content"], data=data, sparse=sparse, data_name=data_name, output_name=output_name, pretrain=pretrain)


class Duck:

    def quack(self):
        print('Quack, quack')

    def fly(self):
        print('Flap, Flap!')

class Person:

    def quack(self):
        print("I'm Quacking Like a Duck!")

    def fly(self):
        print("I'm Flapping my Arms!")

def quack_and_fly(thing):
    # Not Duck-Typed (Non-Pythonic)
    if isinstance(thing, Duck):
        thing.quack()
        thing.fly()
    else:
        print('This has to be a Duck!')

    # LBYL (Non-Pythonic): Look Before You Leap
    if hasattr(thing, 'quack'):  # True if either attribute or method
        if callable(thing.quack):  # True if method
            thing.quack()

    if hasattr(thing, 'fly'):
        if callable(thing.fly):
            thing.fly()

    # Pythonic: Duck Typing: If it walks like a duck and it quacks like a duck, then it must be a duck.  EAFP: Easier to ask forgiveness than permission. this concept means try to do sth if it works great! if not handle the error
        try:
            thing.quack()
            thing.fly()
            thing.bark()
        except AttributeError as e:
            print(e)

d = Duck()
quack_and_fly(d)
p = Person()
quack_and_fly(p)


n = int(input("ingrese un número para factorial:"))

y = n

z = 1

while y > 1:
    z *= y

    y -= 1

    print("valores al final ciclo de", "n:", n, "y:", y, "z:", z)

print("el resultado del factorial del numero", n, "es", z)