import io
import unittest
from fractions import Fraction

import vtab
from vtab.note import Note

class MockFormatter(object):
	def __init__(self):
		self.history = []

	def __getattr__(self, name):
		def mock(*args, **kwargs):
			if 0 == len(kwargs):
				self.history.append((name,) + args)
			else:
				self.history.append((name,) + args + (kwargs,))
		return mock

class VtabParserTest(unittest.TestCase):
	def setUp(self):
		self.parser = vtab.VtabParser()
		self.formatter = MockFormatter()
		self.parser.add_formatter(self.formatter)

		# This loop adds *all* the formatters to the parser during
		# the parser unit tests. Strictly speaking this is not within
		# the scope of unit tests but it has very little impact on the
		# behaviour of the parser but allows us (for free) to check
		# that the formatters don't react to formatting commands by
		# raising an exception.
		for fmt in (vtab.AsciiFormatter(),
			    vtab.DummyFormatter(),
			    vtab.LilypondFormatter()):
			sio = io.StringIO()
			fmt.set_file(sio)
			self.parser.add_formatter(fmt)

		self.assertEqual(len(self.formatter.history), 0)
		self.history_counter = 0

	def tearDown(self):
		# Check for unexpected history
		self.assertEqual(len(self.formatter.history), self.history_counter)

		# Check that no state is held by the parser at the end of the test
		self.parser.flush()
		self.assertEqual(len(self.formatter.history), self.history_counter)

	def parse(self, s):
		for ln in s.split('\n'):
			self.parser.parse(ln)
		self.parser.flush()

	def expectHistory(self, t):
		self.assertTupleEqual(self.formatter.history[self.history_counter], t)
		self.history_counter += 1

	def expectBarline(self, barline_type='-'):
		expected_barline = None

		if barline_type == '-':
			expected_barline = {}
		elif barline_type == '=':
			expected_barline = { 'double': 'plain' }
		elif barline_type == ':-':
			expected_barline = { 'repeat': 'close' }
		elif barline_type == '-:':
			expected_barline = { 'repeat': 'open' }
		elif barline_type == ':-:':
			expected_barline = { 'repeat': 'both' }
		elif barline_type == ':=':
			expected_barline = { 'double': 'plain', 'repeat': 'close' }
		elif barline_type == '=:':
			expected_barline = { 'double': 'plain', 'repeat': 'open' }
		elif barline_type == ':=:':
			expected_barline = { 'double': 'plain', 'repeat': 'both' }

		assert(None != expected_barline)

		self.expectHistory(('format_barline', expected_barline))

	def expectNote(self, template, duration=Fraction(1,4), tie=False):
		def parse_note(note):
			try:
				return Note(note)
			except:
				return None
		notes = [parse_note(note) for note in template.split()]
		self.expectHistory(('format_note', tuple(notes), duration, tie))

	def testComment(self):
		comment = '# This is a comment'
		self.parse(comment)
		self.expectHistory(('format_attribute', 'comment', comment[2:]))

	def testError(self):
		self.parse("""
		===========
		| | | | | 0
		This is gibber
		| | | | | 0
		""")

		self.expectBarline('=')
		# TODO: The comment appearing before the note is a consequence of the
		#       note length detection. The comment really ought to be delayed until after
		#       the note stops.
		self.expectHistory(('format_attribute', 'error', "Cannot parse '\t\tThis is gibber' at line 4"))
		self.expectNote('X  X  X  X  X  E4')
		self.expectNote('X  X  X  X  X  E4')

	def testUnderlinedTitle(self):
		"""Check that a title line is not prematurely issued to the formatter.

		A title can be demarked by its underlining. Therefore is cannot be
		issued to the formatter until the next line has been parsed.

		Note: This implies that we cannot use the self.parse() helper function.
		"""
		title = 'This is a title'
		self.parser.parse(title)
		self.assertEqual(len(self.formatter.history), 0)

		self.parser.parse('========')
		self.expectHistory(('format_attribute', 'title', title))

	def testKeyPairTitle(self):
		title = 'This is a title'
		self.parse('title: ' + title)
		self.expectHistory(('format_attribute', 'title', title))

	def testKeyPairCaseNormalization(self):
		title = 'This is a title'
		self.parse('Title: ' + title)
		self.expectHistory(('format_attribute', 'title', title))

		self.parser.parse('TITLE: ' + title)
		self.expectHistory(('format_attribute', 'title', title))

	def testKeyPairWithoutWhitespace(self):
		title = 'This is a title'
		self.parse('title:' + title)
		self.expectHistory(('format_attribute', 'title', title))

	def testKeyPairWithExcessiveWhitespace(self):
		title = 'This is a title'
		self.parse('\ttitle  : \t ' + title)
		self.expectHistory(('format_attribute', 'title', title))

	def testSingleBarLine(self):
		self.parse('--------')
		self.expectBarline('-')

	def testDoubleBarLine(self):
		self.parse('========')
		self.expectBarline('=')

	def testDoubleRepeatBarLine(self):
		self.parse("""
		========:
		| | 0 | | | 1
		--------
		| | 0 | | |
		:=======
		""")

		self.expectBarline('=:')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,1)))
		self.expectNote(' X  X D3  X  X  X', Fraction(1,1))
		self.expectBarline('-')
		self.expectNote(' X  X D3  X  X  X', Fraction(1,1))
		self.expectBarline(':=')

	def testNoteBarLineInteraction(self):
		self.parse("""
		===========
		| | 0 | | |  2
		| | 0 | | |
		-----------
		| | 0 | | |
		| | 0 | | |
		===========
		""")

		self.expectBarline('=')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,2)))
		self.expectNote(' X  X D3  X  X  X', Fraction(1,2))
		self.expectNote(' X  X D3  X  X  X', Fraction(1,2))
		self.expectBarline('-')
		self.expectNote(' X  X D3  X  X  X', Fraction(1,2))
		self.expectNote(' X  X D3  X  X  X', Fraction(1,2))
		self.expectBarline('=')

	def testDecoratedBarLine(self):
		self.parse('-------- 8 "Some-"')
		self.expectHistory(('format_attribute', 'duration', Fraction(1, 8)))
		self.expectHistory(('format_attribute', 'lyric', 'Some-'))
		self.expectBarline('-')

	def testRepeatOpen(self):
		self.parse('--------:')
		self.expectBarline('-:')

	def testRepeatClose(self):
		self.parse(':-------')
		self.expectBarline(':-')

	def testRepeatCloseOpen(self):
		self.parse(':------:')
		self.expectBarline(':-:')

	def testOpenStrings(self):
		self.parse('0 | | | | |')
		self.expectNote('E2  X  X  X  X  X')

		self.parse('| 0 | | | |')
		self.expectNote(' X A2  X  X  X  X')

		self.parse('| | 0 | | |')
		self.expectNote(' X  X D3  X  X  X')

		self.parse('| | | 0 | |')
		self.expectNote(' X  X  X G3  X  X')

		self.parse('| | | | 0 |')
		self.expectNote(' X  X  X  X B3  X')

		self.parse('| | | | | 0')
		self.expectNote(' X  X  X  X  X E4')

	def testBigChords(self):
		self.parse(' 3  2  0  0  0  3')
		self.expectNote(  'G2 B2 D3 G3 B3 G4')

		self.parse(' |  3  2  0  1  0')
		self.expectNote(  ' X C3 E3 G3 C4 E4')

		self.parse('12 14 14 13  12 12')
		self.expectNote(  'E3 B3 E4 G#4 B4 E5')

	def testDecoratedNotes(self):
		self.parse('|  | 14 |  |  |  8')
		self.expectHistory(('format_attribute', 'duration', Fraction(1, 8)))
		self.expectNote (' X  X E4 X  X  X', Fraction(1, 8))

	def testNoteDurationMinim(self):
		self.parse("""
		-------------
		 | 3 | | | |  2
		 | 3 | | | |  4
		 | | | | | |
		-------------
		 | 3 | | | |  8
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | 3 | | | |  16
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		-------------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,2)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,4)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,8)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,16)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))

		self.expectBarline('-')

	def testNoteDurationCrotchet(self):
		self.parse("""
		-------------)
		 | 3 | | | |  4
		 | 3 | | | |  8
		 | | | | | |
		 | 3 | | | |  16
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | 3 | | | |  32
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		-------------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,4)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,4))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,8)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,4))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,16)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,4))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,32)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,4))
		self.expectBarline('-')

	def testNoteDurationDottedCrotchet(self):
		self.parse("""
		-------------
		 | 3 | | | |   8
		 | | | | | |
		 | | | | | |
		 | 3 | | | |  16
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | 3 | | | |   4
		-------------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,8)))
		self.expectNote(' X C3  X  X  X  X', Fraction(3,8))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,16)))
		self.expectNote(' X C3  X  X  X  X', Fraction(3,8))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,4)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,4))
		self.expectBarline('-')

	def testNoteDurationQuaver(self):
		self.parse("""
		 | 3 | | | |   8
		 | 3 | | | |  16
		 | | | | | |
		 | 3 | | | |  32
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | 3 | | | |  64
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		 | | | | | |
		""")

		self.expectHistory(('format_attribute', 'duration', Fraction(1,8)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,8))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,16)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,8))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,32)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,8))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,64)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,8))

	def testNotesAndRests(self):
		self.parse("""
			| | | 2 1 1  16
			| | | : : :
			| | | 2 1 1
			| | | : : :
			| | | | | |
			| | | | | |
			| | | 2 1 1
			| | | | | |
			| | | | | |
			| | | : : :
			| | | | | |
			| | | | | |
			| | | 2 1 1
			| | | | | |
			| | | : : :
			| | | | | |
		""")

		self.expectHistory(('format_attribute', 'duration', Fraction(1,16)))
		self.expectNote(' X  X  X A3 C4 F4', Fraction(1,16))
		self.expectNote(' X  X  X  X  X  X', Fraction(1,16))
		self.expectNote(' X  X  X A3 C4 F4', Fraction(1,16))
		self.expectNote(' X  X  X  X  X  X', Fraction(3,16))
		self.expectNote(' X  X  X A3 C4 F4', Fraction(3,16))
		self.expectNote(' X  X  X  X  X  X', Fraction(3,16))
		self.expectNote(' X  X  X A3 C4 F4', Fraction(2,16))
		self.expectNote(' X  X  X  X  X  X', Fraction(2,16))

	def testRestAtStartOfLine(self):
		self.parse("""
			-----------
			| | | | | |  2
			3 | 0 0 0 3
			-----------
			3 | 0 0 0 3
			3 | 0 0 0 3
			-----------
		""")

		self.expectBarline('-')

		self.expectHistory(('format_attribute', 'duration', Fraction(1,2)))
		self.expectNote(' X  X  X  X  X  X', Fraction(1, 2))
		self.expectNote('G2  X D3 G3 B3 G4', Fraction(1, 2))

		self.expectBarline('-')

		self.expectNote('G2  X D3 G3 B3 G4', Fraction(1, 2))
		self.expectNote('G2  X D3 G3 B3 G4', Fraction(1, 2))

		self.expectBarline('-')

	def testNoteCarriedOverBarline(self):
		self.parse("""
		 -----------
		 | 3 | | | |  2
		 | | | 0 1 0
		 -----------
		 | | | | | |
		 | | | 0 1 0
		 -----------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,2)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))
		self.expectNote(' X  X  X G3 C4 E4', Fraction(1,2))
		self.expectBarline('-')
		self.expectNote(' X  X  X G3 C4 E4', Fraction(1,2), True)
		self.expectNote(' X  X  X G3 C4 E4', Fraction(1,2))
		self.expectBarline('-')

	def testNoteStoppedAtBarline(self):
		self.parse("""
		 -----------
		 | 3 | | | |  2
		 | | | 0 1 0
		 -----------
		 | | | : : :
		 | | | 0 1 0
		 -----------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,2)))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,2))
		self.expectNote(' X  X  X G3 C4 E4', Fraction(1,2))
		self.expectBarline('-')
		self.expectNote(' X  X  X  X  X  X', Fraction(1,2), False) # No tie
		self.expectNote(' X  X  X G3 C4 E4', Fraction(1,2))
		self.expectBarline('-')

	def testOverText(self):
		self.parse("""
		 -----------
		 | 3 | | | |  t:C
		 | | | 0 1 0
		 | | 2 | | |
		 | | | 0 1 0
		 -----------
		 3 | | | | |  text:G
		 | | | 0 0 3
		 | | 0 | | |
		 | | | 0 0 3
		 -----------
		 1 | | | | |  text:(F)
		 1 | | | | |  "text:Two words"
		 1 | | | | |  text:"Different quoting"
		 0 | | | | |  text:'Em'
		 -----------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'text', 'C'))
		self.expectNote(' X C3  X  X  X  X')
		self.expectNote(' X  X  X G3 C4 E4')
		self.expectNote(' X  X E3  X  X  X')
		self.expectNote(' X  X  X G3 C4 E4')
		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'text', 'G'))
		self.expectNote('G2  X  X  X  X  X')
		self.expectNote(' X  X  X G3 B3 G4')
		self.expectNote(' X  X D3  X  X  X')
		self.expectNote(' X  X  X G3 B3 G4')
		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'text', '(F)'))
		self.expectNote('F2  X  X  X  X  X')
		self.expectHistory(('format_attribute', 'text', 'Two words'))
		self.expectNote('F2  X  X  X  X  X')
		self.expectHistory(('format_attribute', 'text', 'Different quoting'))
		self.expectNote('F2  X  X  X  X  X')
		self.expectHistory(('format_attribute', 'text', 'Em'))
		self.expectNote('E2  X  X  X  X  X')
		self.expectBarline('-')

	def testHammerOn(self):
		self.parse("""
		 ----------------
		 |  0  |  |  |  |  4
		 | h2  |  |  |  |
		 |  0  |  |  |  |  8
		 | h2  |  |  |  |
		 | h3  |  |  |  |
		 |  0  |  |  |  |
		 ----------------
		""")

		self.expectBarline('-')
		self.expectHistory(('format_attribute', 'duration', Fraction(1,4)))
		self.expectNote(' X A2  X  X  X  X', Fraction(1,4))
		self.expectNote(' X B2  X  X  X  X', Fraction(1,4))
		self.expectHistory(('format_attribute', 'duration', Fraction(1,8)))
		self.expectNote(' X A2  X  X  X  X', Fraction(1,8))
		self.expectNote(' X B2  X  X  X  X', Fraction(1,8))
		self.expectNote(' X C3  X  X  X  X', Fraction(1,8))
		self.expectNote(' X A2  X  X  X  X', Fraction(1,8))
		self.expectBarline('-')

if __name__ == "__main__":
	#import sys;sys.argv = ['', 'Test.testName']
	unittest.main()


import pygame

def game_loop():
    import Mainshmp

pygame.init()

display_width = 1000
display_height = 600

HW,HH = display_width / 2, display_height / 2
AREA = display_width * display_height

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

player_width = 50
player_heigth = 50

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("MyPy")
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)
clock = pygame.time.Clock()
pygame.font.init()

joysticks = []
for i in range(0, pygame.joystick.get_count()):
    joysticks.append(pygame.joystick.Joystick(i))
    joysticks[-1].init()

pygame.mixer.music.load("random silly chip song.wav")
pygame.mixer.music.play(-1)

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load("back.png")
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location
bg = Background('background_image.png', [0,0])
kenny = pygame.image.load("kenny.png")

button1 = pygame.image.load("button1.png")
button2 = pygame.image.load("button2.png")
quit1 = pygame.image.load("quit1.png")
quit2 = pygame.image.load("quit2.png")

def text_objects(text, font):
    textSurface = font.render(text, True, red)
    return textSurface, textSurface.get_rect()

def button(x,y,w,h, b1, b2, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    gameDisplay.blit(b2,(x,y))
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        if click[0] == 1 and action != None:
            if action == "play":
                game_loop()
            elif action == "quit":
                pygame.quit()

        gameDisplay.blit(b1,(x,y))

def game_intro():
    intro = True

    while intro:

        for event in pygame.event.get():
            print(event)

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type ==pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

            if event.type ==pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    game_loop()

            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 9:
                    game_loop()

            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 8:
                    pygame.quit()
                    quit()

            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 6:
                    pygame.quit()
                    quit()

            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 7:
                    game_loop()

        gameDisplay.blit(bg.image, bg.rect)

        gameDisplay.blit(kenny,(425, 300))

        largeText = pygame.font.Font('SnackerComic.ttf',115)
        TextSurf, TextRect = text_objects("MyPy", largeText)
        TextRect.center = ((display_width/2),(display_height/3))
        gameDisplay.blit(TextSurf, TextRect)

        button(200,500,100,39,button1,button2, "play")
        button(700,500,100,39,quit1,quit2, "quit")

        pygame.display.update()
        clock.tick(15)

game_intro()
pygame.quit()
quit


# Ejercicio 1 Proyecto
# Enrique Lopez Serrano
# Importar y definir la fecha y hora.
from datetime import datetime
from datetime import date
import os
import sys

# Definir variables de fecha y hora.
fecha = datetime.now().strftime('%d-%m-%Y')
hora = datetime.now().strftime('%H:%M')

# Bloque principal
temperaturas = []
while True:
    temperatura = int(input("Introduce la temperatura: "))
    if temperatura != 100:
        temperaturas.append(temperatura)
    if temperatura == 100:
        break;

# Bucle
print("Informe de temperaturas del Parque Natural de Doñana: ")
print("-----------------------------------------------------")
print("Fecha:" ,fecha)
print("Hora:" ,hora)
print("Numero de muestras: %d" % len(temperaturas))
print("Temperaturas tomadas:" ,temperaturas)
print("Temperatura maxima:" ,max(temperaturas))
print("Temperatura minima:" ,min(temperaturas))
print("Temperatura media:" ,round(sum(temperaturas)/len(temperaturas),2))
temp_tupla = (fecha,hora,temperaturas)
lista = list(temp_tupla)
file = open("temperaturasELS.txt", "a")
file.write('temperaturas = %s' % lista + '\n')
file.close()


from app import db

class Car(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    brand = db.Column(db.String(100))
    model = db.Column(db.String(100))
    price = db.Column(db.Float)
    description = db.Column(db.String(1000))
    available = db.Column(db.Boolean, default=True)
    picture_url = db.Column(db.String(250))
    ratings = db.relationship('Rating', backref='car', lazy='dynamic')

    def __init__(self, brand, model, price, description=None, picture_url='/static/img/default.jpg', available=True):
        self.brand = brand
        self.model = model
        self.price = price
        self.description = description
        self.available = available
        self.picture_url = picture_url

    def __repr__(self):
        return '<Car %s - %s>' % (self.brand, self.model)

class Rating(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    rating = db.Column(db.Integer)
    car_id = db.Column(db.Integer, db.ForeignKey('car.id'))

    def __init__(self, name, car, rating):
        self.name = name
        self.car_id = car
        self.rating = rating

    def __repr__(self):
        return '<Rating %s: %d>' % (self.name, self.rating)

    @property
    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'car_id': self.car_id,
            'rating': self.rating
        }


from typing import List

class Solution(object):

    def __init__(self):
        print('Start 3Sum')

    def threeSum(self, nums: List[int]) -> List[List[int]]:
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        result = []
        size = len(nums)
        # f is fix point
        for f in range(size):
            if f == 0 or nums[f] != nums[f-1]:
                p1, p2 = f + 1, size - 1
                target = 0 - nums[f]
                while p1 < p2:
                    other = nums[p1] + nums[p2]
                    if target == other:
                        result.append([nums[f], nums[p1], nums[p2]])
                        while p1 < p2 and nums[p1] == nums[p1+1]:
                            p1 += 1
                        while p1 < p2 and nums[p2] == nums[p2-1]:
                            p2 -= 1
                        p1 += 1
                        p2 -= 1
                    elif target < other:
                        p2 -= 1
                    else:
                        p1 += 1
        return result

if __name__ == '__main__':

    nums = [-1,0,1,2,-1,-4]
    nums = [0,0,0]

    solution = Solution()
    print(solution.threeSum(nums))

    # O(N^2)


# ðŸš€ ExercÃcio 1 - Facebook
# VocÃª receberÃ¡ uma lista de palavras e uma string. Escreva uma
# funÃ§Ã£o que decida quais palavras podem ser formadas com os caracteres
# da string (cada caractere sÃ³ pode ser utilizado uma vez). Retorne a soma
# do comprimento das palavras escolhidas.

# words = ["cat", "bt", "hat", "tree"], chars = "atach"
# # saÃda: 6
# """ExplicaÃ§Ã£o: As palavras que podem ser formadas com os caracteres
# da string sÃ£o "cat" (tamanho 3) e "hat" (tamanho 3)."""

# words = ["hello", "world", "students"], chars = "welldonehoneyr"
# # saÃda: 10
# """ExplicaÃ§Ã£o: As palavras que podem ser formadas com os caracteres
# da string sÃ£o "hello" (tamanho 5) e "world" (tamanho 5)."""

# Complexidade O(n^2)
def match_words(words, chars):
    char_catalog = {char: True for char in chars}
    compatible_words = []

    for word in words:
        length = len(word)
        match_letters = 0
        for letter in word:
            if letter in char_catalog:
                match_letters += 1
        if length == (match_letters):
            compatible_words.append(length)

    return sum(compatible_words)


import cv2

url = 'http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear2/prog_index.m3u8'
cap = cv2.VideoCapture(url)
while cap.isOpened():
    success, frame = cap.read()
    if not success:
        break
    cv2.namedWindow('a', 0)
    cv2.resizeWindow('a', 640, 360)
    cv2.imshow('a', frame)
    if cv2.waitKey(1) in [ord('q'), 27]:
        break


import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
from plotly.subplots import make_subplots

from exchange_tools import OrderBook, ExchangeConnector

st.title("Coin forecast")

@st.cache_data
def display_order_book(symbol, _api, pump_volume):

    st.write(f'Coin Market: {symbol}', unsafe_allow_html=True)
    order_book = OrderBook(symbol, _api)
    full_asks = order_book.to_df('asks')
    full_asks = full_asks[full_asks.price < int(factor[1]) * order_book.last_price]

    fig2 = make_subplots(specs=[[{"secondary_y": True}]])
    fig2.add_trace(go.Scatter(x=full_asks.index, y=full_asks.factor, name='factor'), secondary_y=True)
    fig2.add_trace(go.Scatter(x=full_asks.index, y=full_asks.csum_base_volume, name='base volume'),
                   secondary_y=False)
    fig2.add_vline(x=full_asks[full_asks.base_volume.cumsum() < pump_volume[1]].index.max(), line_color='red')
    fig2.add_vline(x=full_asks[full_asks.base_volume.cumsum() < pump_volume[0]].index.max(), line_color='green')
    fig2.update_yaxes(
        title_text=f"Base volume {symbol}",
        secondary_y=False)
    fig2.update_yaxes(
        title_text="Factor",
        secondary_y=True)
    fig2.update_xaxes(title_text='index')
    st.plotly_chart(fig2)

    st.markdown("---")

connector = ExchangeConnector('kucoin', st.secrets.BASE_CURRENCY)
conn = st.connection("postgresql", type="sql")

available_days = conn.query("""select date(timestamp) as "collection day"
from ranked_orders.orders
group by date(timestamp);""")['collection day'].tolist()

current_day = st.sidebar.selectbox(label='Select collection day', options=available_days)

factor = st.sidebar.slider(label='Factor range: ', min_value=1, max_value=10, value=(2, 5))
volume = st.sidebar.slider(label='Volume range: ', min_value=10000, max_value=600000, value=(100000, 200000))
# Perform query.
df = conn.query(f"""
select symbol                as "Symbol",
       max(csum_base_volume) as "Cumulated Base Volume",
       max(volume_ranking)   as "Volume Ranking",
       max(factor)           as "Factor",
       max(price)            as "Price"
from ranked_orders.orders
where factor between {factor[0]} and {factor[1]}
and csum_base_volume between {volume[0]} and  {volume[1]}
and date(timestamp) = date('{current_day}')
group by symbol;
""", ttl=0)

st.text(f"On {current_day} there where {len(df)} markets of interest:")
st.dataframe(df.set_index('Symbol'), use_container_width=True)

if st.sidebar.checkbox("Show graphs "):
    for coin in df['Symbol'].tolist():
        display_order_book(coin, connector.connect(), volume)


import sys

# read command line arguments
arguments = sys.argv[1:]

flag = None
path = None

for arg in arguments:
    if arg.startswith('-'):
        flag = arg
    else:
        path = arg

if flag == '-a':
    print("You chose to add")
elif flag == '-b':
    print("You chose to delete")
elif flag == '-ab':
    print("You can't do both at same time!")
else:
    print("Invalid flag")

print("Your specified flag and path is:")
print("Flag: ", flag)
print("Path: ", path)


from iroha import IrohaCrypto
from iroha_tui.proto.helpers import add_spaces, capitalize_snake_case
from iroha_tui.proto.message import ProtoMessageProxy

class QueryViewer:
    def __init__(self, query):
        self._query = query
        self._data = self._precalc_data()

    @property
    def data(self):
        return self._data

    def _precalc_data(self):
        return {
            "creator": self._query.payload.meta.creator_account_id,
            "type": self._get_type(),
            "payload": self._get_payload(),
            "signature": self._get_signature_status()
        }

    def _get_type_field(self):
        return self._query.payload.WhichOneof("query")

    def _get_type(self):
        snake = self._get_type_field()
        capitalized = capitalize_snake_case(snake)
        return add_spaces(capitalized)

    def _get_payload(self):
        type_ = self._get_type_field()
        type_proxy = ProtoMessageProxy(getattr(self._query.payload, type_))
        payload_parts = []
        for field in type_proxy.descriptor:
            name = field["name"]
            path = field["field_path"]
            value = type_proxy.read(path)
            payload_parts.append(f"{name}={value}")
        return " ".join(payload_parts)

    def _get_signature_status(self):
        if not self._query.signature.signature:
            return " "
        if IrohaCrypto.is_signature_valid(self._query, self._query.signature):
            return "+"
        else:
            return "-"


T= int(input())
for tc in range(T):
    N = int(input())
    dp = [0] * 11
    dp[1] = 1
    dp[2] = 2
    dp[3] = 4
    # 여기까지는 값 직접 넣어줘야 함.
    # i번째의 개수 구하기
    for i in range(4,11):
        dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
    print(dp[N])


import numpy as np
from copy import deepcopy
import pandas as pd

def check_streams_number(df_streams_in, df_streams_out, above_pinch, delta_T_min, reach_pinch,check_time):
    """Check stream number rule

    This function aims to check one of the pinch analysis rule, which is that the number of streams_in <= streams_out.
    If this does not occur, multiple combinations and stream splits will be made to ensure that the number of
    streams_in and streams_out is equal.

    It was implemented the parameter reach_pinch, that is used at a first instance as reach_pinch=True to ensure that
    when all_first_match_pinch_combinations runs, all streams_in can be matched. At a second instance with
    reach_pinch=False, after all the first matches have been done.

    The function check_streams_number acts as main which runs split_streams as many time as the existent surplus number
    of streams in.

    Parameters
    ----------
    df_streams_in : df
        DF with streams going into the pinch

    df_streams_out : df
        DF with streams going out of the pinch

    above_pinch : boolean
        If above (TRUE) or below (FALSE) pinch analysis

    delta_T_min : float
        Minimum temperature difference [ºC]

    reach_pinch : boolean
        Whether streams reaches pinch temperature

    check_time : float
        Multiplier. To identify in which routine there is a stream split

    Returns
    -------
    all_combinations : list
        All combinations with [df_streams_in, df_streams_out] updated

    """
    ############################################################################################
    # Get info

    df_streams_in_copy = df_streams_in.copy()
    df_streams_out_copy = df_streams_out.copy()
    original_df_streams_in = deepcopy(df_streams_in)
    original_df_streams_out = deepcopy(df_streams_out)

    # create temporary key
    df_streams_in_copy['Split_Check'] = df_streams_in_copy['Split'].copy()
    df_streams_out_copy['Split_Check'] = df_streams_out_copy['Split'].copy()

    # get streams match info
    df_streams_in_copy_match_info = deepcopy(df_streams_in_copy['Match'])
    df_streams_out_copy_match_info = deepcopy(df_streams_out_copy['Match'])

    if reach_pinch == True:
        # change streams_in match meaning - check if complete match done - sometimes values are different by millesime
        df_streams_in_copy['Match'] = df_streams_in_copy.apply(
            lambda x: x['Match'] == True if x['Supply_Temperature'] == round(x['Closest_Pinch_Temperature']) else False,
            axis=1)
        df_streams_out_copy['Match'] = df_streams_out_copy.apply(
            lambda x: x['Match'] == True if x['Target_Temperature'] == round(x['Closest_Pinch_Temperature']) else False,
            axis=1)

    else:
        # change streams_in match meaning - check if complete match done - sometimes values are different by millesime
        df_streams_in_copy['Match'] = df_streams_in_copy.apply(
            lambda x: x['Match'] == True if x['Supply_Temperature'] == round(x['Closest_Pinch_Temperature']) else False,
            axis=1)
        df_streams_out_copy['Match'] = df_streams_out_copy.apply(
            lambda x: x['Match'] == True if x['Target_Temperature'] == round(x['Closest_Pinch_Temperature']) else False,
            axis=1)

    ############################################################################################
    # Get combinations

    # check if streams split is needed
    number_streams_out = df_streams_out_copy[
        df_streams_out_copy['Target_Temperature'] != round(df_streams_out_copy['Closest_Pinch_Temperature'], 1)].shape[0]
    number_streams_in = df_streams_in_copy[
        df_streams_in_copy['Supply_Temperature'] != round(df_streams_in_copy['Closest_Pinch_Temperature'], 1)].shape[0]

    all_combinations = [[df_streams_in_copy, df_streams_out_copy]]

    if number_streams_out < number_streams_in:
        if reach_pinch == True:
            surplus_streams_in = df_streams_in_copy[(df_streams_in_copy['Reach_Pinch'] == True) & (df_streams_in_copy['Match'] == False)].shape[0] - df_streams_out_copy[(df_streams_out_copy['Reach_Pinch'] == True) & (df_streams_out_copy['Match'] == False)].shape[0]
        else:
            surplus_streams_in = number_streams_in - number_streams_out

        # create all possibilities of stream splitting with a recursive function
        cycles = [0] * surplus_streams_in
        for cycle in cycles:
            all_combinations = split_streams(all_combinations, above_pinch, delta_T_min,check_time)

        # data treatment
        for dfs in all_combinations:
            df_streams_in_copy, df_streams_out_copy = dfs
            df_streams_out_copy['Match'] = df_streams_out_copy_match_info
            df_streams_out_copy.fillna(False, inplace=True)
            df_streams_in_copy['Match'] = df_streams_in_copy_match_info
            df_streams_in_copy.fillna(False, inplace=True)

    # delete temporary columns
    for combination in all_combinations:
        combination[0].drop(columns=['Split_Check'], inplace=True)
        combination[1].drop(columns=['Split_Check'], inplace=True)

    ############################################################################################
    # OUTPUT
    # eliminate repeated combinations
    if len(all_combinations) > 1:
        keep = [all_combinations[0]]
        for dfs_combination in all_combinations:
            append = True

            # get df streams out to compare with remaining
            dfs_combination_streams_out = dfs_combination[1].copy()
            dfs_combination_streams_out = dfs_combination_streams_out.sort_values('mcp')
            dfs_combination_streams_out.index = np.arange(1, len(dfs_combination_streams_out) + 1)

            # get df streams out to compare
            for dfs_keep in keep:
                dfs_keep_streams_out = dfs_keep[1].copy()
                dfs_keep_streams_out = dfs_keep_streams_out.sort_values('mcp')
                dfs_keep_streams_out.index = np.arange(1, len(dfs_keep_streams_out) + 1)

                if dfs_combination_streams_out['mcp'].equals(dfs_keep_streams_out['mcp']) != True and append == True:
                    append = True
                else:
                    append = False

            if append == True:
                keep.append(dfs_combination)

        all_combinations = keep
        all_combinations.append([original_df_streams_in, original_df_streams_out])

    elif len(all_combinations) == 1:
        for combination in all_combinations:
            df_streams_in, df_streams_out = combination
            df_streams_out['Match'] = df_streams_out_copy_match_info
            df_streams_in['Match'] = df_streams_in_copy_match_info

    else:
        all_combinations = [[original_df_streams_in, original_df_streams_out]]

    return all_combinations

def split_streams(combinations, above_pinch, delta_T_min, check_time):

    # init arrays
    combinations_updated = []

    # get combinations
    for combination in combinations:
        pairs = []
        df_streams_in, df_streams_out = combination

        # get first pair combinations between the streams to increase pinch analysis variability
        for index_stream_out in df_streams_out.index.values:
            for index_stream_in in df_streams_in.index.values:
                # get streams
                stream_out = df_streams_out.loc[index_stream_out]
                stream_in = df_streams_in.loc[index_stream_in]

                # only streams not yet split
                if stream_out['Split_Check'] == False and stream_in['Split_Check'] == False:

                    # only streams not yet matched
                    if stream_out['Match'] == False and stream_in['Match'] == False:

                        # only relevant to look for streams_out with larger mcp than streams_in
                        if stream_out['mcp'] > stream_in['mcp']:

                            # only relevant to look for streams_out whose temperature can meet streams_in temperature range
                            if (stream_out['Closest_Pinch_Temperature'] + delta_T_min < stream_in[
                                'Supply_Temperature'] and above_pinch is True) or (
                                    stream_out['Closest_Pinch_Temperature'] - delta_T_min > stream_in[
                                'Supply_Temperature'] and above_pinch is False):

                                if (stream_out['Closest_Pinch_Temperature'] + delta_T_min <= stream_in[
                                    'Closest_Pinch_Temperature'] and above_pinch is True) or (
                                        stream_out['Closest_Pinch_Temperature'] - delta_T_min >= stream_in[
                                    'Closest_Pinch_Temperature'] and above_pinch is False):
                                    pairs += [[index_stream_out, index_stream_in]]

        # match between pairs
        if pairs != []:
            for pair in pairs:
                # get dfs
                df_streams_in_copy = df_streams_in.copy()
                df_streams_out_copy = df_streams_out.copy()

                # get streams
                index_stream_out, index_stream_in = pair
                stream_in = df_streams_in_copy.loc[index_stream_in]
                stream_out = df_streams_out_copy.loc[index_stream_out]

                ###################################################################################
                # perform streams_in split
                if above_pinch == True:
                    # get streams info
                    hx_cold_stream_T_cold = stream_out['Closest_Pinch_Temperature']
                    cold_stream_max_T_hot = stream_out['Target_Temperature']
                    hot_stream_max_T_hot = stream_in['Supply_Temperature']
                    hx_hot_stream_T_cold = stream_in['Closest_Pinch_Temperature']
                    hot_stream_mcp = stream_in['mcp']

                    # compute/check temperatures
                    if hot_stream_max_T_hot >= (cold_stream_max_T_hot + delta_T_min):
                        hx_cold_stream_T_hot = cold_stream_max_T_hot
                    else:
                        hx_cold_stream_T_hot = hot_stream_max_T_hot - delta_T_min

                    hx_hot_stream_T_hot = hot_stream_max_T_hot
                    hx_power = hot_stream_mcp * (hx_hot_stream_T_hot - hx_hot_stream_T_cold)

                    # create split stream
                    split_stream_mcp = hx_power / (hx_cold_stream_T_hot - hx_cold_stream_T_cold)
                    new_row = stream_out.copy()  # split stream has same info as original

                    # if split stream larger than stream mcp, find new hx_power
                    if new_row['mcp'] - split_stream_mcp < 0:
                        hx_hot_stream_T_hot = cold_stream_max_T_hot + delta_T_min
                        hx_power = hot_stream_mcp * (hx_hot_stream_T_hot - hx_hot_stream_T_cold)
                        split_stream_mcp = hx_power / (hx_cold_stream_T_hot - hx_cold_stream_T_cold)

                else:
                    # get streams info
                    hx_hot_stream_T_hot = stream_out['Supply_Temperature']
                    hot_stream_min_T_cold = stream_out['Target_Temperature']
                    cold_stream_mcp = stream_in['mcp']
                    cold_stream_min_T_cold = stream_in['Supply_Temperature']
                    hx_cold_stream_T_hot = stream_in['Closest_Pinch_Temperature']

                    # compute/check temperatures
                    if cold_stream_min_T_cold <= (hot_stream_min_T_cold - delta_T_min):
                        hx_hot_stream_T_cold = hot_stream_min_T_cold
                    else:
                        hx_hot_stream_T_cold = cold_stream_min_T_cold + delta_T_min

                    hx_cold_stream_T_cold = cold_stream_min_T_cold
                    hx_power = cold_stream_mcp * (hx_cold_stream_T_hot - hx_cold_stream_T_cold)

                    # create split stream
                    split_stream_mcp = hx_power / (hx_hot_stream_T_hot - hx_hot_stream_T_cold)
                    new_row = stream_out.copy()  # split stream has same info as original

                    # if split stream larger than stream mcp, find new hx_power
                    if new_row['mcp'] - split_stream_mcp < 0:
                        hx_cold_stream_T_cold = hot_stream_min_T_cold - delta_T_min
                        hx_power = cold_stream_mcp * (hx_cold_stream_T_hot - hx_cold_stream_T_cold)
                        split_stream_mcp = hx_power / (hx_hot_stream_T_hot - hx_hot_stream_T_cold)

                # new row data
                new_row['mcp'] -= split_stream_mcp  # correct split mcp
                new_row['mcp'] = round(new_row['mcp'] + .0, 5)
                new_row.name = int(index_stream_out) * 10210 * check_time  # new ID
                new_row['Split_Check'] = False

                # add split stream to df
                df_streams_out_copy = pd.concat([df_streams_out_copy, pd.DataFrame([new_row])])

                # update dfs
                df_streams_out_copy.loc[index_stream_out, ['Split_Check']] = True
                df_streams_out_copy.loc[index_stream_out, ['Match']] = True
                df_streams_out_copy.loc[index_stream_out, ['mcp']] = round(split_stream_mcp + .0, 5)
                df_streams_in_copy.loc[index_stream_in, ['Match']] = True

                # safety check
                if new_row['mcp'] > 0:
                    combinations_updated.append([df_streams_in_copy, df_streams_out_copy])

        else:
            combinations_updated.append([df_streams_in, df_streams_out])

    return combinations_updated


""" Helper class for the params of the handler
"""
import datetime, cgi
import urllib.parse
import logging

class ParamCollection():
    def __init__(self, request=None):
        self.params = {}
        if request:
            for k in request.arguments():
                self.params[urllib.parse.unquote(k)] = urllib.parse.unquote(request.get(k))

            # work around for PUT request that doesn't process the parameter correctly
            if len(self.params) == 0 and request.method == 'PUT':
                pp = urllib.parse.parse_qs(request.body, keep_blank_values=True)
                for p in pp:
                    value = pp[p][0]
                    # if isinstance(value, str):
                    #     value = unicode(value, 'utf-8')
                    self.params[p] = value

    def removeEmpty(self):
        for k in self.params.keys():
            if self.params[k] == '':
                del self.params[k]

    def reset(self):
        self.params = {}

    def exists(self, param):
        if param in self.params:
            return True
        else:
            return False

    def addValue(self, param, value):
        self.params[param] = value

    def getValue(self, param, default=None):
        if self.exists(param):
            v = self.params[param]
            if v == '':
                return default
            else:
                return v
        else:
            return default

    def hasValue(self, param):
        if self.exists(param):
            if self.getValue(param) is None:
                return False
            else:
                return True
        else:
            return False

    # Get the values types out of the collection
    # ------------------------------------------
    def getString(self, param, default=None):
        return self.getValue(param, default=None)

    def getDate(self, param, default=None):
        return ParamCollection.get_date(self.getValue(param), default)

    def getDateTime(self, param, default=None):
        return ParamCollection.get_datetime(self.getValue(param), default)

    def getDateTimeMicroSeconds(self, param, default=None):
        return ParamCollection.get_datetime_microseconds(self.getValue(param), default)

    def getTime(self, param, default=None):
        t = default
        v = self.getValue(param)
        if v is not None:
            try:
                if v in ['24:00', '24:00:00']:
                    t = datetime.time(hour=23, minute=59, second=59)
                elif len(v) == 8:
                    dt = datetime.datetime.strptime(v, '%H:%M:%S')
                    t = datetime.time(hour=dt.hour, minute=dt.minute, second=dt.second)
                else:
                    dt = datetime.datetime.strptime(v, '%H:%M')
                    t = datetime.time(hour=dt.hour, minute=dt.minute)

            except Exception as e:
                logging.warning("Time Error: %s - %s" % (v, e.message))

        return t

    def getFloat(self, param, default=0.0):
        f = default
        v = self.getValue(param)
        if v is not None:
            try:
                f = float(v)
            except Exception as e:
                logging.warning("Number format Error: %s - %s" % (v, e.message))

        return f

    def getInt(self, param, default=0):
        return ParamCollection.get_int(self.getValue(param), default)

    def getBool(self, param, default=False):
        return ParamCollection.get_bool(self.getValue(param), default)

    def getBinary(self, param):
        if self.exists(param):
            return self.params[param]
        else:
            return None

    @staticmethod
    def get_date(value, default=None):
        d = default
        v = value
        if v is not None:
            if isinstance(v, datetime.date) or isinstance(v, datetime.datetime):
                return v
            else:
                try:
                    if len(v) == 10:
                        dt = datetime.datetime.strptime(v,'%Y-%m-%d')
                    else:
                        # fix the date
                        i = v.find('.')
                        if i > 0: v = v[:i]
                        if v[-1] != 'Z': v += "Z"

                        dt = datetime.datetime.strptime(v,'%Y-%m-%dT%H:%M:%SZ')

                    d = datetime.date(dt.year, dt.month, dt.day)
                except Exception as e:
                    logging.warning("Date Error: %s - %s" % (v, e.message))

        return d

    @staticmethod
    def get_datetime(value, default=None):
        dt = default
        v = value
        if v is not None:
            if isinstance(v, datetime.date) or isinstance(v, datetime.datetime):
                return v

            if len(v) > 10 :
                # fix the date
                i = v.find('.')
                if i > 0: v = v[:i]
                if v[-1] != 'Z': v += "Z"

            try:
                dt = datetime.datetime.strptime(v,'%Y-%m-%dT%H:%M:%SZ')
            except Exception as e:
                logging.warning("DateTime Error: %s - %s" % (v, e.message))

        return dt

    @staticmethod
    def get_datetime_microseconds(value, default=None):
        """ Extension of get_datetime to support accuracy up to microseconds.
        This is first used by api/v1/locations/id/cont(r)acts?modified_after.
        """
        #TODO: Once this is verified to be working properly in all situations, we can merge this function with get_datetime

        dt = default
        v = value
        if v is not None:
            if isinstance(v, datetime.date) or isinstance(v, datetime.datetime):
                return v

            if len(v) > 10:
#                 # fix the date
#                 i = v.find('.')
#                 if i > 0: v = v[:i]
                if v[-1] != 'Z':
                    v += "Z"

            try:
                if len(v) > 20:
                    dt = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%fZ')
                else:
                    dt = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%SZ')
            except Exception as e:
                logging.warning("DateTime Error: %s - %s" % (v, e.message))

        return dt

    @staticmethod
    def get_int(value, default=0):
        i = default
        v = value
        if v is not None:
            try:
                i = int(v)
            except Exception as e:
                logging.warning("Integer Error: %s - %s" % (v, e.message))
        return i

    @staticmethod
    def get_bool(value, default=False):
        b = default
        v = value
        if v is not None:
            if v is not None and v in ['1', 'true', 'TRUE', 'True', True]:
                b = True

        return b

    @staticmethod
    def formatDate(date):
        if date:
            return date.strftime("%Y-%m-%d")
        return ''

    def removeParam(self, param):
        del self.params[param]

    def pprint(self, print_me=None):
        ''' Use this pretty printer to print dictionaries, its only available in development
            environments since it errors on production.
        '''
        import os
        if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
            from pprint import PrettyPrinter
            pp = PrettyPrinter(indent=4)
            if print_me is not None:
                logging.info('Printing given dictionary')
                pp.pprint(print_me)
            else:
                logging.info('Printing params')
                pp.pprint(self.params)


import ply.lex as lex
import re
import types
from tokens import tokens, reserved, Token
from errors import LexicographicError, SyntaticError
from pprint import pprint
from nltk.tokenize import word_tokenize, sent_tokenize

class RmayorLexer:
    def __init__(self, **kwargs):
        self.reserved = reserved
        self.tokens = tokens
        self.errors = []
        self.lexer = lex.lex(module=self, **kwargs)
        self.lexer.lineno = 1
        self.lexer.linestart = 0

    def _update_column(self, t):
        t.column = t.lexpos - t.lexer.linestart + 1

    states = (
        ('comments', 'exclusive'),
        ('strings', 'exclusive')
    )
    # Comments

    def t_comment(self, t):
        r'--.*($|\n)'
        t.lexer.lineno += 1
        t.lexer.linestart = t.lexer.lexpos

    def t_comments(self, t):
        r'\(\*'
        t.lexer.level = 1
        t.lexer.begin('comments')

    def t_comments_open(self, t):
        r'\(\*'
        t.lexer.level += 1

    def t_comments_close(self, t):
        r'\*\)'
        t.lexer.level -= 1

        if t.lexer.level == 0:
            t.lexer.begin('INITIAL')

    def t_comments_newline(self, t):
        r'\n+'
        t.lexer.lineno += len(t.value)
        t.lexer.linestart = t.lexer.lexpos

    t_comments_ignore = '  \t\f\r\t\v'

    def t_comments_error(self, t):
        t.lexer.skip(1)

    def t_comments_eof(self, t):
        self._update_column(t)
        if t.lexer.level > 0:
            error_text = LexicographicError.EOF_COMMENT
            self.errors.append(LexicographicError(
                error_text, t.lineno, t.column))

    t_strings_ignore = ''

    def t_strings(self, t):
        r'\"'
        t.lexer.str_start = t.lexer.lexpos
        t.lexer.myString = ''
        t.lexer.backslash = False
        t.lexer.begin('strings')

    def t_strings_end(self, t):
        r'\"'
        self._update_column(t)

        if t.lexer.backslash:
            t.lexer.myString += '"'
            t.lexer.backslash = False
        else:
            t.value = t.lexer.myString
            t.type = 'string'
            t.lexer.begin('INITIAL')
            return t

    def t_strings_newline(self, t):
        r'\n'
        t.lexer.lineno += 1
        self._update_column(t)

        t.lexer.linestart = t.lexer.lexpos

        if not t.lexer.backslash:
            error_text = LexicographicError.UNDETERMINATED_STRING
            self.errors.append(LexicographicError(
                error_text, t.lineno, t.column))
            t.lexer.begin('INITIAL')

    def t_strings_nill(self, t):
        r'\0'
        error_text = LexicographicError.NULL_STRING
        self._update_column(t)

        self.errors.append(LexicographicError(error_text, t.lineno, t.column))

    def t_strings_consume(self, t):
        r'[^\n]'
        # self._update_column(t)

        if t.lexer.backslash:
            if t.value == 'b':
                t.lexer.myString += '\b'

            elif t.value == 't':
                t.lexer.myString += '\t'

            elif t.value == 'f':
                t.lexer.myString += '\f'

            elif t.value == 'n':
                t.lexer.myString += '\n'

            elif t.value == '\\':
                t.lexer.myString += '\\'
            else:
                t.lexer.myString += t.value
            t.lexer.backslash = False
        else:
            if t.value != '\\':
                t.lexer.myString += t.value
            else:
                t.lexer.backslash = True

    def t_strings_error(self, t):
        pass

    def t_strings_eof(self, t):
        self._update_column(t)

        error_text = LexicographicError.EOF_STRING
        self.errors.append(LexicographicError(error_text, t.lineno, t.column))

    t_ignore = '  \t\f\r\t\v'

    def t_semi(self, t):
        r';'
        self._update_column(t)
        return t

    def t_colon(self, t):
        r':'
        self._update_column(t)
        return t

    def t_comma(self, t):
        r','
        self._update_column(t)
        return t

    def t_dot(self, t):
        r'\.'
        self._update_column(t)
        return t

    def t_opar(self, t):
        r'\('
        self._update_column(t)
        return t

    def t_cpar(self, t):
        r'\)'
        self._update_column(t)
        return t

    def t_lbracket(self, t):
        r'\['
        self._update_column(t)
        return t

    def t_rbracket(self, t):
        r'\]'
        self._update_column(t)
        return t

    def t_ocur(self, t):
        r'\{'
        self._update_column(t)
        return t

    def t_ccur(self, t):
        r'\}'
        self._update_column(t)
        return t

    def t_larrow(self, t):
        r'<-'
        self._update_column(t)
        return t

    def t_arroba(self, t):
        r'@'
        self._update_column(t)
        return t

    def t_rarrow(self, t):
        r'->'
        self._update_column(t)
        return t

    def t_nox(self, t):
        r'~'
        self._update_column(t)
        return t

    def t_equal(self, t):
        r'='
        self._update_column(t)
        return t

    def t_plus(self, t):
        r'\+'
        self._update_column(t)
        return t

    # def t_of(self, t):
    #     r'of'
    #     self._update_column(t)
    #     return t

    def t_minus(self, t):
        r'-'
        self._update_column(t)
        return t

    def t_star(self, t):
        r'\*'
        self._update_column(t)
        return t

    def t_div(self, t):
        r'/'
        self._update_column(t)
        return t

    def t_lesseq(self, t):
        r'<='
        self._update_column(t)
        return t

    def t_moreeq(self, t):
        r'>='
        self._update_column(t)
        return t

    def t_less(self, t):
        r'<'
        self._update_column(t)
        return t

    def t_more(self, t):
        r'>'
        self._update_column(t)
        return t

    def t_and(self, t):
        r'&'
        self._update_column(t)
        return t

    def t_or(self, t):
        r'\|'
        self._update_column(t)
        return t

    # def t_inherits(self, t):
    #     r'inherits'
    #     self._update_column(t)
    #     return t

    def t_end(self, t):
        r'end'
        self._update_column(t)
        return t

    def t_type(self, t):
        r'[A-Z][a-zA-Z_0-9]*'
        t.type = self.reserved.get(t.value.lower(), 'type')
        self._update_column(t)
        return t
  # Check for reserved words:

    def t_id(self, t):
        r'[a-z][a-zA-Z_0-9]*'
        t.type = self.reserved.get(t.value.lower(), 'id')
        self._update_column(t)
        return t

    # Get Numbers

    def t_num(self, t):
        r'\d+(\.\d+)? '
        t.value = float(t.value)
        self._update_column(t)
        return t

    # Define a rule so we can track line numbers
    def t_newline(self, t):
        r'\n+'
        t.lexer.lineno += len(t.value)
        t.lexer.linestart = t.lexer.lexpos

    # Error handling rule
    def t_error(self, t):
        self._update_column(t)
        error_text = LexicographicError.UNKNOWN_TOKEN % t.value[0]

        self.errors.append(LexicographicError(error_text, t.lineno, t.column))
        t.lexer.skip(1)
        # t.lexer.skip(len(t.value))

    def tokenize_text(self, text: str) -> list:
        self.lexer.input(text)
        tokens = []
        for tok in self.lexer:
            tokens.append(Token(tok.type, tok.value, tok.lineno, tok.column))
        self.lexer.lineno = 1
        self.lexer.linestart = 0
        return tokens

    def _check_empty_line(self, tokens: list):
        if len(tokens) == 0:
            error_text = SyntaticError.ERROR % 'EOF'
            print(SyntaticError(error_text, 0, 0))
            raise Exception()

    def run(self, text: str):
        tokens = self.tokenize_text(text)
        if self.errors:
            for error in self.errors:
                print(error)
            raise Exception()

        self._check_empty_line(tokens)
        return tokens

if __name__ == "__main__":
    lexer = RmayorLexer()

    data = open('string4.rm', encoding='utf-8')
    data = data.read()
    res = lexer.tokenize_text(data)
    # pprint(res)
    pprint(lexer.run(data))

# # Regular expression rules for simple tokens
# t_PLUS = r'\+'
# t_MINUS = r'\-'
# t_MULTIPLY = r'\*'
# t_DIVIDE = r'\/'
# t_MODULO = r'\%'

# t_NOT = r'\~'
# t_EQUALS = r'\='
# t_AND = r'&'
# t_OR = r'\|'

# t_COMMENT = r'\#.*',

# t_AGENTS = r'AGENT'        # AGENTS
# t_ENVIRONMENT = r'ENVIRONMENT'   # ENVIRONMENT
# t_MAP = r'MAP'           # MAP
# t_STAGES = r'STAGES'  # STAGES
# t_SEMAPHORES = r'SEMAPHORES'     # SEMAPHORES
# t_DEPOT = r'DEPOT'         # DEPOT
# t_BUS_STOP = r'BUS_STOP'      # BUS_STOP
# t_COMPANY = r'COMPANY'       # COMPANY
# t_VEHICLE = r'VEHICLE'       # VEHICLE
# t_CLIENT = r'CLIENT'        # CLIENT
# t_FIRM = r'FIRM'          # FIRM

# def t_newline(t):
#     r'\n+'
#     t.lexer.lineno += len(t.value)

# def t_error(t):
#     print("Illegal character '%s'" % t.value[0])
#     t.lexer.skip(1)

# # lexer=ply.lex()


from trajalign.traj import Traj
from trajalign.average import load_directory
from trajalign.average import nanMAD as MAD
from matplotlib import pyplot as plt
from scipy import stats
import numpy as np

def measure_lifetimes( list_of_trajectories , min_cutoff = 3 , max_cutoff = 125 ):

	#measure_lifetimes of the trajectories in the list

	lifetimes = []

	for element in list_of_trajectories :

		if ( element.frames()[ 0 ] > min_cutoff ) & ( element.frames()[ len( element ) - 1 ] < max_cutoff ) :

			lifetimes.append( element.lifetime() )

	return lifetimes

def average_lifetime( l , how ) :

	#average the lifetime of the trajectories

	if how == 'mean' or how == 'Mean' :

		a = [ np.mean( l ) , np.std( l ) / np.sqrt( len( l ) ) ]

	elif how == 'median' or how == 'Median' :

		a = [ np.nanmedian( l ) , MAD( l ) / np.sqrt( len( l ) ) ]

	else :

		print( 'how must be either [mM]ean or [mM]edian' )

	return a

def ctrlifetimes( path , dt , how , protein_name , pattern , cutoff = ( 1 , np.inf ) , comment_char = '%' , t_unit = 's' , coord_unit = 'pxl' , frames = 0 , coord = ( 1 , 2 ) , f = 3 ) :

	#wrapper to load the trajectories and compute their average_lifetime

	l = load_directory(
			path = path ,
			pattern = pattern ,
			comment_char = comment_char ,
			dt = dt ,
			t_unit = t_unit ,
			frames = frames ,
			coord = coord ,
			coord_unit = coord_unit ,
			f = f ,
			protein = protein_name
			)

	ml = measure_lifetimes( l , min_cutoff = cutoff[ 0 ] , max_cutoff = cutoff[ 1 ] )
	al = average_lifetime( ml , how )

	return( { 'average' : al , 'lifetimes' : ml , 'name' : protein_name } )

def significance( c1 , c2 ) :

	p = stats.mannwhitneyu( c1[ 'lifetimes' ] , c2[ 'lifetimes' ] )

	print( 'H0: the distribution of ' + c1[ 'name' ] + ' is equal to the distribution of ' + c2[ 'name' ] + '. P value = ' + str( p[ 1 ] ) )

	return p

def barplot( l , filename , figsize , ylabel , reference = [ ] , x_rotation = 0 ) :

	# l is a list of ctralifetimes outputs
	# it can be that a user inputs a tuple instead
	l = list( l )

	g , ( barplot ) = plt.subplots( 1 , 1 , gridspec_kw = { 'height_ratios' : [ 1 ] , 'width_ratios' : [ 1 ] } , figsize = figsize )

	#reference (f), if present,  is the first bar
	if len( reference ) :

		bplt_x = [ 0 ] + [ i + 1 for i in range( len( l ) ) ]
		bplt_y = [ reference[ 'average' ][ 0 ] ] + [ i[ 'average' ][ 0 ] for i in l ]
		bplt_yerr = [ reference[ 'average' ][ 1 ] ] + [ i[ 'average' ][ 1 ] for i in l ]
		bplt_names = [ reference[ 'name' ] ] + [ i[ 'name' ] for i in l ]

	else :

		bplt_x = [ i + 1 for i in range( len( l ) ) ]
		bplt_y = [ i[ 'average' ][ 0 ] for i in l ]
		bplt_yerr = [ i[ 'average' ][ 1 ] for i in l ]
		bplt_names = [ i[ 'name' ] for i in l ]

	barplot.bar( bplt_x , bplt_y , yerr = bplt_yerr , color = 'grey' , ecolor = 'black' )

	plt.subplot( barplot )

	xaxt = [ 0 ]

	plt.text( 0 , 1 , "n=" + str( len( reference[ 'lifetimes' ] ) ) , horizontalalignment = 'center' )

	for i in  range( len( l ) ):

		xaxt.append( i + 1 )

		plt.text( i + 1 , 1 , "n=" + str( len( l[ i ][ 'lifetimes' ] ) ) , horizontalalignment = 'center' )

	plt.ylabel( ylabel )
	barplot.set_xticks( xaxt )
	barplot.set_xticklabels( bplt_names , rotation = x_rotation )

	g.savefig( filename )

def write_csv( path , data ) :

	"""
	write_csv: write the lifetimes in the result dictionary outputs of ctrlifetimes, inputed as a tuple, into a csv file named path.
	The path includes the file name but not .csv, which is added automatically by the script
	"""

	f = open( path + '.csv' , "w" )

	header = ""
	data_len = []
	l = len( data )

	for i in range( l ) :

		header = header + data[ i ][ 'name' ] + ","
		data_len.append( len( data[ i ][ 'lifetimes' ] ) )

	f.write( header )
	f.write( "\n" )

	m = max( data_len )

	for i in range( m ) :

		line = ""

		for ii in range( l ) :

			try :

				line = line + str( data[ ii ][ 'lifetimes' ][ i ] ) + ","

			except :

				line = line + "" + ","

		f.write( line )
		f.write( "\n" )

	f.close()


from suds.client import Client

def main():
    url = "http://%s:%s/%s?wsdl" % ("localhost", 9236, "HelloService")
    print(url)
    client = Client(url)
    print("Start client.")
    ret = client.service.hello("Bob")
    print(ret)

if __name__ == '__main__':
    main()


# standard library
import os

# dash libs
import dash
from dash.dependencies import Input, Output, State, Event
import dash_core_components as dcc
import dash_html_components as html
import plotly.figure_factory as ff
import plotly.graph_objs as go

# pydata stack
import pandas as pd
from sqlalchemy import create_engine

from datetime import datetime as dt

import io
import flask
from flask import send_file, url_for, request
import urllib.parse as p
import xlsxwriter
import zipfile
import io
import pathlib
import numpy as np

# set params
#conn = create_engine(os.environ['DB_URI'])
conn = create_engine("sqlite:///atcTyres.db")
globalStockReport = pd.DataFrame(columns = ['plantCode', 'rmCode', 'calDate', 'stock', 'qty', 'etsDate'])

#######################
# Data Analysis / Model
#######################

def fetch_data(q):
    print ("Executing Query:", q)
    result = pd.read_sql(
        sql=q,
        con=conn
    )
    return result

def get_plants():
    '''Returns the list of plants that are stored in the database'''

    plant_query = (
        '''
        SELECT DISTINCT plantCode
        FROM StockReport
        '''
    )
    plants = fetch_data(plant_query)
    plants = list(plants['plantCode'].sort_values(ascending=True))
    return plants

def get_rawMats(plant):
    '''Returns the raw material of selected plant'''

    rawMats_query = (
        '''
        SELECT DISTINCT rmCode
        FROM StockReport
        WHERE plantCode='%s'
        '''%plant
    )
    rawMaterials = fetch_data(rawMats_query)
    rawMaterials = list(rawMaterials['rmCode'].sort_values(ascending=False))
    return rawMaterials

def get_SafeStock(plantCode,rmCode):
    '''Returns the Safe Stock for selected RM and Plant'''

    safeStock_query = (
        '''
        SELECT safeStock
        FROM SafeStock
        WHERE plantCode='%s'
        AND rmCode='%s'
        '''%(plantCode,rmCode)
    )
    safeStockQty = fetch_data(safeStock_query)
    return safeStockQty['safeStock']

#DB query to fetch consumption history
def get_ConsumptionHistory(plantCode, rmCode, reportDate):
    '''Returns consumption history for specified plant, rawMat since specified date'''

    report_query = (
        '''
        SELECT plantCode, rmCode, monthYear, mthlyConsumption
        FROM MthlyConsumption
        WHERE plantCode='%s'
        AND rmCode='%s'
        ORDER BY monthYear ASC
        '''%(plantCode, rmCode)
    )
    consumptionReport = fetch_data(report_query)
    return consumptionReport
        #AND monthYear >='{reportDate}'

#DB query to fetch stock report
def get_StockReport(plantCode, rmCode, reportDate):
    '''Returns stock details for specified plant, rawMat since specified date'''

    report_query = (
        '''
        SELECT plantCode, rmCode, calDate, stock, qty, etsDate
        FROM StockReport
        WHERE plantCode='%s'
        AND rmCode='%s'
        AND calDate >='%s'
        ORDER BY calDate ASC
        '''%(plantCode, rmCode, reportDate)
    )
    stockReport = fetch_data(report_query)
    stockReport =modify_stock_report(stockReport,0,plantCode, rmCode, reportDate)
    return stockReport

def modify_stock_report (results , safeStock,plantCode, rmCode, reportDate):
    # temp hardcode  consumption number
    consumptionReport = get_ConsumptionHistory(plantCode, rmCode, reportDate)
    mnonthly_cosumption = consumptionReport['mthlyConsumption'].iloc[0]
    daily_cosumption = -mnonthly_cosumption/30
    stock = results['stock'].iloc[0]
    start_value = stock
    stop_value = stock +120*daily_cosumption
    #print("series vale" , start_value,stop_value,daily_cosumption)

    data = np.arange(start_value,stop_value,daily_cosumption)
    stock_series = pd.Series(data)
    #print("Stock series is ",len(stock_series))

    date  = results['calDate'].iloc[0]

    plantcode = results['plantCode'].iloc[0]
    rmcode  =results['rmCode'].iloc[0]
    dataframe_new = pd.DataFrame(index=range(120),columns = ['calDate','plantCode', 'rmCode', 'stock', 'qty', 'etsDate'])
    dataframe_new['plantCode'] = plantcode
    dataframe_new['rmCode'] = rmcode
    dataframe_new['stock'].iloc[0] = stock
    dataframe_new['qty'] = pd.to_numeric(results['qty'])
    dataframe_new['etsDate'] = results['etsDate']

    dataframe_new['qty'].fillna(0, inplace=True)
    #print("Report date " ,  pd.to_numeric(dataframe_new['qty']))

    rng = pd.date_range(date, periods=120, freq='D')

   # print("data range datafram", rng.to_series)
    dataframe_new =  dataframe_new.assign(calDate= rng)

    dataframe_new =  dataframe_new.assign(stock= stock_series)

   # print("concated frame", dataframe_new)
    dataframe_new['stock'] =dataframe_new['stock'] +pd.to_numeric(dataframe_new['qty'])
    dataframe_new['stock'] = dataframe_new['stock'].round(2)
    return dataframe_new

def draw_stockReport_graph(results , safeStock):
    dates = results['calDate']
    #safeStocks = [safeStock] * results.shape[0]
    safeStocks = pd.DataFrame([safeStock] * results.shape[0])
    stocks = results['stock']

    # Trace Safe Stock
    trace0 = go.Scatter(
        x = dates,
        y = safeStocks[0],
        name = 'Safe Stock',
        line = dict(
            color = ('rgb(205, 12, 24)'),
            width = 4)
    )
    # Trace Actual Stock
    trace1 = go.Scatter(
        x = dates,
        y = stocks,
        name = 'Actual Stock',
        line = dict(
            color = ('rgb(22, 96, 167)'),
            width = 4,)
    )

    figure = go.Figure(
        data= [ trace0 ,  trace1],
        layout=go.Layout(
            title='Stock Report',
            showlegend=True
        )
    )
    return figure

#########################
# Dashboard Layout / View
#########################

def generate_table(dataframe, max_rows=10):
    '''Given dataframe, return template generated using Dash components
    '''
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

def onLoad_plant_options():
    '''Actions to perform upon initial page load'''

    plant_options = (
        [{'label': plantCode, 'value': plantCode}
         for plantCode in get_plants()]
    )
    return plant_options

# Set up Dashboard and create layout
app = dash.Dash(__name__)
app.css.append_css({
    "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})

app.layout = html.Div([
    html.Div([
        html.Div([
        html.Img(src='/assets/ATGlogo.png',style={'width': '150px'}),
        ], className='three columns'),
        html.Div(className='nine columns'),
    ], className='twelve columns'),
    # Page Header
    html.Div([
        html.H4('Stock Report Viewer')
    ]),

    # Dropdown Grid
    html.Div([
        html.Div([
            # Select Plant Dropdown
            html.Div([
                html.Div('Select Plant', className='three columns'),
                html.Div(dcc.Dropdown(id='plant-selector',
                                      options=onLoad_plant_options()),
                         className='nine columns')
            ]),

            # Select Raw Material Dropdown
            html.Div([
                html.Div('Select Raw Material', className='three columns'),
                html.Div(dcc.Dropdown(id='rawMat-selector'),
                         className='nine columns')
            ]),
        ], className='six columns'),

        # Empty
        # html.Div(className='six columns'),

        html.Div([
             html.P('Select Date'),
             dcc.DatePickerSingle(
        id='reportStartDate',
        min_date_allowed=dt(2001, 8, 1),
        max_date_allowed=dt(2018, 10, 1),
        placeholder='Start Date',
        ),
        ], className='three columns'),

        #Link to trigger /download_excel route
        html.Div(children=[
            html.P(html.A(
                    'Download Data',
                    id='excel-download-link',
                    download="",
                    href="",
                    target="_blank")),
            html.P(html.A(
                    'Download Zip',
                    id='zip-download-link',
                    download="",
                    href="",
                    target="_blank",
		    n_clicks=0)),
            html.P(html.A(['Print PDF'],className="button no-print print")),
        ], className='three columns'),
    ], className='twleve columns'),
    html.Div([
            html.Div([
            # Safe Stock table
            html.Div(children='Safe Stock:',className='three columns'),
            html.Div(id='safe-stock',className='one columns'),
            html.Div(className='two columns'),
            ],className='six columns'),

	    html.Div([
            #Consumption History
            html.Table(id='consumption-history'),
            ],className='six columns'),
    ],className='twelve columns'),

    # Stock Report Grid
    html.Div([

        # Stock Report Table
        html.Div(
            html.Table(id='stock-report'),
            className='six columns'
        ),

        # Stock Summary Table and Graph
        html.Div([
            # graph
            dcc.Graph(id='stock-graph')
            # style={},
        ], className='six columns')
    ]),
])

#############################################
# Interaction Between Components / Controller
#############################################

# Load Seasons in Dropdown
@app.callback(
    Output(component_id='rawMat-selector', component_property='options'),
    [
        Input(component_id='plant-selector', component_property='value')
    ]
)
def populate_rawMaterial_selector(plant):
    rawMaterials = get_rawMats(plant)
    return [
        {'label': rmCode, 'value': rmCode}
        for rmCode in rawMaterials
    ]

# Load Stock Report
@app.callback(
    Output(component_id='stock-report', component_property='children'),
    [
        Input(component_id='plant-selector', component_property='value'),
        Input(component_id='rawMat-selector', component_property='value'),
        Input(component_id='reportStartDate', component_property='date')
    ]
)
def load_stockReport(plantCode, rmCode, reportDate):
    results = get_StockReport(plantCode, rmCode, reportDate)
    return generate_table(results, max_rows=50)

# Load Safe Stock
@app.callback(
    Output(component_id='safe-stock', component_property='children'),
    [
        Input(component_id='plant-selector', component_property='value'),
        Input(component_id='rawMat-selector', component_property='value')
    ]
)
def load_stockReport(plantCode, rmCode):
    safeStock = get_SafeStock(plantCode, rmCode)
    return safeStock

# Load Consumption History
@app.callback(
    Output(component_id='consumption-history', component_property='children'),
    [
        Input(component_id='plant-selector', component_property='value'),
        Input(component_id='rawMat-selector', component_property='value'),
        Input(component_id='reportStartDate', component_property='date')
    ]
)
def load_consumptionHist(plantCode, rmCode, reportDate):
    consumptionHist = get_ConsumptionHistory(plantCode, rmCode, reportDate)
    return generate_table(consumptionHist, max_rows=50)

#Update Stock Point Graph
@app.callback(
    Output(component_id='stock-graph', component_property='figure'),
    [
        Input(component_id='plant-selector', component_property='value'),
        Input(component_id='rawMat-selector', component_property='value'),
        Input(component_id='reportStartDate', component_property='date')
    ]
)
def load_stockReport_graph(plantCode, rmCode, reportDate):
    results = get_StockReport(plantCode, rmCode, reportDate)
    safeStock = get_SafeStock(plantCode, rmCode)

    figure = []
    if len(results) > 0:
        figure = draw_stockReport_graph(results, safeStock)

    return figure

#Callback to download data as csv
#@app.callback(
#    Output(component_id='excel-download-link', component_property='href'),
#    [        Input(component_id='plant-selector', component_property='value'),
#        Input(component_id='rawMat-selector', component_property='value'),
#        Input(component_id='reportStartDate', component_property='date')]
#)
#def download_CSVSingle(plantCode, rmCode, reportDate):
#    stockReport = get_StockReport(plantCode, rmCode, reportDate)
#    globalStockReport = stockReport
#    globalStockReport= globalStockReport.dropna()
#    csv_string = globalStockReport.to_csv(index=False, encoding='utf-8')
#    csv_string = "data:text/csv;charset=utf-8," +p.quote(csv_string)
#    return csv_string

#Callback to download Excel for single RM
@app.callback(
    Output(component_id='excel-download-link', component_property='href'),
    [   Input(component_id='plant-selector', component_property='value'),
        Input(component_id='rawMat-selector', component_property='value'),
        Input(component_id='reportStartDate', component_property='date')]
)
def download_ExcelSingle(plantCode, rmCode, reportDate):
	return url_for('generate_singleRM_report',plantCode=plantCode,rmCode=rmCode,reportDate=reportDate)

#Callback to download ZIP file
@app.callback(
    Output('zip-download-link', 'href'),
    [Input('zip-download-link', 'n_clicks'),
    Input(component_id='plant-selector', component_property='value'),
    Input(component_id='reportStartDate', component_property='date')]
)
def generate_report_url(n_clicks, plantCode, reportDate):
	return url_for('generate_report_url',plantCode=plantCode,reportDate=reportDate)

# Flask routes to serve various files for download

# Serve Excel for single RM
@app.server.route('/dash/singleRMReportDownload')
def generate_singleRM_report():
	plantCode = request.args.get('plantCode')
	rmCode = request.args.get('rmCode')
	reportDate = request.args.get('reportDate')
	stockReport = get_StockReport(plantCode, rmCode, reportDate)
	stockReport = stockReport.dropna()
	rmDownload_filename = str(rmCode) + ".xlsx"
	wsName = str(plantCode) + "_" + str(rmCode)
	absolute_filename = os.path.join(os.getcwd(), rmDownload_filename)
	buf = io.BytesIO()
	#excel_writer = pd.ExcelWriter(absolute_filename, engine="xlsxwriter")
	excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
	stockReport.to_excel(excel_writer, sheet_name=wsName)
	excel_writer.save()
	excel_data = buf.getvalue()
	buf.seek(0)
	#return send_file(absolute_filename,
	return send_file(buf,
		attachment_filename = rmDownload_filename, as_attachment = True)
		#mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

# Serve ZIP for All RM
@app.server.route('/dash/allRMZipdownload')
def generate_report_url():
        plantCode = request.args.get('plantCode')
        reportDate = request.args.get('reportDate')
        rawMaterials=get_rawMats(plantCode)

        #Create  excelFile for each RM across the plant
        for rm in rawMaterials:
            rmReport = get_StockReport(plantCode,rm,reportDate)
            rmReport = rmReport.dropna()
            rm_filename = str(rm) + ".xlsx"
            wsName = str(plantCode) + "_" + str(rm)
            relative_filename = os.path.join('excelFiles',rm_filename)
            absolute_filename = os.path.join(os.getcwd(), relative_filename)
            writer = pd.ExcelWriter(absolute_filename, engine='xlsxwriter')
            rmReport.to_excel(writer, sheet_name = wsName)
            writer.save()
        zip_filename = str(plantCode) + ".zip"
        relative_filename = os.path.join('zipFiles',zip_filename)
        absolute_filename = os.path.join(os.getcwd(), relative_filename)
        excelFilePath = os.path.join(os.getcwd(), 'excelFiles')
        base_path = pathlib.Path('./excelFiles')
        with zipfile.ZipFile(relative_filename, mode='w') as z:
            for f_name in base_path.iterdir():
                z.write(f_name)

        return send_file(relative_filename, attachment_filename = zip_filename, as_attachment = True)

external_css = ["https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css",
                "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css",
                "//fonts.googleapis.com/css?family=Raleway:400,300,600",
                "https://codepen.io/bcd/pen/KQrXdb.css",
                "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"]

for css in external_css:
    app.css.append_css({"external_url": css})

external_js = ["https://code.jquery.com/jquery-3.2.1.min.js",
               "https://codepen.io/bcd/pen/YaXojL.js"]

for js in external_js:
    app.scripts.append_script({"external_url": js})

# start Flask server
if __name__ == '__main__':
    app.run_server(
        debug=True,
        host='0.0.0.0',
        port=8050
    )


from aiogram import types
from aiogram.utils.keyboard import ReplyKeyboardBuilder, InlineKeyboardBuilder

EMPTY = types.ReplyKeyboardRemove()

def get_reply_keyboard(lst_name_btn: list, kb_type):
    builder = ReplyKeyboardBuilder()

    if kb_type == "row3":
        for i in lst_name_btn:
            builder.add(types.KeyboardButton(text=str(i)))
        if len(lst_name_btn) > 3:
            builder.adjust(round(len(lst_name_btn) / 3))
        return builder.as_markup(resize_keyboard=True)

def get_inline_keyboard(lst_name_btn, kb_type):
    builder = InlineKeyboardBuilder()

    if kb_type == "url":
        for key in lst_name_btn:
            builder.add(types.InlineKeyboardButton(text=str(key),
                                                   url=str(lst_name_btn[key])))
        return builder.as_markup(resize_keyboard=True)
    elif kb_type == "callback_data":
        for key in lst_name_btn:
            builder.add(types.InlineKeyboardButton(text=str(key),
                                                   callback_data=str(lst_name_btn[key])))
        return builder.as_markup(resize_keyboard=True)


# -*- coding: utf-8 -*-
"""
    tests.test_site
    ~~~~~~~~~~~~~~~

    Provides unit tests for the website.
"""
from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import nose.tools as nt
from datetime import datetime

from . import APIHelper, get_globals
from app import db
from app.utils import jsonify, make_cache_key

tables = None
client = None

def setup_module():
    """site initialization"""
    global initialized
    global tables
    global client

    app, client = get_globals()
    tables = [k[4:] for k in app.blueprints.keys() if k.endswith('api0')]
    db.create_all()
    initialized = True
    print('Site Module Setup\n')

class TestAPI(APIHelper):
    """Unit tests for the API"""
    global client

    def __init__(self):
        self.cls_initialized = False

    def test_home(self):
        r = client.get('/')
        nt.assert_equal(r.status_code, 200)

    def test_status(self):
        r = self.get('lorem')
        result = self.get_json(r)['result']
        nt.assert_true(len(result) > 0)

class TestUtils(APIHelper):
    """Unit tests for the utils module"""
    def __init__(self):
        self.cls_initialized = False

    def test_make_cache_key(self):
        nt.assert_equal(make_cache_key(), 'http://localhost/')

    def test_jsonify(self):
        # test string
        r = jsonify(result='Hello')
        result = self.get_json(r)['result']
        nt.assert_equal(result, 'Hello')

        # test iterator
        r = jsonify(result=iter(['Hello', 'World']))
        result = self.get_json(r)['result']
        nt.assert_equal(result, ['Hello', 'World'])

        # test date
        r = jsonify(result=datetime(2015, 1, 15))
        result = self.get_json(r)['result']
        nt.assert_equal(result, u'2015-01-15 00:00:00')


import cv2
#lets define the function for mouse event
def click_event(event,x,y,flags,param):
    if event==cv2.EVENT_LBUTTONDOWN:#this is the event for left click of mouse
      print(x,',',y)#it will print the x,y coordinates
      strxy=str(x)+','+str(y)
      cv2.putText(img, strxy, (x,y),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,0,0),1)
      cv2.imshow("image",img)
img=cv2.imread('village.png')
cv2.imshow("image",img)
cv2.setMouseCallback("image",click_event)#it is a callback function that call the mouse event function
cv2.waitKey(0)
cv2.destroyAllWindows()


import warnings
warnings.simplefilter('ignore')

import sys
import pdb
import argparse

sys.path.append('/mnt/experiments/privacy-GAN/')
from data import *
from utils.generic import *
from utils.data import *

def seperate_real_and_categorical_columns(data):

    cols = data.columns
    num_cols = list(data._get_numeric_data().columns)
    non_num_cols = list(set(cols) - set(num_cols))

    num_data = data[num_cols]
    non_num_data = data[non_num_cols]
    data = pd.concat([num_data, non_num_data], axis=1)

    return data

def convert_target_column_to_categorical(target_data, basis='median'):

    if basis == 'median':
        mid_value = target_data.median()

    target_data_copy = target_data.copy()
    target_data.loc[target_data_copy <= mid_value]  = 'low'
    target_data.loc[target_data_copy > mid_value]  = 'high'

    return target_data

def seperate_out_target_variable(data_config, data, target_column):

    cols = list(data.columns)
    cols.pop(cols.index(target_column))
    non_target_data = data[cols]
    target_data = data[target_column]
    if data_config['target_variable_type'] == 'real':
        target_data = convert_target_column_to_categorical(target_data)
    new_data = pd.concat([non_target_data, target_data], axis=1)

    return new_data

def replace_nan_by_mean(dataset, num_real):
    # For numeric columns
    for i in range(num_real):
        col = dataset.iloc[:, i]
        col = col.fillna(col.mean())
        dataset.iloc[:, i] = col

    # For non-numeric columns
    for i in range(num_real, dataset.shape[1]):
        col = dataset.iloc[:, i]
        temp = (col.values).astype('str')
        val = np.unique(temp)
        if 'nan' in val:
            true_classes = list(set(val) - set(['nan']))
            num_classes = len(true_classes)
            indices = [i for i, value in enumerate(list(temp)) if value == 'nan']
            to_replace_by = np.random.randint(low=0, high=num_classes, size=len(indices))
            dataset.iloc[indices, i] = to_replace_by

    return dataset

def clean_dataset(dataset_name):
    print("<---------- Cleaning {} dataset ---------->".format(dataset_name))
    data_config = load_data_config(dataset_name)
    raw_data = load_dataset(dataset_name, state='raw')

    print("=> Seperating numeric and non_numeric columns ...")
    data = seperate_real_and_categorical_columns(raw_data)

    print("=> Dropping direct identifiers ...")
    direct_identifiers = data_config['identifiers']
    data = data.drop(direct_identifiers, axis=1)

    print("=> Replacing NaN values by column mean ...")
    num_real = data_config['num_real']
    data = replace_nan_by_mean(data, num_real=num_real)

    print("=> Shifting the target column to the last index ...")
    target_column = data_config['target_column']
    data = seperate_out_target_variable(data_config, data, target_column)

    print("=> Saving cleaned dataset ...")
    save_filepath = join(DATASETS_PATH, dataset_name, "clean_data.csv")
    data.to_csv(save_filepath, index=False)

    return

if __name__ == '__main__':

    argv = sys.argv[1:]
    parser = argparse.ArgumentParser()
    parser = argparse.ArgumentParser(description='Taking user inputs.')
    parser.add_argument('-d', '--dataset_name', type=str, choices=['adult', 'lacity'], help='Dataset name', required=True)
    parser.add_argument('-s', '--save_subset', type=bool, help='Save only a subset of the cleaned dataset?', default=False)
    parser.add_argument('-n', '--num_in_subset', type=int, help='Number of examples in to-be-saved subset', default=18000)
    args = parser.parse_known_args(argv)[0]

    clean_dataset(args.dataset_name)
    if args.save_subset:
        save_subset_of_dataset(args.dataset_name, args.num_in_subset)


import sys

s = sys.stdin.readline()[:-1]
pc = [0] * (1+len(s))
po = [0] * (1+len(s))
pw = [0] * (1+len(s))

for i, ch in enumerate(s):
    pc[i+1] = pc[i]
    po[i+1] = po[i]
    pw[i+1] = pw[i]
    if ch=='C':
        pc[i+1] = pc[i]+1
    elif ch=='O':
        po[i+1] = po[i]+1
    elif ch=='W':
        pw[i+1] = pw[i]+1

cases = int(sys.stdin.readline())
for _ in range(cases):
    case = [int(x) for x in sys.stdin.readline()[:-1].split()]
    l, r = case[0], case[1]
    c = pc[r] - pc[l-1]
    o = po[r] - po[l-1]
    w = pw[r] - pw[l-1]
    if (c+o)%2 and (o+w)%2==0:
        print('Y', end='')
    else:
        print('N', end='')


# from utils import *
import numpy as np

def main():

    a = [1, 2, 3, 4, 5]
    d = {str(i): 'hi' for i in range(len(a))}
    print(d)

if __name__ == "__main__":
    main()


op = []
ns = ''
s = ''

while int(input()) != 0:
    ns = ''
    s = ''
    l = list(map(int, input().split()))  # list of integers of permutation
    ans = [] * 10
    for i in range(len(l)):
        s += str(l[i])
        ans.insert(l[i], i + 1)
    for j in ans:
        ns += str(j)
    if ns == s:
        print(ns, ' ', s)
        op.append('Ambiguous')
    else:
        print(ns, ' ', s)
        op.append('not ambiguous')
for x in op:
    print(x)


import sys
import os
import json
from Bio import motifs
from Bio import SeqIO
from Bio.Alphabet import IUPAC
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

def build_gibbs_command(inputFilePath, motifLen):
    #outputFilePath = '/kb/module/work/tmp/gibbs_output.txt'
    if not os.path.exists('/kb/module/work/tmp/gibbs'):
        os.mkdir('/kb/module/work/tmp/gibbs')
    outputFilePath = '/kb/module/work/tmp/gibbs/gibbs_output_' + str(motifLen) +  '.txt'

    #outputFilePath = './temp/gibbs_output.txt'
    length = '8'
    command = 'Gibbs ' + inputFilePath + ' ' + str(motifLen) + ' -n > ' + outputFilePath
    return command

def run_gibbs_command(command):
    os.system(command)

def parse_gibbs_output(path):
    outputFileList = []
    #outputFileDir = '/kb/module/work/tmp'
    #for i in range(motif_min_length,motif_max_length+1,2):
        #outputFileList.append(outputFileDir + '/gibbs_output_' + str(i) + '.txt')
    for filename in os.listdir(path):
        outputFileList.append(path + '/' + filename)

    #outputFileDir = '/Users/arw/identify_promoter/test_local/workdir/tmp'
    #outputFilePath = outputFileDir + '/gibbs_output_' + str(motifLen) + '.txt'
    motifList = []
    for outputFilePath in outputFileList:

        gibbsFile = open(outputFilePath,'r')

        motifDict = {}
        pwmList = []
        processPWM = False
        processLoc = False
        gotSig = False
        motifIncluded = False

        #TODO: keeping p-value as -1 until I understand the output stats better
        motifDict['Locations'] = []
        for line in gibbsFile:
            if 'nMotifLen' in line:
                MotifLen = int(line.split()[2])
            if processLoc is True:
                if '****' in line:
                    processLoc = False
                    gotSig = False
                    motifDict['p-value'] = -1.0

                    a = []
                    c = []
                    g = []
                    t = []
                    for row in motifDict['pwm']:
                        a.append(row[0][1])
                        c.append(row[1][1])
                        g.append(row[2][1])
                        t.append(row[3][1])

                    motifStr = '>test\n'
                    motifStr += 'A ' + str(a).replace(',','') + '\n'
                    motifStr += 'C ' + str(c).replace(',','') + '\n'
                    motifStr += 'G ' + str(g).replace(',','') + '\n'
                    motifStr += 'T ' + str(t).replace(',','') + '\n'
                    handle = StringIO(motifStr)
                    BioMotif = motifs.read(handle, 'jaspar')
                    motifDict['Iupac_signature']=str(BioMotif.degenerate_consensus)

                    for m in motifList:
                        if motifDict['Iupac_signature'] == m['Iupac_signature']:
                            motifIncluded = True
                    if not motifIncluded:
                        if len(motifDict['pwm']) != len(motifDict['Iupac_signature']):
                            print(outputFilePath)
                            print(motifDict['Iupac_signature'])
                            print(len(motifDict['pwm']))
                        motifList.append(motifDict)
                    motifDict = {}
                    motifDict['Locations'] = []
                    motifIncluded = False
                    pwmList = []
                #add motif to list from here
                elif 'Num Motifs' not in line:
                    elems = line.split()
                    if not gotSig:
                        motif = elems[4]
                        #motifDict['Iupac_signature'] = motif
                        gotSig = True
                    locList = []
                    if len(line.split()) == 10:
                        locList.append(elems[9])
                        locList.append(elems[2])
                        locList.append(elems[6])
                        if elems[8] == 'F':
                            locList.append('+')
                        else:
                            locList.append('-')
                    elif len(line.split()) == 9:
                        locList.append(elems[8])
                        locList.append(elems[2])
                        locList.append(elems[5])
                        if elems[7] == 'F':
                            locList.append('+')
                        else:
                            locList.append('-')
                    motifDict['Locations'].append(locList)
            elif processPWM is True:
                if 'Background' in line:
                    processPWM = False
                    motifDict['pwm'] = pwmList
                elif '|' in line:
                    before = after
                    after = int(line.split()[0])
                    if before != -1 and after != -1:
                        if (after-before) != 1:
                            for i in range(0,(before-after)):
                                rowList = []
                                rowList.append(('A',.25))
                                rowList.append(('C',.25))
                                rowList.append(('G',.25))
                                rowList.append(('T',.25))
                                pwmList.append(rowList)
                    #baseCount += 1
                    elems = line.split()
                    rowList = []
                    rowList.append(('A',float(elems[2])))
                    rowList.append(('C',float(elems[4])))
                    rowList.append(('G',float(elems[5])))
                    rowList.append(('T',float(elems[3])))
                    pwmList.append(rowList)

            elif 'columns' in line:
                motifLength = int(line.split()[0])
                processLoc = True
            elif 'Motif probability model' in line:
                processPWM = True
                before = -1
                after = -1

    #jsonFilePath = outputFileDir + '/gibbs.json'
    #with open(jsonFilePath,'w') as jsonFile:
    #    json.dump(motifList,jsonFile)
    return motifList


# Extracted from Li, P., Wang, S., Li, T., Lu, J., HuangFu, Y., & Wang, D. (2020). A Large-Scale CT and PET/CT Dataset for Lung Cancer Diagnosis (Lung-PET-CT-Dx) [Data set]. The Cancer Imaging Archive. https://doi.org/10.7937/TCIA.2020.NNC2-0461

import os
from preprocessing.utils import *

def getUID_path(path):
    dict = {}
    list = os.listdir(path)

    for date in list:
        date_path = os.path.join(path, date)
        series_list = os.listdir(date_path)
        series_list.sort()

        for series in series_list:
            series_path = os.path.join(date_path, series)
            dicom_list = os.listdir(series_path)
            dicom_list.sort()

            for dicom in dicom_list:
                dicom_path = os.path.join(series_path, dicom)
                info = loadFileInformation(dicom_path)
                dict[info['dicom_num']] = (dicom_path, dicom)

    return dict

def getUID_file(path):
    info = loadFileInformation(path)
    UID = info['dicom_num']
    return UID


class RoutingTable:
    ID_KEY = "id"
    NAME_KEY = "name"
    IBM_CLOUD_KEY = "ibm_cloud"
    REGION_KEY = "region"
    VPC_KEY = "vpc"
    ROUTES_KEY = "routes"
    RESOURCE_JSON_KEY = "resource_json"

    def __init__(self, id_, name, region, vpc):
        self.id = id_
        self.name = name
        self.region = region
        self.vpc = vpc
        self.routes = []

    def to_json(self):
        return {
            self.ID_KEY: self.id,
            self.RESOURCE_JSON_KEY: {
                self.NAME_KEY: self.name,
                self.ROUTES_KEY: [routing_table_route.to_resource_json() for routing_table_route in
                                  self.routes],
            },
            self.IBM_CLOUD_KEY: self.region.cloud.to_reference_json(),
            self.REGION_KEY: self.region.to_reference_json(),
            self.VPC_KEY: self.vpc.to_reference_json(),
        }

    def to_reference_json(self):
        return {
            self.ID_KEY: self.id,
            self.NAME_KEY: self.name
        }

    @property
    def region(self):
        return self.__region

    @region.setter
    def region(self, region):
        from ibm.web.cloud_translations.vpc_construct import Region

        assert isinstance(region, Region)

        self.__region = region
        if self not in region.cloud.routing_tables:
            region.cloud.routing_tables.append(self)
            region.cloud.translated_resources[self.id] = self