# -*- coding: UTF-8 -*-
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image

import math
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

from pandas import DataFrame
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import random

import constants.constants as constants

from view import Router
from view import popup as popup_
from view.code import home
from view.code import getPlacar as placar

from view.code.aprendizado import start as start_

from view.code import graph

import info as Info

from time import sleep
import threading
import os, glob
from pathlib import Path

def view(TelaInicial, dict_config):

    results_r1 = []
    results_r2 = []
    results_saldo = []
    graph_x = []

    def popup(s):
        popup_.run(s)

    def router(id):
        Router.router(id, TelaInicial)
        pass

    def openFile():
    	# placares gerais AR x RESERVA
        arq_results = open('.results.txt', 'w');
        arq_results.write('Placares das Partidas \n(AR) x (Reserva)\n\n')
        for x in range(0, len(results_r1)):
            arq_results.write(str(results_r1[x]) + ' x ' + str(results_r2[x]) + '\n')
        arq_results.close()

        # Resultados apenas AR
        arq_results = open('.ResultadosAR.txt', 'w');
        # arq_results.write('Resultados -> (AR)\n\n')
        for x in range(0, len(results_r1)):
            arq_results.write(str(results_r1[x]) + '\n')
        arq_results.close()

        # Resultados apenas RESERVA
        arq_results = open('.ResultadosReserva.txt', 'w');
        # arq_results.write('Resultados -> (Reserva)\n\n')
        for x in range(0, len(results_r2)):
            arq_results.write(str(results_r2[x]) + '\n')
        arq_results.close()

        input_ = 'gedit .results.txt .ResultadosAR.txt .ResultadosReserva.txt'
        os.system(input_)

    def openGraph():
        graph.open(graph_x, results_r1, results_r2, results_saldo)

    def results():
        threading.Thread(target=openFile).start()
        openGraph()

    def verify():
        if dict_config["started"] and int(dict_config["episode"]) <= int(dict_config["episodes"]):
            start()
        else:
            countMatch(1, 1)
            # ------------------------------------------------------
            # Button Start
            # ------------------------------------------------------
            btMenu = Button(
                TelaInicial,
                width=76,
                text=constants.btBeforeAR,
                command=results,
                bg=constants.butonColorInfo,
                fg=constants.letterColor,
                activebackground=constants.activeButtonColorInfo
            )
            btMenu.place(
                x=402,
                y=579,
                anchor=CENTER
            )
            # ------------------------------------------------------

    def start():
        if not dict_config["started"]:
            # results_r1.clear()
            # results_r2.clear()
            # results_saldo.clear()
            # graph_x.clear()
            dict_config["started"] = True
            # ------------------------------------------------------
            # Button Start
            # ------------------------------------------------------
            btMenu = Button(
                TelaInicial,
                width=76,
                text=constants.btAfterAguarde,
                command=start,
                bg=constants.buttonStopColor,
                fg=constants.letterColor,
                activebackground=constants.buttonStopColorActive
            )
            btMenu.place(
                x=402,
                y=579,
                anchor=CENTER
            )
        else:
            while(dict_config["started"] and int(dict_config["episode"]) <= int(dict_config["episodes"])):
                dicTeam = {
                    "partida" : constants.btModoMatchFast,
                    "team1" : {
                        "teamName" : constants.addressTeamArName,
                        "path" : constants.addressTeamArSystem
                    },
                    "team2" : {
                        "teamName" : constants.addressTeamResName,
                        "path" : constants.addressTeamResSystem
                    }
                }
                countMatch(dict_config["episode"])
                TelaInicial.update_idletasks()

                r1, r2 = start_.run(dicTeam)
                if r1 != constants.ERROR and r2 != constants.ERROR:

                    results_r1.append(int(r1))
                    results_r2.append(int(r2))
                    results_saldo.append(int(r1)-int(r2))
                    graph_x.append(int(dict_config["episode"]))

                    graphLive()
                    progress_bar.set(int(dict_config["episode"]))

                    ep = str(dict_config["episode"])
                    r1 = str(r1)
                    r2 = str(r2)

                    while len(ep) < 3:
                        ep += ' '
                    while len(r1) < 2:
                        r1 += ' '
                    while len(r2) < 2:
                        r2 += ' '

                    listbox_1.insert(END, " Partida " + ep)
                    listbox_2.insert(END, r1)
                    listbox_3.insert(END, r2)

                    listbox_1.see(listbox_1.size())
                    listbox_2.see(listbox_2.size())
                    listbox_3.see(listbox_3.size())
                    dict_config["episode"] += 1
                else:
                    popup_.run(constants.msgReiniciarPartida, 2000)
                TelaInicial.update_idletasks()

        TelaInicial.update_idletasks()
        TelaInicial.after_idle(verify())

    def countMatch(x, final = None):
        if final == None:
            desc = "Partida " + str(x) + " em andamento"
        else:
            desc = "        Episódios completos        "
        # ------------------------------------------------------
        lbPartida = Label(
            TelaInicial,
            text=desc,
            bg=constants.backgroundColor,
            fg=constants.letterColor
        )
        lbPartida.config(
            font=(
                constants.fontPersonalizada,
                constants.fontSizeTitleTelaIn
            )
        )
        lbPartida.place(
            x=410,
            y=20,
            anchor=N
        )
        # ------------------------------------------------------

    def graphLive():
        data1 = {'Partida': graph_x,
                 'Saldo_de_Gol': results_saldo
                }
        df1 = DataFrame(data1,columns=['Partida','Saldo_de_Gol'])
        df2 = df1[['Partida','Saldo_de_Gol']].groupby('Partida').sum()
        df2.plot(kind='line', legend=False, ax=ax2, color='r',marker='o', linewidth=1, linestyle='dashed')

        figure2.canvas.draw()
        figure2.canvas.flush_events()

    data1 = {'Partida': graph_x,
             'Saldo_de_Gol': results_saldo
            }
    df1 = DataFrame(data1,columns=['Partida','Saldo_de_Gol'])

    figure2 = plt.Figure(figsize=(19,4), dpi=50, facecolor='white', edgecolor='white')
    ax2 = figure2.add_subplot(111)
    line2 = FigureCanvasTkAgg(figure2, TelaInicial)
    line2.get_tk_widget().place(
        x=390,
        y=370,
        anchor=N
    )
    df2 = df1[['Partida','Saldo_de_Gol']].groupby('Partida').sum()
    # df2.plot(kind='line', legend=False, ax=ax2, color='w',marker='', linewidth=0, linestyle='dashed')
    ax2.tick_params(top='off', bottom='off', left='off', right='off', labelright=True)
    ax2.set_title('Saldo de Gols')
    ax2.set_xlabel('')

    # AR x Reserva
    Label(
        TelaInicial,
        text=constants.labelResultTeam,
        bg=constants.backgroundColor,
        font=constants.fontPersonalizadaList,
    ).place(
        x=530,
        y=90,
        anchor=W
    )
    # Resultados
    Label(
        TelaInicial,
        text=constants.labelResult,
        bg=constants.backgroundColor,
        font=constants.fontPersonalizadaList,
    ).place(
        x=395,
        y=90,
        anchor=W
    )
    # ------------------------------------------------------
    # listbox partida
    # ------------------------------------------------------
    listbox_1 = Listbox(
        TelaInicial,
        width=12,
        height=6,
        font=constants.fontPersonalizadaList,
        fg=constants.listboxFG,
        bg=constants.listboxBG,
        bd=0,
    )
    listbox_1.configure(justify=CENTER)
    listbox_1.place(
        x=380,
        y=170,
        anchor=W
    )
    # ------------------------------------------------------
    # ------------------------------------------------------
    # listbox result ar
    # ------------------------------------------------------
    listbox_2 = Listbox(
        TelaInicial,
        width=3,
        height=6,
        font=constants.fontPersonalizadaList,
        fg=constants.listboxFG,
        bg=constants.listboxBG,
        bd=0,
    )
    listbox_2.configure(justify=CENTER)
    listbox_2.place(
        x=530,
        y=170,
        anchor=W
    )
    # ------------------------------------------------------
    # ------------------------------------------------------
    # listbox result reserva
    # ------------------------------------------------------
    listbox_3 = Listbox(
        TelaInicial,
        width=3,
        height=6,
        font=constants.fontPersonalizadaList,
        fg=constants.listboxFG,
        bg=constants.listboxBG,
        bd=0,
    )
    listbox_3.configure(justify=CENTER)
    listbox_3.place(
        x=600,
        y=170,
        anchor=W
    )
    # ------------------------------------------------------

    # ------------------------------------------------------
    # percent 1
    width = 50
    height = 50
    img_1 = Image.open(constants.addressPercent_1)
    img_1 = img_1.resize((width,height), Image.ANTIALIAS)
    logo_1 = ImageTk.PhotoImage(img_1)
    panel_1 = Label(TelaInicial, image=logo_1, bg=constants.backgroundColor)
    panel_1.place(x=68, y=313, anchor=CENTER)
    # ------------------------------------------------------
    # ------------------------------------------------------
    # percent 2
    img_2 = Image.open(constants.addressPercent_2)
    img_2 = img_2.resize((width,height), Image.ANTIALIAS)
    logo_2 = ImageTk.PhotoImage(img_2)
    panel_2 = Label(TelaInicial, image=logo_2, bg=constants.backgroundColor)
    panel_2.place(x=68 + 328, y=313, anchor=CENTER)
    # ------------------------------------------------------
    # ------------------------------------------------------
    # percent 3
    img_3 = Image.open(constants.addressPercent_3)
    img_3 = img_3.resize((width,height), Image.ANTIALIAS)
    logo_3 = ImageTk.PhotoImage(img_3)
    panel_3 = Label(TelaInicial, image=logo_3, bg=constants.backgroundColor)
    panel_3.place(x=68 + 663, y=313, anchor=CENTER)
    # ------------------------------------------------------

    progress_bar = DoubleVar()

    s = ttk.Style()
    s.theme_use('clam')
    s.configure(
        "bar.Horizontal.TProgressbar",
        troughcolor=constants.backgroundColor,
        bordercolor=constants.backgroundColor,
        background=constants.butonColorInfo,
        lightcolor=constants.butonColorInfo,
        darkcolor=constants.activeButtonColorInfo
    )

    barra = ttk.Progressbar(
        TelaInicial,
        style="bar.Horizontal.TProgressbar",
        length=744,
        variable=progress_bar,
        orient="horizontal",
        maximum=int(dict_config["episodes"]),
    )
    barra.place(
        x=402,
        y=350,
        anchor=N
    )

    dist_x = 115
    # Algorithm
    Label(
        TelaInicial,
        text=constants.labelAlgorithm,
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=100,
        anchor=W
    )
    # Alpha
    Label(
        TelaInicial,
        text=constants.labelAlpha,
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=130,
        anchor=W
    )
    # Gamma
    Label(
        TelaInicial,
        text=constants.labelGamma,
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=160,
        anchor=W
    )
    # Epsilon
    Label(
        TelaInicial,
        text=constants.labelEpsilon,
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=190,
        anchor=W
    )
    # Episodes
    Label(
        TelaInicial,
        text=constants.labelEpisodes,
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=220,
        anchor=W
    )

    dist_x = 250
    # Algorithm
    Label(
        TelaInicial,
        text="->",
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=100,
        anchor=W
    )
    # Alpha
    Label(
        TelaInicial,
        text="->",
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=130,
        anchor=W
    )
    # Gamma
    Label(
        TelaInicial,
        text="->",
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=160,
        anchor=W
    )
    # Epsilon
    Label(
        TelaInicial,
        text="->",
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=190,
        anchor=W
    )
    # Episodes
    Label(
        TelaInicial,
        text="->",
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=220,
        anchor=W
    )

    dist_x = 270
    # Algorithm
    Label(
        TelaInicial,
        text=dict_config["algorithm"],
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=100,
        anchor=W
    )
    # Alpha
    Label(
        TelaInicial,
        text=dict_config["alpha"],
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=130,
        anchor=W
    )
    # Gamma
    Label(
        TelaInicial,
        text=dict_config["gamma"],
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=160,
        anchor=W
    )
    # Epsilon
    Label(
        TelaInicial,
        text=dict_config["epsilon"],
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=190,
        anchor=W
    )
    # Episodes
    Label(
        TelaInicial,
        text=dict_config["episodes"],
        bg=constants.backgroundColor
    ).place(
        x=dist_x,
        y=220,
        anchor=W
    )

    # ------------------------------------------------------
    # Button Voltar
    # ------------------------------------------------------
    btMenu = Button(
        TelaInicial,
        width=5,
        text=constants.btMenu,
        command=lambda router=router: router(0),
        bg=constants.butonColor,
        fg=constants.letterColor,
        activebackground=constants.activeButtonColor
    )
    btMenu.place(
        x=795,
        y=595,
        anchor=SE
    )
    # ------------------------------------------------------

    # ------------------------------------------------------
    # Button Sair
    # ------------------------------------------------------
    btSair = Button(
        TelaInicial,
        width=5,
        text=constants.btExit,
        command=lambda router=router: router(999),
        bg=constants.butonColor,
        fg=constants.letterColor,
        activebackground=constants.activeButtonColor
    )
    btSair.place(
        x=10,
        y=595,
        anchor=SW
    )
    # ------------------------------------------------------
    # ------------------------------------------------------
    # Button Start
    # ------------------------------------------------------
    btMenu = Button(
        TelaInicial,
        width=76,
        text=constants.btAfterAR,
        command=start,
        bg=constants.buttonColorConfig,
        fg=constants.letterColor,
        activebackground=constants.activeButtonColor
    )
    btMenu.place(
        x=402,
        y=579,
        anchor=CENTER
    )

    TelaInicial.mainloop()


"""
    :codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import pytest

import salt.states.debconfmod as debconfmod
from tests.support.mock import MagicMock, patch

@pytest.fixture
def configure_loader_modules():
    return {debconfmod: {}}

def test_set_file():
    """
    Test to set debconf selections from a file or a template
    """
    name = "nullmailer"
    source = "salt://pathto/pkg.selections"

    ret = {"name": name, "result": False, "comment": "", "changes": {}}

    comt = "Context must be formed as a dict"
    ret.update({"comment": comt})
    assert debconfmod.set_file(name, source, context="salt") == ret

    comt = "Defaults must be formed as a dict"
    ret.update({"comment": comt})
    assert debconfmod.set_file(name, source, defaults="salt") == ret

    with patch.dict(debconfmod.__opts__, {"test": True}):
        comt = "Debconf selections would have been set."
        ret.update({"comment": comt, "result": None})
        assert debconfmod.set_file(name, source) == ret

        with patch.dict(debconfmod.__opts__, {"test": False}):
            mock = MagicMock(return_value=True)
            with patch.dict(debconfmod.__salt__, {"debconf.set_file": mock}):
                comt = "Debconf selections were set."
                ret.update({"comment": comt, "result": True})
                assert debconfmod.set_file(name, source) == ret

def test_set():
    """
    Test to set debconf selections
    """
    name = "nullmailer"
    data = {
        "shared/mailname": {"type": "string", "value": "server.domain.tld"},
        "nullmailer/relayhost": {"type": "string", "value": "mail.domain.tld"},
    }

    ret = {"name": name, "result": None, "comment": "", "changes": {}}

    changes = {
        "nullmailer/relayhost": "New value: mail.domain.tld",
        "shared/mailname": "New value: server.domain.tld",
    }

    mock = MagicMock(return_value=None)
    with patch.dict(debconfmod.__salt__, {"debconf.show": mock}):
        with patch.dict(debconfmod.__opts__, {"test": True}):
            ret.update({"changes": changes})
            assert debconfmod.set(name, data) == ret


#!/usr/bin/env python3

import enum, math, random, sys

# TODO: bitwise, comma operator, delete key from object
# TODO: arrays and array literals
# TODO: for loops, do-while, built-in methods, standard library
# TODO: try-catch
# TODO: write conways game of life to test

# DeleteExpression -> 'delete' MemberAccess
# returns false if property is non-configurable ex:
# var a = [1,2,3], delete a["length"]; evaluated to true
# see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
class TokenType(enum.Enum):
	# TODO: replace var with let
	VAR = 0
	FUNCTION = 1
	IF = 2
	ELSE = 3
	WHILE = 4
	RETURN = 5
	BREAK = 6
	CONTINUE = 7
	TRY = 8
	CATCH = 9
	THROW = 10
	IDENTIFIER = 11
	NUMBER = 12
	STRING = 13
	BOOL = 14
	NULL = 15
	OPEN_PAREN = 16
	CLOSE_PAREN = 17
	OPEN_BRACE = 18
	CLOSE_BRACE = 19
	OPEN_BRACKET = 20
	CLOSE_BRACKET = 21
	SEMICOLON = 22
	COLON = 23
	MUL_OP = 24
	ADD_OP = 25
	REL_OP = 26
	EQ_OP = 27
	NOT = 28
	ASSIGN_OP = 29
	COMMA = 30
	DOT_OP = 31
	AND_OP = 32
	OR_OP = 33
	EOF = 34

class Lexer:
	reservedWords = {
		'true'     : (TokenType.BOOL,     True),
		'false'    : (TokenType.BOOL,     False),
		'null'     : (TokenType.NULL,     None),
		'var'      : (TokenType.VAR,      None),
		'function' : (TokenType.FUNCTION, None),
		'if'       : (TokenType.IF,       None),
		'else'     : (TokenType.ELSE,     None),
		'in'       : (TokenType.REL_OP,   'in'),
		# TODO: delete operator
		'while'    : (TokenType.WHILE,    None),
		'return'   : (TokenType.RETURN,   None),
		'break'    : (TokenType.BREAK,    None),
		'continue' : (TokenType.CONTINUE, None),
		'try'      : (TokenType.TRY,      None),
		'catch'    : (TokenType.CATCH,    None),
		'throw'    : (TokenType.THROW,    None)
	}

	operators = {
		'+': TokenType.ADD_OP,
		'-': TokenType.ADD_OP,
		'*': TokenType.MUL_OP,
		'/': TokenType.MUL_OP,
		'%': TokenType.MUL_OP,
		'<': TokenType.REL_OP,
		'>': TokenType.REL_OP,
		'!': TokenType.NOT,
		'=': TokenType.ASSIGN_OP,
		'+=': TokenType.ASSIGN_OP,
		'-=': TokenType.ASSIGN_OP,
		'*=': TokenType.ASSIGN_OP,
		'/=': TokenType.ASSIGN_OP,
		'%=': TokenType.ASSIGN_OP,
		'<=': TokenType.REL_OP,
		'>=': TokenType.REL_OP,
		'!=': TokenType.EQ_OP,
		'==': TokenType.EQ_OP,
		'&&': TokenType.AND_OP,
		'||': TokenType.OR_OP,
		'.': TokenType.DOT_OP
	}

	punctuation = {
		'(': TokenType.OPEN_PAREN,
		')': TokenType.CLOSE_PAREN,
		'{': TokenType.OPEN_BRACE,
		'}': TokenType.CLOSE_BRACE,
		'[': TokenType.OPEN_BRACKET,
		']': TokenType.CLOSE_BRACKET,
		',': TokenType.COMMA,
		':': TokenType.COLON,
		';': TokenType.SEMICOLON
	}

	escapeSequences = {
		'b': '\b',
		'f': '\f',
		'n': '\n',
		'r': '\r',
		't': '\t',
		'v': '\v',
		'0': '\0',
		'\'': '\'',
		'"': '"',
		'\\': '\\'
	}

	def __init__(self, s):
		self.s = s
		self.i = 0

	def getchar(self, noEof = False):
		pos = self.i
		self.i += 1
		if pos < len(self.s):
			return self.s[pos]
		else:
			if noEof:
				raise Exception('unexpected EOF')
			return ''

	def unget(self):
		self.i -= 1

	def lexan(self):
		while True:
			c = self.getchar()
			# EOF
			if c == '':
				return (TokenType.EOF, '')
			# Whitespace
			elif c.isspace():
				continue
			# Comments and Division
			elif c == '/':
				c = self.getchar()

				# Single line comment
				if c == '/':
					while c != '' and c != '\n':
						c = self.getchar()
				elif c == '*':
					# Multiline comments
					while True:
						c = self.getchar(True)
						while c != '*':
							c = self.getchar(True)
						c = self.getchar(True)
						if c == '/':
							break
						if c == '*':
							self.unget()
				elif c == '=':
					return (Lexer.operators['/='], '/=')
				else:
					self.unget()
					return (Lexer.operators['/'], '/')
			# Numbers
			elif c.isdigit():
				# TODO: octal and hex literals
				# Integer Part
				number = 0
				while c.isdigit():
					number *= 10
					number += ord(c) - ord('0')
					c = self.getchar()

				# Check if floating point
				if c == '.':
					floatPart = 0
					decimalPlace = 0.1
					c = self.getchar(noEof=True)
					if not c.isdigit():
						raise Exception('invalid token %r at %d' % (c, i))

					while c.isdigit():
						floatPart += decimalPlace * (ord(c) - ord('0'))
						decimalPlace /= 10.0
						c = self.getchar()
					number += floatPart

				self.unget()
				return (TokenType.NUMBER, number)
			# Identifiers and reserved words
			elif c.isalpha() or c == '$' or c == '_':
				identifier = ''
				while c.isalnum() or c == '$' or c == '_':
					identifier += c
					c = self.getchar()
				self.unget()
				return Lexer.reservedWords.get(identifier, (TokenType.IDENTIFIER, identifier))
			# String literals
			elif c == '"' or c == '\'':
				quoteType = c
				text = ''
				c = self.getchar(noEof=True)
				while c != quoteType:
					# Escape sequence
					if c == '\\':
						c = self.getchar(noEof=True)
						c = Lexer.escapeSequences.get(c, c)
					text += c
					c = self.getchar(noEof=True)

				return (TokenType.STRING, text)
			# Operators
			elif c in '<>=+-*%!':
				if self.getchar() == '=':
					return (Lexer.operators[c + '='], c + '=')
				else:
					self.unget()
					return (Lexer.operators[c], c)
			elif c == '&':
				if self.getchar() != '&':
					raise Exception('invalid token for and')
				return (TokenType.AND_OP, '&&')
			elif c == '|':
				if self.getchar() != '|':
					raise Exception('invalid token for or')
				return (TokenType.OR_OP, '||')
			elif c == '.':
				return (TokenType.DOT_OP, None)
			# Punctuation
			elif c in Lexer.punctuation:
				return (Lexer.punctuation[c], None)
			else:
				raise Exception('unknown token %r' % c)

	def tokenize(self):
		tokens = []
		while True:
			t = self.lexan()
			if t[0] == TokenType.EOF:
				break
			tokens.append(t)
		return tokens

class Statement:
	def eval(self, environment):
		raise NotImplemented

class Expression(Statement):
	pass

class Number(Expression):
	def __init__(self, value):
		self.value = value
	def __repr__(self):
		return '%f' % self.value
	def eval(self, environment):
		return self.value

class String(Expression):
	def __init__(self, value):
		self.value = value
	def __repr__(self):
		return '%r' % self.value
	def eval(self, environment):
		return self.value

class Bool(Expression):
	def __init__(self, value):
		assert(value in [True, False])
		self.value = value
	def __repr__(self):
		if self.value:
			return 'true'
		return 'false'
	def eval(self, environment):
		return self.value

class Null(Expression):
	def __repr__(self):
		return 'null'
	def eval(self, environment):
		return None

class Identifier(Expression):
	def __init__(self, name):
		self.name = name
	def __repr__(self):
		return 'id(%s)' % self.name
	def eval(self, environment):
		return environment.get(self.name)

class ObjectLiteral(Expression):
	def __init__(self, members):
		assert(type(members) == list)
		self.members = []
		for key, value in members:
			assert(isinstance(value, Expression))
			if type(key) == String:
				self.members.append((key.value, value))
			elif type(key) == Identifier:
				self.members.append((key.name, value))
			else:
				assert(type(key) == Number)
				self.members.append((key.value, value))
	def __repr__(self):
		return '{%s}' % (', '.join('%r:%r' % (key, value) for key, value in self.members),)

	def eval(self, environment):
		o = {}
		for key, value in self.members:
			o[key] = value.eval(environment)
		return o

class MemberAccess(Expression):
	def __init__(self, obj, key):
		assert(isinstance(key, Expression))
		assert(isinstance(obj, Expression))
		self.obj, self.key = obj, key
	def __repr__(self):
		return '%r[%r]' % (self.obj, self.key)

	def eval(self, environment):
		'''
		$ // object is evaluated first, then key
		$ var a = {};
		$ function f() { console.log("f"); return a; };
		$ function g() { console.log("g"); return "a";};
		$ f()[g()];
		f
		g
		$
		'''
		obj = self.obj.eval(environment)
		key = self.key.eval(environment)
		if type(obj) != dict:
			raise Exception('non-objects do not have members')
		return obj.get(key)

class Block(Statement):
	def __init__(self, statements):
		self.statements = statements
	def __repr__(self):
		r = '\n'.join(s.__repr__() for s in self.statements)
		return '{ %s }' % r
	def eval(self, environment):
		environment = Environment(environment)
		for statement in self.statements:
			statement.eval(environment)

class Function:
	def __init__(self, params, body, closure):
		self.params = params
		self.body = body
		self.closure = closure

	def __repr__(self):
		paramsRep = ', '.join(self.params)
		return 'function(%s)%r env: %r' % (paramsRep, self.body, self.closure)

	def __call__(self, *arguments):
		environment = Environment(self.closure)
		if len(arguments) != len(self.params):
			raise Exception('wrong number of arguments')
		for name, value in zip(self.params, arguments):
			environment.create(name, value)
		try:
			self.body.eval(environment)
		except ReturnValue as r:
			return r.value

class FunctionLiteral(Expression):
	def __init__(self, params, body):
		paramNames = set()
		self.params = []
		for param in params:
			assert(type(param) == Identifier)
			if param.name in paramNames:
				raise Exception('Repeated function parameter name %r' % param.name)
			paramNames.add(param.name)
			self.params.append(param.name)
		assert(type(body) == Block)
		self.body = body

	def __repr__(self):
		paramsRep = ', '.join(self.params)
		return 'function(%s)%r' % (paramsRep, self.body)

	def eval(self, environment):
		return Function(self.params, self.body, environment)

class Call(Expression):
	def __init__(self, fun, args):
		assert(isinstance(fun, Expression))
		for arg in args:
			assert(isinstance(arg, Expression))
		self.fun, self.args = fun, args

	def __repr__(self):
		args = ', '.join(a.__repr__() for a in self.args)
		return 'call(%r, %s)' % (self.fun, args)

	def eval(self, environment):
		# TODO: which gets evaluated first? function or arguments
		fun = self.fun.eval(environment)

		if callable(fun):
			return fun(*[a.eval(environment) for a in self.args])
		raise Exception('not callable')

class Not(Expression):
	def __init__(self, expr):
		assert(isinstance(expr, Expression))
		self.expr = expr
	def __repr__(self):
		return 'not(%r)' % self.expr
	def eval(self, environment):
		return not self.expr.eval(environment)

class UnaryMinus(Expression):
	def __init__(self, expr):
		assert(isinstance(expr, Expression))
		self.expr = expr
	def __repr__(self):
		return 'minus(%r)' % self.expr
	def eval(self, environment):
		return -self.expr.eval(environment)

class BinaryOp(Expression):
	def __init__(self, lhs, rhs, op):
		assert(isinstance(lhs, Expression))
		assert(isinstance(rhs, Expression))
		self.lhs, self.rhs, self.op = lhs, rhs, op
	def __repr__(self):
		return '(%s %r %r)' % (self.op, self.lhs, self.rhs)
	ops = {
		'*': lambda a, b: a * b,
		'/': lambda a, b: a / b,
		'%': lambda a, b: a % b,
		'+': lambda a, b: a + b,
		'-': lambda a, b: a - b,
		'<': lambda a, b: a < b,
		'<=': lambda a, b: a <= b,
		'>': lambda a, b: a > b,
		'>=': lambda a, b: a >= b,
		'in': lambda a, b: a in b,
		'==': lambda a, b: a == b,
		'!=': lambda a, b: a != b
	}

	def eval(self, environment):
		# TODO: type checking and type conversions
		return BinaryOp.ops[self.op](self.lhs.eval(environment), self.rhs.eval(environment))

class MulOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op in '*/%')
		BinaryOp.__init__(self, lhs, rhs, op)

class AddOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op in '+-')
		BinaryOp.__init__(self, lhs, rhs, op)

class RelOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op in ['<', '<=', '>', '>=', 'in'])
		BinaryOp.__init__(self, lhs, rhs, op)

class EqOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op in ['==', '!='])
		BinaryOp.__init__(self, lhs, rhs, op)

class AndOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op == '&&')
		BinaryOp.__init__(self, lhs, rhs, '&&')
	def eval(self, environment):
		lhs = self.lhs.eval(environment)
		if not lhs:
			return lhs
		return self.rhs.eval(environment)

class OrOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op == '||')
		BinaryOp.__init__(self, lhs, rhs, '||')
	def eval(self, environment):
		lhs = self.lhs.eval(environment)
		if lhs:
			return lhs
		return self.rhs.eval(environment)

class AssignOp(BinaryOp):
	def __init__(self, lhs, rhs, op):
		assert(op in ['=', '+=', '-=', '*=', '/=', '%='])
		BinaryOp.__init__(self, lhs, rhs, op)

	def eval(self, environment):
		value = self.rhs.eval(environment)

		if type(self.lhs) == Identifier:
			get = lambda: environment.get(self.lhs.name)
			def update(value):
				environment.update(self.lhs.name, value)
		elif type(self.lhs) == MemberAccess:
			key = self.lhs.key.eval(environment)
			obj = self.lhs.obj.eval(environment)
			if type(obj) != dict:
				raise Exception('non-objects do not have members')
			get = lambda: obj.get(key)
			def update(value): obj[key] = value
		else:
			# See: https://stackoverflow.com/questions/16686974/can-a-functions-return-value-be-an-lvalue-in-javascript
			# and https://stackoverflow.com/questions/13124417/real-world-examples-of-ecmascript-functions-returning-a-reference
			raise Exception('invalid left-hand side in assignemnt')

		if self.op != '=':
			# Note: get is not called for '=' -> allows adding members
			curValue = get()
			if self.op == '+=':
				value = curValue + value
			elif self.op == '-=':
				value = curValue - value
			elif self.op == '*=':
				value = curValue * value
			elif self.op == '/=':
				value = curValue / value
			elif self.op == '%=':
				value = curValue % value
			else:
				raise Exception('unknown assignment operator %r' % self.op)

		update(value)
		return value

class If(Statement):
	def __init__(self, condition, body, elseBody=None):
		assert(isinstance(condition, Expression))
		assert(isinstance(body, Statement))
		if elseBody:
			assert(isinstance(elseBody, Statement))
		self.condition, self.body, self.elseBody = condition, body, elseBody
	def __repr__(self):
		e = ''
		if self.elseBody != None:
			e = ' else %r' % self.elseBody
		return '(if (%r) %r%s)' % (self.condition, self.body, e)

	def eval(self, environment):
		if self.condition.eval(environment):
			self.body.eval(environment)
		elif self.elseBody != None:
			self.elseBody.eval(environment)

class While(Statement):
	def __init__(self, condition, body):
		assert(isinstance(condition, Expression))
		assert(isinstance(body, Statement))
		self.condition, self.body = condition, body
	def __repr__(self):
		return '(while (%r) %r)' % (self.condition, self.body)

	def eval(self, environment):
		while self.condition.eval(environment):
			try:
				self.body.eval(environment)
			except BreakLoop:
				break
			except ContinueLoop:
				continue

class ReturnValue(Exception):
	def __init__(self, value):
		self.value = value

class Return(Statement):
	def __init__(self, expr=None):
		if expr != None:
			assert(isinstance(expr, Expression))
		self.expr = expr
	def __repr__(self):
		return 'return %r' % self.expr

	def eval(self, environment):
		raise ReturnValue(self.expr and self.expr.eval(environment))

class BreakLoop(Exception): pass
class Break(Statement):
	def __repr__(self):
		return 'break'
	def eval(self, environment):
		raise BreakLoop()

class ContinueLoop(Exception): pass
class Continue(Statement):
	def __repr__(self):
		return 'continue'
	def eval(self, environment):
		raise ContinueLoop()

class ExceptionObject(Exception):
	def __init__(self, obj):
		self.obj = obj

class Throw(Statement):
	def __init__(self, expr):
		self.expr = expr
	def __repr__(self):
		return 'throw %r' % self.expr
	def eval(self, environment):
		raise ExceptionObject(self.expr.eval(environment))

class TryCatch(Statement):
	def __init__(self, tryBlock, catchBlock, exceptionIdentifier):
		self.tryBlock = tryBlock
		self.catchBlock = catchBlock
		self.exceptionIdentifier = exceptionIdentifier
	def eval(self, environment):
		try:
			self.tryBlock.eval(environment)
		except ExceptionObject as e:
			catchEnv = Environment(environment)
			catchEnv.create(self.exceptionIdentifier, e.obj)
			self.catchBlock.eval(catchEnv)
		# TODO: finally + multiple catch blocks

class Declaration(Statement):
	# TODO: use Null instead of none for default expression values
	def __init__(self, name, initializer=None):
		assert(isinstance(name, Identifier))
		if initializer:
			assert(isinstance(initializer, Expression))
		self.name, self.initializer = name, initializer
	def __repr__(self):
		i = ''
		if self.initializer != None:
			i = ' = %r' % self.initializer
		return 'var %s%s' % (self.name.name, i)
	def eval(self, environment):
		value = None
		if self.initializer:
			value = self.initializer.eval(environment)
		environment.create(self.name.name, value)

class Parser:
	def __init__(self, s):
		self.lexer = Lexer(s)
		self.tokenType, self.tokenValue = self.lexer.lexan()

	def match(self, c):
		if self.tokenType != c:
			raise Exception('expected token of type %r not %r (%r)' % (c, self.tokenValue, self.tokenValue))
		self.tokenType, self.tokenValue = self.lexer.lexan()

	def identifier(self):
		i = Identifier(self.tokenValue)
		self.match(TokenType.IDENTIFIER)
		return i

	def function(self):
		'''
		Function -> 'function' '(' ParameterNames ')' Block
		ParameterNames -> epsilon | ParameterName {',' ParameterName }*
		ParameterName -> Identifier
		'''
		self.match(TokenType.FUNCTION)
		self.match(TokenType.OPEN_PAREN)

		parameters = []
		if self.tokenType == TokenType.IDENTIFIER:
			parameters.append(self.identifier())
			while self.tokenType == TokenType.COMMA:
				self.match(TokenType.COMMA)
				parameters.append(self.identifier())

		self.match(TokenType.CLOSE_PAREN)
		body = self.block()
		return FunctionLiteral(parameters, body)

	def objectLiteral(self):
		members = []
		def member():
			#https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript
			if self.tokenType not in [TokenType.STRING, TokenType.IDENTIFIER, TokenType.NUMBER]:
				raise Exception("Object literal keys must be string or number literals, or identifiers")
			key = self.atom()
			self.match(TokenType.COLON)
			value = self.expression()
			members.append((key, value))

		self.match(TokenType.OPEN_BRACE)
		if self.tokenType != TokenType.CLOSE_BRACE:
			member()
			while self.tokenType == TokenType.COMMA:
				self.match(TokenType.COMMA)
				member()

		self.match(TokenType.CLOSE_BRACE)
		return ObjectLiteral(members)

	def atom(self):
		'''
		Atom -> Number | String | Identifier | 'true' | 'false' | 'null' |
			ObjectLiteral | Function | '(' Expression ')'
		'''
		if self.tokenType == TokenType.NUMBER:
			e = Number(self.tokenValue)
			self.match(TokenType.NUMBER)
		elif self.tokenType == TokenType.STRING:
			e = String(self.tokenValue)
			self.match(TokenType.STRING)
		elif self.tokenType == TokenType.IDENTIFIER:
			return self.identifier()
		elif self.tokenType == TokenType.BOOL:
			e = Bool(self.tokenValue)
			self.match(TokenType.BOOL)
		elif self.tokenType == TokenType.NULL:
			e = Null()
			self.match(TokenType.NULL)
		elif self.tokenType == TokenType.OPEN_BRACE:
			return self.objectLiteral()
		elif self.tokenType == TokenType.FUNCTION:
			return self.function()
		else:
			self.match(TokenType.OPEN_PAREN)
			e = self.expression()
			self.match(TokenType.CLOSE_PAREN)
		return e

	def unit(self):
		'''
		Unit -> Atom | MemberAccess | FunctionCall
		MemberAccess -> Atom '[' Expression ']' | Atom '.' Identifier
		FunctionCall -> Atom '(' Arguments ')'
		Arguments -> epsilon | Expression {',' Expression }*
		'''
		u = self.atom()
		# Member access and function calls can be chained
		while self.tokenType in [TokenType.OPEN_BRACKET, TokenType.DOT_OP, TokenType.OPEN_PAREN]:
			if self.tokenType == TokenType.OPEN_BRACKET:
				self.match(TokenType.OPEN_BRACKET)
				member = self.expression()
				self.match(TokenType.CLOSE_BRACKET)
				u = MemberAccess(u, member)
			elif self.tokenType == TokenType.DOT_OP:
				self.match(TokenType.DOT_OP)
				u = MemberAccess(u, String(self.identifier().name))
			else:
				self.match(TokenType.OPEN_PAREN)
				# Parse arguments
				args = []
				if self.tokenType != TokenType.CLOSE_PAREN:
					args.append(self.expression())
					while self.tokenType == TokenType.COMMA:
						self.match(TokenType.COMMA)
						args.append(self.expression())
				self.match(TokenType.CLOSE_PAREN)
				u = Call(u, args)
		return u

	def factor(self):
		'''
		Factor -> '!' Factor | '-' Factor | Unit
		'''
		# Right to left associative
		if self.tokenType == TokenType.NOT:
			self.match(TokenType.NOT)
			return Not(self.factor())

		if self.tokenType == TokenType.ADD_OP:
			if self.tokenValue == '-':
				self.match(TokenType.ADD_OP)
				return UnaryMinus(self.factor())
			elif self.tokenValue == '+':
				self.match(TokenType.ADD_OP)
				return self.factor()
			else:
				raise Exception("unknown add op")

		return self.unit()

	def expression(self):
		# TODO: comma expression (typically used in for loops)
		'''
		Expression -> SingleExpression {',' SingleExpression}*
		SingleExpression -> OrExpression | Assignment

		Assignment -> OrExpression AssignOp Expression
		AssignOp -> '=' | '+=' | '-=' | '*=' | '/=' | '%='

		OrExpression -> AndExpression { '&&' AndExpression}*
		AndExpression -> EqExpression { '&&' EqExpression}*

		EqExpression -> RelationalExpression { EqOp EqExpression }*
		EqOp -> '==' | '!='

		RelationalExpression -> ArithematicExpression { RelOp ArithematicExpression }*
		RelOp -> '<' | '<=' | '>' | '>=' | 'in'

		ArithematicExpression -> Term { AddOp Term }*
		AddOp -> '+' | '-'

		Term -> Factor { MulOp Factor }*
		MulOp -> '*' | '/' | '%'
		'''
		# Operators in order of increasing precedence
		# op token type, op class, isLeftAssociative
		precedenceLevels = [
			(TokenType.ASSIGN_OP, AssignOp, False),
			(TokenType.OR_OP,  OrOp,  True),
			(TokenType.AND_OP, AndOp, True),
			(TokenType.EQ_OP,  EqOp,  True),
			(TokenType.REL_OP, RelOp, True),
			(TokenType.ADD_OP, AddOp, True),
			(TokenType.MUL_OP, MulOp, True)
		]

		def level(i):
			if i == len(precedenceLevels):
				return self.factor()
			tokenType, opClass, isLeftAssociative = precedenceLevels[i]

			expr = level(i + 1)
			if isLeftAssociative:
				while self.tokenType == tokenType:
					op = self.tokenValue
					self.match(tokenType)
					rhs = level(i + 1)
					expr = opClass(expr, rhs, op)
			elif self.tokenType == tokenType:
				op = self.tokenValue
				self.match(tokenType)
				return opClass(expr, level(i), op)

			return expr

		return level(0)

	def ifStatement(self):
		self.match(TokenType.IF)
		self.match(TokenType.OPEN_PAREN)
		condition = self.expression()
		self.match(TokenType.CLOSE_PAREN)
		body = self.statement()
		elseBody = None
		if self.tokenType == TokenType.ELSE:
			self.match(TokenType.ELSE)
			elseBody = self.statement()
		return If(condition, body, elseBody)

	def whileStatement(self):
		self.match(TokenType.WHILE)
		self.match(TokenType.OPEN_PAREN)
		condition = self.expression()
		self.match(TokenType.CLOSE_PAREN)
		body = self.statement()
		return While(condition, body)

	def declaration(self):
		self.match(TokenType.VAR)
		name = self.tokenValue
		self.match(TokenType.IDENTIFIER)
		value = None
		if self.tokenType == TokenType.ASSIGN_OP and self.tokenValue == '=':
			self.match(TokenType.ASSIGN_OP)
			value = self.expression()
		self.match(TokenType.SEMICOLON)
		return Declaration(Identifier(name), value)

	def tryCatch(self):
		'''
		TryCatch -> 'try' Block 'catch' '(' Identifier ')' Block
		// TODO: multiple catch blocks, finally blocks
		'''
		self.match(TokenType.TRY)
		tryBlock = self.block()
		# TODO: multiple catch blocks
		self.match(TokenType.CATCH)
		self.match(TokenType.OPEN_PAREN)
		exceptionIdentifier = self.identifier()
		self.match(TokenType.CLOSE_PAREN)
		catchBlock = self.block()
		return TryCatch(tryBlock, catchBlock, exceptionIdentifier.name)

	def statement(self):
		'''
		Statement -> Declaration | Block | IfStatement | WhileStatement
					| ReturnStatement | Expression ';'
					| BreakStatement
					| ContinueStatement
					| TryCatch
					| ThrowStatement

		BreakStatement -> 'break' ';'
		ContinueStatement  -> 'continue' ';'
		ReturnStatement -> 'return' [ Expression ] ';'
		ThrowStatement -> 'throw' Expression ';'
		'''
		if self.tokenType == TokenType.VAR:
			return self.declaration()
		if self.tokenType == TokenType.OPEN_BRACE:
			return self.block()
		if self.tokenType == TokenType.IF:
			return self.ifStatement()
		if self.tokenType == TokenType.WHILE:
			return self.whileStatement()
		if self.tokenType == TokenType.TRY:
			return self.tryCatch()
		if self.tokenType == TokenType.RETURN:
			self.match(TokenType.RETURN)
			expr = None
			if self.tokenType != TokenType.SEMICOLON:
				expr = self.expression()
			self.match(TokenType.SEMICOLON)
			return Return(expr)
		if self.tokenType == TokenType.BREAK:
			self.match(TokenType.BREAK)
			self.match(TokenType.SEMICOLON)
			return Break()
		if self.tokenType == TokenType.CONTINUE:
			self.match(TokenType.CONTINUE)
			self.match(TokenType.SEMICOLON)
			return Continue()
		if self.tokenType == TokenType.THROW:
			self.match(TokenType.THROW)
			expr = self.expression()
			self.match(TokenType.SEMICOLON)
			# TODO: check rules on throw statements
			return Throw(expr)

		e = self.expression()
		self.match(TokenType.SEMICOLON)
		return e

	def block(self):
		statements = []
		self.match(TokenType.OPEN_BRACE)
		while self.tokenType != TokenType.CLOSE_BRACE:
			statements.append(self.statement())
		self.match(TokenType.CLOSE_BRACE)
		return Block(statements)

	def parse(self):
		statements = []
		while self.tokenType != TokenType.EOF:
			statements.append(self.statement())
		self.match(TokenType.EOF)
		return statements

class Environment:
	def __init__(self, parent=None):
		self.parent = parent
		self.variables = {}

	def has(self, name):
		if name in self.variables:
			return True
		if self.parent:
			return self.parent.has(name)
		return False

	def get(self, name):
		if name in self.variables:
			return self.variables[name]
		if self.parent:
			return self.parent.get(name)
		raise Exception('%r is undefined' % name)

	def create(self, name, value):
		if name in self.variables:
			raise Exception('%r already exists in innermost environment' % name)
		self.variables[name] = value

	def update(self, name, value):
		# Note: change to "name in self.variables or not self.parent" to allow global prop
		if name in self.variables:
			self.variables[name] = value
		elif not self.parent:
			raise Exception('%r is undefined' % name)
		else:
			self.parent.update(name, value)

def evaluate(source):
	program = Parser(source).parse()
	environment = Environment()
	environment.create('print', print)

	def consoleAssert(cond, *args):
		if not cond:
			raise Exception('Assertion failed:', args)
	def mathRound(x):
		# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
		y = +x + 0.5
		return y - (y % 1)

	environment.create('console', {
		'log': print,
		'assert': consoleAssert
	})
	environment.create('Math', {
		'E': math.e,
		'LN2': math.log(2),
		'LN10': math.log(10),
		'LOG2E': math.log2(math.e),
		'LOG10E': math.log10(math.e),
		'PI': math.pi,
		'SQRT1_2': math.sqrt(0.5),
		'SQRT2': math.sqrt(2),
		'abs': abs,
		'acos': math.acos,
		'acosh': math.acosh,
		'asin': math.asin,
		'asinh': math.asinh,
		'atan': math.atan,
		'atanh': math.atanh,
		'atan2': math.atan2,
		'cbrt': lambda x: math.pow(x, 1.0/3.0),
		'ceil': math.ceil,
		'clz32': NotImplemented,
		'cos': math.cos,
		'cosh': math.cosh,
		'exp': math.exp,
		'expm1': math.expm1,
		'floor': math.floor,
		'fround': NotImplemented,
		'hypot': lambda *args: math.sqrt(sum(x*x for x in args)),
		'imul': NotImplemented,
		'log': math.log,
		'log1p': math.log1p,
		'log10': math.log10,
		'log2': math.log2,
		'max': max,
		'min': min,
		'pow': math.pow,
		'random': random.random,
		'round': mathRound,
		'sign': lambda x: 1 if x > 0 else -1 if x < 0 else 0,
		'sin': math.sin,
		'sinh': math.sinh,
		'sqrt': math.sqrt,
		'tan': math.tan,
		'trunc': int
	})
	# TODO: parseInt, parseFloat, string methods
	for statement in program:
		try:
			statement.eval(environment)
		except ReturnValue:
			raise Exception('cannot have return statement outside of function body')
		except BreakLoop:
			raise Exception('cannot have break statement outside of loop')
		except ContinueLoop:
			raise Exception('cannot have continue statement outside of loop')

def testEval():
	testCases = [
		'''
		var memo = {};
		var fib = function(n) {
			if(n < 2) return n;
			return fib(n - 1) + fib(n - 2);
		};
		var i = 0;
		while(i < 10) {
			memo[i] = fib(i);
			i = i + 1;
		}
		memo;
		''',
		'''
		var a = {x: 0, y:1, z:2};
		'w' in a;
		'x' in a;
		'y' in a;
		'z' in a;
		''',
		'''
		var memo = {};
		var fib = function(n) {
			if(n < 2) return n;
			if(n in memo) {
				return memo[n];
			}
			var f = fib(n - 1) + fib(n - 2);
			return memo[n] = f;
		};
		var i = 0;
		while(i < 10) {
			memo;
			fib(i);
			i = i + 1;
		}
		memo;
		''',
		'''
		var fib = function() {
			// closure demo
			var memo = {};
			return function(n) {
				if(n < 2) return n;
				if(n in memo) {
					return memo[n];
				}
				var f = fib(n - 1) + fib(n - 2);
				return memo[n] = f;
			};
		}();

		var i = 10;
		var r = {};
		while(i >= 0) {
			r[i] = fib(i);
			i -= 1;
		}
		r;
		''',
		'''
		var n = 4;
		var i = 0;
		while(i < n) {
			print(Math["cos"](Math["PI"]*i/n), Math["sin"](Math["PI"]*i/n));
			i += 1;
		}
		''',
		'''
		var n = 4;
		var i = 0;
		while(i < n) {
			print(Math.cos(Math.PI*i/n), Math.sin(Math.PI*i/n));
			i += 1;
		}
		''',
		'''
		var i = 0;
		var s = 0;
		var n = 10;
		while(i < n) {
			i = i + 1;
			print(i, s);
			if(i % 2) {
				print('Skiping odd');
				continue;
			}
			print('Even!');
			s += i;
		}
		print(s);
		''',
		'''
		var i = 1;
		var n = 30;
		while(true) {
			if(i >= n) {
				break;
			}
			i *= 2;
		}
		print(i);
		''',
		'''
		print("Testing &&");
		5 > 9 && print("should not print");
		5 < 9 && print("should print");
		print((1 && 2 && 3 && 4) == 4);
		print((1 && 0 && 3 && 4) == 0);
		''',
		'''
		print("Testing ||");
		5 > 9 || print("should print");
		5 < 9 || print("should not print");
		print((0 || 0 || 3 || 4) == 3);
		''',
		'''
		print("&& has greater precedence than ||");
		print((1 && 2 || 3) == 2);
		print((1 || 2 && print("should not print")) == 1);
		print((0 || 2 && 3) == 3);
		''',
		'''
		print("higher order functions");
		var map = function(f, n) {
			var i = 0;
			while(i < n) {
				print(f(i));
				i += 1;
			}
		};
		map(function(x) { return x*x;}, 10);
		'''
	]
	for testCase in testCases:
		print('Testing')
		print(testCase)
		evaluate(testCase)

def testParser():
	testCases = [
		('0;',),
		('\'hello\';',),
		('a;',),
		('true;',),
		('false;',),
		('null;',),
		('function(){};',),
		('function(a){};',),
		('function(a, b, c){};',),
		('(1);',),
		('a["hi"];',),
		('a["users"]["adrian"];',),
		('a("hi");',),
		('a("hi", 4, 8);',),
		('a["callbacks"]["error"]();',),
		('a["callbacks"]["error"](404, "Not found");',),
		('function(){}();',),
		('a[function(){}];',),
		('a[function(){}()];',),
		('function(a, b, c){}(1, 2, 3);',),
		('!!!!true;',),
		('- - -7;',),
		('- + +7;',),
		('-8;',),
		('!-8;',),
		('-!0;',),
		('71 * -8 / +2 % 10;',),
		('order["quantity"] * prices[order["item"]];', ),
		('2 * 3 + 4 < 5 - 6/7;',),
		('order["item"] in prices;',),
		('x1 > y1 == x2 > y2;',),
		('a = b = c;',),
		('b += a = 2 * 3 + 4 < 5 - 6/7;',),
		('if (x < 0) {}',),
		('if (x < 0) {} else {}',),
		('if (x < 0) {} else if(x > 0) {}',),
		('if (x < 0) {} else if(x > 0) {} else {}',),
		('while(x > 0) {}',),
		('while(x > 0) x = x - 1;',),
		('while(x > 1)  if(x % 2 == 0) x = x/2; else x = 3*x + 1;',),
		('function(x) { return; }(0);',),
		('function(x) { return x + 1; }(0);',),
		('while(i < length) { if(a[i] == x) break; i = i + 1;}',),
		('{ i = length; while(i > 0) { i = i - 1; if(a[i] % 2 == 1) continue; a[i] = -a[i]; } }',),
		('var a;',),
		('var a = 0;',),
		('var f = function(x) { return x + 1;};',),
		('var a = {};',),
		('var a = {"name":"Adrian", "age":22};',),
		('{ 1; 2;}',), # block
		('var a = { "x": 1, "y": 0};',), # strings for keys
		('var b = { x: 1, y: 0};',), # identifier for keys
		('var c = { 1: 1, 0: 0};',), # number literals for keys
	]

	for testCase in testCases:
		source = testCase[0]
		print(source, Parser(source).parse())

	invalid = [
		('function()', 'function without body'),
		('function)', 'function without open paren'),
		('function(', 'function without close paren'),
		('function(a b){}', 'invalid paramenter list'),
		('function(7){}', 'invalid paramenter list'),
		('function(a, b,){}', 'invalid paramenter list'),
		('function(a, b, a){}', 'invalid parameter list'),
		('a("hi"', 'no closing paren in call'),
		('a("hi", 2, 3', 'no closing paren in call'),
		('a["hi"', 'no closing brace in member access'),
		('-', 'unary minus without argument'),
		('- + - -', 'unary minus without argument'),
		('+', 'unary plus without argument'),
		('!', 'not without argument'),
		('!!!', 'not without argument'),
		('71 * -8 / +2 %', 'no modulus'),
		('71 * -8 /', 'no divisor'),
		('* 89', 'no lhs'),
		('= 89', 'no lhs'),
		('71 *', 'no rhs'),
		('71 +', 'no rhs'),
		('71 <=', 'no rhs'),
		('71 =', 'no rhs'),
		('if', 'invalid if'),
		('if 8', 'invalid if'),
		('if (8', 'invalid if: no close paren'),
		('if (x < 0)', 'invalid if: no body'),
		('if (x < 0) else', 'invalid if: no body'),
		('if (x < 0) f(-x); else', 'invalid if: no body'),
		('if (x < 0) {} else', 'no body for else'),
		('while','no loop condition'),
		('while ) {}', 'no open paren'),
		('while (x {}', 'no close paren'),
		('while (x)', 'no body'),
		('while() {}', 'no loop condition'),
		('function(x) { return x + 1 }', 'no semicoln after expresion in return'),
		('function(x) { return }', 'invalid return'),
		('function(x) { return return; }', 'invalid return'),
		('return ;','Return statement outside of function'),
		('break ;','Break statement outside of loop'),
		('continue ;','continue statement outside of loop'),
		('function() { break ; }();','Break statement outside of loop'),
		('function() { continue ; }();','Continue statement outside of loop'),
		('var ','no variable name'),
		('var ;', 'no variable name'),
		('var a', 'no semicolon'),
		('var a = ;', 'no initialization expression'),
		('var f = function(x) { return x + 1};', 'invalid expression'),
		('{a:1};','cannot have object literal at beginning of statement'),
	]

	for source, description in invalid:
		try:
			Parser(source).parse()
			print('FAIL: expected error', source, description)
		except:
			pass

def testLexer():
	testCases = [
		# Numbers
		('0', [(TokenType.NUMBER, 0)]),
		('123', [(TokenType.NUMBER, 123)]),
		('0.234', [(TokenType.NUMBER, 0.234)]),
		# Reserved words
		('true', [(TokenType.BOOL, True)]),
		('false', [(TokenType.BOOL, False)]),
		('null', [(TokenType.NULL, None)]),
		('var', [(TokenType.VAR, None)]),
		('function', [(TokenType.FUNCTION, None)]),
		('if', [(TokenType.IF, None)]),
		('while', [(TokenType.WHILE, None)]),
		('return', [(TokenType.RETURN, None)]),
		# Identifiers
		('a', [(TokenType.IDENTIFIER, 'a')]),
		('a123', [(TokenType.IDENTIFIER, 'a123')]),
		('ABC_DEF', [(TokenType.IDENTIFIER, 'ABC_DEF')]),
		('$', [(TokenType.IDENTIFIER, '$')]),
		('$Money', [(TokenType.IDENTIFIER, '$Money')]),
		# String literals and escape sequences
		('"literal"', [(TokenType.STRING, 'literal')]),
		('"escape \\" sequence \\\\ tada!"', [(TokenType.STRING, 'escape " sequence \\ tada!')]),
		('"\\b\\f\\n\\r\\t\\v\\0\\\'\\"\\\\"', [(TokenType.STRING, '\b\f\n\r\t\v\0\'\"\\')]),
		('"\\a\\c\\d\\e\\g"', [(TokenType.STRING, 'acdeg')]),
		('\'literal\'', [(TokenType.STRING, 'literal')]),
		('\'escape \\" sequence \\\\ tada!\'', [(TokenType.STRING, 'escape " sequence \\ tada!')]),
		('\'\\b\\f\\n\\r\\t\\v\\0\\\'\\"\\\\\'', [(TokenType.STRING, '\b\f\n\r\t\v\0\'\"\\')]),
		('\'\\a\\c\\d\\e\\g\'', [(TokenType.STRING, 'acdeg')]),
		('\'\\\'\'', [(TokenType.STRING, '\'')]),
		# Comments
		('a//hello people', [(TokenType.IDENTIFIER, 'a')]),
		('//hello people\n123', [(TokenType.NUMBER, 123)]),
		# Multi-line Comments
		('a /*hello people\n1 2 3\nhi*/ b', [(TokenType.IDENTIFIER, 'a'), (TokenType.IDENTIFIER, 'b')]),
		('a /*hello * people\n1 2 3\nhi*/ b', [(TokenType.IDENTIFIER, 'a'), (TokenType.IDENTIFIER, 'b')]),
		('a /*hello /* people\n1 2 3\nhi*/ b', [(TokenType.IDENTIFIER, 'a'), (TokenType.IDENTIFIER, 'b')]),
		('a /*hello * //people\n1 2 3\nhi*/ b', [(TokenType.IDENTIFIER, 'a'), (TokenType.IDENTIFIER, 'b')]),
		('a//hello people', [(TokenType.IDENTIFIER, 'a')]),
		# Punctuation
		('(){};:', [(TokenType.OPEN_PAREN, None), (TokenType.CLOSE_PAREN, None), (TokenType.OPEN_BRACE, None), (TokenType.CLOSE_BRACE, None), (TokenType.SEMICOLON, None), (TokenType.COLON, None)]),
		# Operators
	]

	for source, expected in testCases:
		got = Lexer(source).tokenize()
		if got != expected:
			print('FAIL', source, got, expected)

	invalid = [
		'.234',
		'123.',
		'093',
		'123a',
		'/*',
		'/*adsf*'
	]
	for source in invalid:
		try:
			got = Lexer(source).tokenize()
			print('FAIL: expected error', source)
		except:
			pass

def runFile(path):
	with open(path, 'r') as f:
		source = f.read()
	evaluate(source)

if __name__ == '__main__':
	if len(sys.argv) == 2:
		runFile(sys.argv[1])
	# testLexer()
	# testParser()
	# testEval()


from dungeon import Dungeon
from interface import *
from objects import *
import config

if __name__ == '__main__':
    pygame.init()
    pygame.display.set_caption('Magic Dungeon')
    screen = pygame.display.set_mode(SIZE)

    dungeon = Dungeon()

    # Создаем словарь вида {имя окна: класс окна}
    windows = {
        'menu': Window('menu', [
            Image('menu/background', (0, 0)),
            Image('menu/title', (206, 10)),
            Button('menu/play', (192, 190), 'game', {'cycle': True}),
            Button('menu/load', (192, 290), 'load', {'cycle': True}),
            Button('menu/settings', (192, 390), 'settings', {'cycle': True}),
            Button('menu/exit', (192, 490), 'exit', {'cycle': True}),
            Image('menu/fire', (40, 277), {'speed': 6}),
            Image('menu/fire', (407, 277), {'speed': 6}),
        ]),
        'settings': Window('settings', [
            AntiButton('settings/panel', (97, 152), 'menu'),
            Image('settings/music', (131, 212)),
            Image('settings/sounds', (131, 330)),
            Image('settings/scrollbar', (309, 233)),
            Image('settings/scrollbar', (309, 351)),
            Slider('settings/slider', (442, 225), (309, 442),
                   'set_music_volume'),
            Slider('settings/slider', (442, 343), (309, 442),
                   'set_sounds_volume'),
        ]
                           ),
        'load': Window('load', [
            AntiButton('load/panel', (97, 152), 'menu'),
            Image('load/title', (211, 172)),
            Image('load/cell', (119, 263)),
            Text((134, 278), DESCRIPTION_COLOR, target=config,
                 attr_name='USER_NAME'),
            Arrow('load/down', (411, 322), +1, {'cycle': True}),
            Arrow('load/up', (411, 172), -1, {'cycle': True}),
            LoadButton('load/load', (219, 350), 'game', dungeon,
                       {'cycle': True}),
        ]),
        'exit': Window('exit', []),
        'game': Window('game', [dungeon], music_name='game'),
        'lose': Window('lose', [
            Image('lose/background', (0, 0)),
            Image('lose/lose_text', (196, 200)),
            Button('lose/menu', (104, 300), 'menu', {'cycle': True}),
            Button('lose/new_game', (352, 300), 'game', {'cycle': True}),
        ], music_name='defeat'),
        'win': Window('win', [
            Image('win/background', (0, 0)),
            Image('win/win_text', (196, 200)),
            Button('win/menu', (104, 300), 'menu', {'cycle': True}),
            Button('win/new_game', (352, 300), 'game', {'cycle': True}),
        ], music_name='victory'),
        'inventory': Window('inventory', [Inventory(dungeon)],
                            music_name='game'),
        'save': Window('save', [
            AntiButton('save/panel', (97, 152), 'game'),
            Image('save/title', (211, 172)),
            InputBox('save/input_box', (119, 243), ''),
            SaveButton('save/save', (219, 330), 'game', dungeon,
                       {'cycle': True})],
                       music_name='game')

    }

    clock = pygame.time.Clock()
    while True:  # бесконечный игровой цикл
        # обновляем окно и делаем отрисовку
        # в зависимости от произошедших событий
        windows[config.CURRENT_WINDOW].update(screen, pygame.event.get())
        pygame.display.flip()  # обновление экрана
        clock.tick(FPS)  # задержка


import pytest

from mock import patch

from polyaxon.cli.components import components
from tests.test_cli.utils import BaseCommandTestCase

@pytest.mark.cli_mark
class TestCliComponent(BaseCommandTestCase):
    @patch("polyaxon_sdk.ProjectsV1Api.create_version")
    @patch("polyaxon_sdk.ProjectsV1Api.get_version")
    def test_create_component(self, get_version, create_component):
        self.runner.invoke(components, ["push"])
        assert create_component.call_count == 0
        assert get_version.call_count == 0
        self.runner.invoke(components, ["push", "--name=owner/foo"])
        assert get_version.call_count == 0
        assert create_component.call_count == 0

    @patch("polyaxon_sdk.ProjectsV1Api.list_versions")
    def test_list_components(self, list_components):
        self.runner.invoke(components, ["ls", "--project=owner/foo"])
        assert list_components.call_count == 1

    @patch("polyaxon_sdk.ProjectsV1Api.get_version")
    def test_get_components(self, get_components):
        self.runner.invoke(components, ["get", "-p", "admin/foo"])
        assert get_components.call_count == 1

    @patch("polyaxon_sdk.ProjectsV1Api.patch_version")
    def test_update_components(self, update_components):
        self.runner.invoke(
            components, ["update", "-p", "admin/foo", "--description=foo"]
        )
        assert update_components.call_count == 1

    @patch("polyaxon_sdk.ProjectsV1Api.create_version_stage")
    def test_update_artifact_stage(self, stage_component):
        self.runner.invoke(
            components,
            ["stage", "-p", "admin/foo", "-to", "production", "--reason=foo"],
        )
        assert stage_component.call_count == 1


import os

import pytest

pytestmark = [
    pytest.mark.windows_whitelisted,
    pytest.mark.skip_unless_on_windows,
    pytest.mark.destructive_test,
    pytest.mark.slow_test,
]

@pytest.fixture(scope="module")
def lgpo(modules):
    return modules.lgpo

@pytest.fixture(scope="module")
def enable_legacy_auditing(lgpo):
    # To test and use these policy settings we have to disable adv auditing
    # Location: Windows Settings -> Security Settings -> Local Policies -> Security Options
    # Policy: "Audit: Force audit policy subcategory settings..."
    # Short Name: SceNoApplyLegacyAuditPolicy
    try:
        lgpo.set_computer_policy("SceNoApplyLegacyAuditPolicy", "Disabled")
        lgpo.set_computer_policy("Audit account management", "No auditing")
        check = lgpo.get_policy("SceNoApplyLegacyAuditPolicy", "machine")
        assert check == "Disabled"
        check = lgpo.get_policy("Audit account management", "machine")
        assert check == "No auditing"
        yield
    finally:
        lgpo.set_computer_policy("SceNoApplyLegacyAuditPolicy", "Not Defined")
        lgpo.set_computer_policy("Audit account management", "Not Defined")

@pytest.fixture(scope="module")
def clean_adv_audit():
    # An `audit.csv` file will cause these tests to fail. Delete the `audit.csv`
    # files from the following locations:
    # - C:\Windows\security\audit
    # - C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit
    win_dir = os.environ.get("WINDIR")
    audit_csv_files = [
        r"{}\security\audit\audit.csv".format(win_dir),
        r"{}\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit\audit.csv".format(
            win_dir
        ),
    ]
    for audit_file in audit_csv_files:
        if os.path.exists(audit_file):
            os.remove(audit_file)
    yield

@pytest.fixture(scope="module")
def legacy_auditing_not_defined(lgpo):
    try:
        lgpo.set_computer_policy("SceNoApplyLegacyAuditPolicy", "Not Defined")
        check = lgpo.get_policy("SceNoApplyLegacyAuditPolicy", "machine")
        assert check == "Not Defined"
        yield
    finally:
        lgpo.set_computer_policy("SceNoApplyLegacyAuditPolicy", "Not Defined")

@pytest.mark.parametrize(
    "setting", ["No auditing", "Success", "Failure", "Success, Failure"]
)
def test_auditing(lgpo, setting, enable_legacy_auditing, clean_adv_audit):
    """
    Helper function to set an audit setting and assert that it was successful
    """
    lgpo.set_computer_policy("Audit account management", setting)
    result = lgpo.get_policy("Audit account management", "machine")
    assert result == setting

@pytest.mark.parametrize(
    "setting_name,setting",
    [
        ("Audit account management", "Success"),
        ("Audit Account Management", "Failure"),
    ],
)
def test_auditing_case_names(
    lgpo, setting_name, setting, enable_legacy_auditing, clean_adv_audit
):
    """
    Helper function to set an audit setting and assert that it was successful
    """
    lgpo.set_computer_policy(setting_name, setting)
    result = lgpo.get_policy(setting_name, "machine")
    assert result == setting

@pytest.mark.parametrize("setting", ["Enabled", "Disabled"])
def test_enable_legacy_audit_policy(
    lgpo, setting, legacy_auditing_not_defined, clean_adv_audit
):
    lgpo.set_computer_policy("SceNoApplyLegacyAuditPolicy", setting)
    result = lgpo.get_policy("SceNoApplyLegacyAuditPolicy", "machine")
    assert result == setting


import cv2
import numpy as np
import pandas as pd

import insightface
from insightface.app import FaceAnalysis
# from insightface.data import get_image as ins_get_image

app = FaceAnalysis(allowed_modules=['detection'])
app.prepare(ctx_id=0, det_size=(640, 640))

handler = insightface.model_zoo.get_model('C:/Users/hungt/.insightface/models/buffalo_l/w600k_r50.onnx')
handler.prepare(ctx_id=0)

path = "E:/PYTHON/pythonProject/insightface/python-package/insightface/data/Faces_database/khanhnt.csv"
embedding_vectors = pd.read_csv(path).values
name = " "

# define a video capture object
vid = cv2.VideoCapture(0)
while (True):
    # Capture the video frame
    # by frame
    ret, frame = vid.read()
    # Display the resulting frame
    faces = app.get(frame)
    if faces == []:
        cv2.imshow('frame', frame)
    else:
        if len(faces) > 1:
            cv2.putText(frame, 'Only one face in screen', (140, 240), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 0, 255), 1)
            cv2.imshow('frame', frame)

        else:
            rimg = app.draw_on(frame, faces, name)
            cv2.imshow('frame', rimg)

            embedding = handler.get(frame, faces[0])
            # embedding = app.get(frame)[-1]['embedding']
            for i in range(1, 6):
                distance = np.linalg.norm(embedding - embedding_vectors[:, i])
                if distance < 20:
                    name = (path.split("/")[-1]).split(".")[0]
                else:
                    name = " "
    # the 'q' button is set as the
    # quitting button you may use any
    # desired button of your choice
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()

# import cv2
# import numpy as np
# import insightface
# from insightface.app import FaceAnalysis
# from insightface.data import get_image as ins_get_image
#
# app = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
# app.prepare(ctx_id=0, det_size=(640, 640))
# img_opp = cv2.imread("E:/khanhnt/opposite.jpg")
# img_up = cv2.imread("E:/khanhnt/up.jpg")
# img_down = cv2.imread("E:/khanhnt/down.jpg")
# img_right = cv2.imread("E:/khanhnt/right.jpg")
# img_left = cv2.imread("E:/khanhnt/left.jpg")
#
# faces_opp = app.get(img_opp)
# faces_up = app.get(img_up)
# faces_down = app.get(img_down)
# faces_right = app.get(img_right)
# faces_left = app.get(img_left)
#
# print("opposite: ", faces_opp[0]['kps'])
# print("up: ", faces_up[0]['kps'])
# print("down: ", faces_down[0]['kps'])
# print("right: ", faces_right[0]['kps'])
# print("left: ", faces_left[0]['kps'])


import os
import yagmail
from twilio.rest import Client
import webbrowser
import requests
def send_mail(receiver_mail,reveiver_whatsapp_number):
    receiver = "add receiver mail"  # receiver email address
    body = "Attendence File"  # email body
    filename = "Attendance"+os.sep+"Attendance_2019-08-29_13-09-07.csv"  # attach the file
    filename = [os.path.join("Attendance", f) for f in os.listdir("Attendance")]
    #print(filename)
    print("You have entered your mail:"+receiver_mail)
    print("You have entered your whatsapp number:"+reveiver_whatsapp_number)
    file=filename[-1]
    #print(file)
    os.startfile(file)
    # mail information
    yag = yagmail.SMTP("use your mail", "use your mail password")

    # sent the mail
    yag.send(
        to=receiver,
        subject="Attendance Report",  # email subject
        contents=body,  # email body
        attachments=file,  # file attached
    )
    account_sid = 'twilio id'
    auth_token = 'twilio token'
    client = Client(account_sid, auth_token)
    message = client.messages.create(
                                  from_='whatsapp:twilio whatsapp number with country code',
                                  body=f"Your Attendance will be accepted, please check your mail",
                                  to='whatsapp:+91whatsappnumber'
                              )


import sys
from cx_Freeze import setup, Executable

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"

setup(  name = "ImageRenamer",
        version = "0.1",
        options = {"build_exe": {"include_msvcr": True}, "bdist_msi": {"add_to_path": True}},
        executables = [Executable("ImageRenamer.py", base=base)])


import numpy as np
import matplotlib.pyplot as plt
import math

def sign(x):
	if x >= 0:
		return 1
	else:
		return -1

def logistic(x):
	return 1 / (1 + math.exp(-x))

def err01(x, y):
	if sign(x) == y:
		return 0
	else:
		return 1

def err1(x, y):
	return max(0, 1 - y * x)

def err2(x, y):
	return pow(max(0, 1 - y * x), 2)

def err3(x, y):
	return max(0, -y * x)

def err4(x, y):
	return logistic(-y * x)

def err5(x, y):
	return math.exp(-y * x)

x_range = np.arange(-2, 2, 0.0001)
y_log = []
err_01 = []
err_1 = []
err_2 = []
err_3 = []
err_4 = []
err_5 = []
y = 1

for i in range(len(x_range)):
	y_log.append(logistic(x_range[i]))
	err_01.append(err01(x_range[i], y))
	err_1.append(err1(x_range[i], y))
	err_2.append(err2(x_range[i], y))
	err_3.append(err3(x_range[i], y))
	err_4.append(err4(x_range[i], y))
	err_5.append(err5(x_range[i], y))

plt.figure(figsize = (20, 7))
plt.subplot(321)
plt.plot(x_range, y_log, label = r'$\frac{1}{1 + \mathrm{exp(-w^Tx)}}$', color = 'red' )
plt.plot(x_range, err_01, label = r'$err0/1$' )
plt.legend()

plt.subplot(322)
plt.plot(x_range, err_1, label = r'$(max(0, 1-y\mathrm{\mathbf{w^Tx}}))^2$', color = 'blue' ) # max(0, 1 − ywT x)
plt.plot(x_range, err_01, label = r'$[[sign(\mathrm{\mathbf{w^Tx}} )\neq y]]$' )
plt.legend()

plt.subplot(323)
plt.plot(x_range, err_2, label = r'$(max(0, 1-y\mathrm{\mathbf{w^Tx}}))^2$', color = 'black' ) #  pow(max(0, 1 − ywT x), 2)
plt.plot(x_range, err_01, label = r'$[[sign(\mathrm{\mathbf{w^Tx}} )\neq y]]$' )
plt.legend()

plt.subplot(324)
plt.plot(x_range, err_3, label = r'$max(0, -y\mathrm{\mathbf{w^Tx}})$', color = 'yellow' ) # max(0, −ywT x)
plt.plot(x_range, err_01, label = r'$[[sign(\mathrm{\mathbf{w^Tx}} )\neq y]]$' )
plt.legend()

plt.subplot(325)
plt.plot(x_range, err_4, label = r'$\theta(-y\mathrm{\mathbf{w^Tx}})$', color = 'green' ) # θ(−ywT x)
plt.plot(x_range, err_01, label = r'$[[sign(\mathrm{\mathbf{w^Tx}} )\neq y]]$' )
plt.legend()

plt.subplot(326)
plt.plot(x_range, err_5, label = r'$exp(-y\mathrm{\mathbf{w^Tx}})$', color = '#AE0000' ) # exp(−ywT x)
plt.plot(x_range, err_01, label = r'$[[sign(\mathrm{\mathbf{w^Tx}} )\neq y]]$' )
plt.legend()

plt.savefig('hw3_2.png', dpi = 100)
plt.show()


import os
import argparse
from datetime import datetime
import logging
import json
import asyncio

from dotenv import load_dotenv

def get_args(host_default, port_default, token_default, username_default, message_default):
    '''Parses arguments from CLI.'''
    parser = argparse.ArgumentParser(description='Undergroung Chat CLI')
    parser.add_argument('--host', help='Host', type=str)
    parser.add_argument('--port', help='Port', type=int)
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--token', help='Token', type=str)
    group.add_argument('--username', help='Username', type=str)
    parser.add_argument('--message', help='Message', type=str)
    args = parser.parse_args()
    if args.username:
        token_default = None
    if args.token:
        username_default = None
    parser.set_defaults(
        host=host_default,
        port=port_default,
        token=token_default,
        username=username_default,
        message=message_default
        )
    args = parser.parse_args()
    return vars(args)

async def authorize(host, port, token, username, message):
    '''Authorizes a user and calls a submit_message() if user exists
     or calls register().'''

    try:
        reader, writer = await asyncio.open_connection(host, port)
        data = await reader.readline()
        logging.info('Received: {}'.format(data.decode()))
        writer.write('{}\n'.format(token).encode())
        logging.info('Sent token: {}'.format(token))
        data = await reader.readline()
        data_json = json.loads(data.decode())

        if data_json:
            logging.info('Received: {}'.format(data_json))
            await submit_message(reader, writer, message)
        elif username:
            logging.info('Go to register with username {}.'.format(username))
            await register(reader, writer, username)
            await submit_message(reader, writer, message)
        else:
            logging.info('Invalid token {}. Please check it.'.format(token))

    finally:
        writer.close()

async def register(reader, writer, username):
    '''Registers a new user in the chat and call submit_message().'''
    data = await reader.readline()
    logging.info(data.decode())
    writer.write('{}\n'.format(sanitize(username)).encode())
    data = await reader.readline()
    token = json.loads(data.decode())['account_hash']
    logging.info('Username "{}" registered with token {}.'.format(
        sanitize(username),
        token
        ))

def sanitize(text):
    return text.replace('\n', '').replace('\r', '')

async def submit_message(reader, writer, message):
    '''Submits a message to the chat.'''
    data = await reader.readline()
    logging.info('Received: {}'.format(data.decode()))
    message = '{}\n\n'.format(sanitize(message)).encode()
    writer.write(message)
    logging.info('Sent message: {}'.format(message.decode()))

if __name__ == '__main__':

    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s,%(msecs)d %(levelname)s: %(message)s',
        datefmt='%H:%M:%S',
        )

    load_dotenv()
    args = get_args(
            os.getenv('HOST'),
            os.getenv('PORT_WRITE'),
            os.getenv('TOKEN'),
            os.getenv('USERNAME'),
            os.getenv('MESSAGE')
            )

    loop = asyncio.get_event_loop()
    loop.run_until_complete(authorize(**args))
    loop.close()


import re

from .common import InfoExtractor
from ..utils import extract_attributes

class BFMTVBaseIE(InfoExtractor):
    _VALID_URL_BASE = r'https?://(?:www\.|rmc\.)?bfmtv\.com/'
    _VALID_URL_TMPL = _VALID_URL_BASE + r'(?:[^/]+/)*[^/?&#]+_%s[A-Z]-(?P<id>\d{12})\.html'
    _VIDEO_BLOCK_REGEX = r'(<div[^>]+class="video_block"[^>]*>)'
    BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_default/index.html?videoId=%s'

    def _brightcove_url_result(self, video_id, video_block):
        account_id = video_block.get('accountid') or '876450612001'
        player_id = video_block.get('playerid') or 'I2qBTln4u'
        return self.url_result(
            self.BRIGHTCOVE_URL_TEMPLATE % (account_id, player_id, video_id),
            'BrightcoveNew', video_id)

class BFMTVIE(BFMTVBaseIE):
    IE_NAME = 'bfmtv'
    _VALID_URL = BFMTVBaseIE._VALID_URL_TMPL % 'V'
    _TESTS = [{
        'url': 'https://www.bfmtv.com/politique/emmanuel-macron-l-islam-est-une-religion-qui-vit-une-crise-aujourd-hui-partout-dans-le-monde_VN-202010020146.html',
        'info_dict': {
            'id': '6196747868001',
            'ext': 'mp4',
            'title': 'Emmanuel Macron: "L\'Islam est une religion qui vit une crise aujourd’hui, partout dans le monde"',
            'description': 'Le Président s\'exprime sur la question du séparatisme depuis les Mureaux, dans les Yvelines.',
            'uploader_id': '876450610001',
            'upload_date': '20201002',
            'timestamp': 1601629620,
            'duration': 44.757,
            'tags': ['bfmactu', 'politique'],
            'thumbnail': 'https://cf-images.eu-west-1.prod.boltdns.net/v1/static/876450610001/5041f4c1-bc48-4af8-a256-1b8300ad8ef0/cf2f9114-e8e2-4494-82b4-ab794ea4bc7d/1920x1080/match/image.jpg',
        },
    }]

    def _real_extract(self, url):
        bfmtv_id = self._match_id(url)
        webpage = self._download_webpage(url, bfmtv_id)
        video_block = extract_attributes(self._search_regex(
            self._VIDEO_BLOCK_REGEX, webpage, 'video block'))
        return self._brightcove_url_result(video_block['videoid'], video_block)

class BFMTVLiveIE(BFMTVIE):  # XXX: Do not subclass from concrete IE
    IE_NAME = 'bfmtv:live'
    _VALID_URL = BFMTVBaseIE._VALID_URL_BASE + '(?P<id>(?:[^/]+/)?en-direct)'
    _TESTS = [{
        'url': 'https://www.bfmtv.com/en-direct/',
        'info_dict': {
            'id': '5615950982001',
            'ext': 'mp4',
            'title': r're:^le direct BFMTV WEB \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
            'uploader_id': '876450610001',
            'upload_date': '20171018',
            'timestamp': 1508329950,
        },
        'params': {
            'skip_download': True,
        },
    }, {
        'url': 'https://www.bfmtv.com/economie/en-direct/',
        'only_matching': True,
    }]

class BFMTVArticleIE(BFMTVBaseIE):
    IE_NAME = 'bfmtv:article'
    _VALID_URL = BFMTVBaseIE._VALID_URL_TMPL % 'A'
    _TESTS = [{
        'url': 'https://www.bfmtv.com/sante/covid-19-un-responsable-de-l-institut-pasteur-se-demande-quand-la-france-va-se-reconfiner_AV-202101060198.html',
        'info_dict': {
            'id': '202101060198',
            'title': 'Covid-19: un responsable de l\'Institut Pasteur se demande "quand la France va se reconfiner"',
            'description': 'md5:947974089c303d3ac6196670ae262843',
        },
        'playlist_count': 2,
    }, {
        'url': 'https://www.bfmtv.com/international/pour-bolsonaro-le-bresil-est-en-faillite-mais-il-ne-peut-rien-faire_AD-202101060232.html',
        'only_matching': True,
    }, {
        'url': 'https://www.bfmtv.com/sante/covid-19-oui-le-vaccin-de-pfizer-distribue-en-france-a-bien-ete-teste-sur-des-personnes-agees_AN-202101060275.html',
        'only_matching': True,
    }, {
        'url': 'https://rmc.bfmtv.com/actualites/societe/transports/ce-n-est-plus-tout-rentable-le-bioethanol-e85-depasse-1eu-le-litre-des-automobilistes-regrettent_AV-202301100268.html',
        'info_dict': {
            'id': '6318445464112',
            'ext': 'mp4',
            'title': 'Le plein de bioéthanol fait de plus en plus mal à la pompe',
            'description': None,
            'uploader_id': '876630703001',
            'upload_date': '20230110',
            'timestamp': 1673341692,
            'duration': 109.269,
            'tags': ['rmc', 'show', 'apolline de malherbe', 'info', 'talk', 'matinale', 'radio'],
            'thumbnail': 'https://cf-images.eu-west-1.prod.boltdns.net/v1/static/876630703001/5bef74b8-9d5e-4480-a21f-60c2e2480c46/96c88b74-f9db-45e1-8040-e199c5da216c/1920x1080/match/image.jpg'
        }
    }]

    def _real_extract(self, url):
        bfmtv_id = self._match_id(url)
        webpage = self._download_webpage(url, bfmtv_id)

        entries = []
        for video_block_el in re.findall(self._VIDEO_BLOCK_REGEX, webpage):
            video_block = extract_attributes(video_block_el)
            video_id = video_block.get('videoid')
            if not video_id:
                continue
            entries.append(self._brightcove_url_result(video_id, video_block))

        return self.playlist_result(
            entries, bfmtv_id, self._og_search_title(webpage, fatal=False),
            self._html_search_meta(['og:description', 'description'], webpage))


import logging
from datetime import datetime

import sqlalchemy

log = logging.getLogger()

def get_sqlalchemy_url(vendor, user, pwd, host, port, dbname):
    return f"{vendor}://{user}:{pwd}@{host}:{port}/{dbname}"

def select_no_label_qna_contents(url, range_lower__gte, range_upper_lt):
    datetime.strptime(range_lower__gte, "%Y-%m-%d")
    datetime.strptime(range_upper_lt, "%Y-%m-%d")

    query = f"""
    select
        id,
        contents
    from
        sample.qna
    where
        label is null
        and contents is not null
        and timezone('kst', created_at) >= '{range_lower__gte}'
        and timezone('kst', created_at) < '{range_upper_lt}'
    """

    with sqlalchemy.create_engine(url).connect() as connection:
        ret = connection.execute(sqlalchemy.text(query))
        log.info("Query: %s." % query)

        rows = ret.fetchall()

        data = {}
        for row in rows:
            row = dict(row)
            for col, value in row.items():
                if col not in data:
                    data[col] = [value]
                else:
                    data[col].append(value)
        return data

def update_qna_contents_label(url, label, ids):
    ret = 0
    if len(ids) > 0:
        query = f"""
            update
                sample.qna
            set
                label = '{label}'
            where
                id in {tuple(ids) if len(tuple(ids)) > 1 else '(%s)' % ids[0]}
        """
        with sqlalchemy.create_engine(url).begin() as transaction:
            ret = transaction.execute(sqlalchemy.text(query)).rowcount
            log.info("Query: %s, rows: %s." % (query, ret))
    return ret


import smtplib, ssl
from contextlib import contextmanager
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from ..config import Settings

context = ssl.create_default_context()

settings = Settings()

def send_email_service(receiver_email: str, message: str) -> None:
    with smtplib.SMTP_SSL(
        settings.smtp_address, settings.smtp_port, context=context
    ) as server:
        server.login(settings.smtp_email, settings.smtp_password)

        server.sendmail(settings.smtp_email, receiver_email, message)

def create_message(
    subject: str, sender_email: str, receiver_email: str, text: str, html: str = None
) -> MIMEMultipart:

    message = MIMEMultipart()
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email

    message.attach(MIMEText(text, "plain"))
    if html is not None:
        message.attach(MIMEText(html, "html"))

    return message


import modules as mx
import sys
import os
import importlib
homedir = os.getcwd() + r'/files/library/'
sys.path.append(homedir)
data = mx.Data()
body = mx.Body()
from buttons import *
importlib.reload(sys.modules['buttons'])
from header import *
importlib.reload(sys.modules['header'])
from content import *
importlib.reload(sys.modules['content'])
from tiles import *
importlib.reload(sys.modules['tiles'])

data.title = "Designed By Dre | About"

### HEADER ###
buttons = list()
button_names = ['About Me','Website Design','Data Mining','Audio Production','Other Services','Contact Me']
button_actions = ["redirect('https://www.drebarrera.com/');", "redirect('https://www.drebarrera.com/');", "redirect('https://www.drebarrera.com/');", "redirect('https://www.drebarrera.com/');", "redirect('https://www.drebarrera.com/');", "redirect('https://www.drebarrera.com/');"]
for x in range(len(button_names)):
    buttons.append(('func',button_names[x],button_actions[x]))
header = Header(branding='center',menubar='center')
header.logo_name='designedbydre.png'
header.logo_height='100px'
header.site_name='designed\nby\ndre'
header.buttons=buttons
header.primary_color='rgb(250,250,250)'
header.accent_color='#005580'
header.button_style='rounded'
header.button_colors='rgb(250,250,250) #005580'
header.button_width='auto 50px'
header.button_padding='10px'
header.nav_switch='750'
header.build()

### OBJECTS
page = Page()
slide1 = Slide()
slide1title = mx.T()
slide1emoji = mx.T()
slide1caption = mx.T()
slide1list = mx.X()
slide1image = mx.Image()
slide1subcaption = mx.T()
slide1button = Button('link','Portfolio',link_url="https://www.drebarrera.com",radius='rounded')
slide2 = Slide()
slide2tileSlide = Tile_Slide()
slide2tileStatic = Tile()
slide2tileWeb = Tile()
slide2tileMine = Tile()
slide2tileAudio = Tile()
slide2tileOther = Tile()
slide2overlay = mx.C()
'''slide2title_c = mx.C()
slide2title = mx.T()
slide2supertitle = mx.T()
slide2leftsubtitle = mx.T()
slide2right = mx.T()
slide2iconlist = IconList()'''

### CONTENT
body.content = [header, page]
page.content = [slide1]

# SLIDE 1
slide1.content = [[[slide1image,slide1title,slide1emoji]],[[slide1caption,slide1list]],[[slide1subcaption, slide1button]]]
slide1image.src = 'images/profile.jpg'
slide1title.content = "Hi, I'm Dre!"
slide1emoji.content = "👋"
slide1caption.content = "Welcome to my site! You are most likely here because you are looking for design services. More information can be found below, but first let me tell you a little about myself!"
slide1list.content = "

I am finishing a degree in Computer Engineering at Purdue University.

8 years of experience in graphic design, website development, and programming.

Graduated high school at 16 years old, exceeding testing standards.

Reliable and ambitious hard worker who is dedicated to getting the job done with minimal hassel!

"
slide1subcaption.content = "For more about me, visit my"

### PROPERTIES
#body.background_color = 'rgb(50,50,50)'
# SLIDE 1
slide1.background = 'linear-gradient(175deg, rgb(250,250,250) 0%, #edf9fe 55%, #76aac2 85%, #36687d 100%)'
slide1.id = 'slide1'
slide1title.type = 'h2'
slide1emoji.type = 'h2'
slide1emoji.id = 'slide1emoji'
slide1caption.id = 'slide1caption'
slide1image.id = 'slide1image'
slide1subcaption.color = 'white'
slide1subcaption.font_weight = '300'
slide1button.id = 'slide1button'
slide1button.primary = '#F35046'
slide1button.accent = 'white'

### BUILD
slide1.build()
slide2.build()


#!/usr/bin/env python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from common.ipaddrchanges import *
from canari.framework import configure #, superuser
from common.entities import Interface
from canari.maltego.message import Field
from canari.maltego.entities import IPv4Address

__author__ = 'catalyst256'
__copyright__ = 'Copyright 2013, Watcher Project'
__credits__ = []

__license__ = 'GPL'
__version__ = '0.1'
__maintainer__ = 'catalyst256'
__email__ = 'catalyst256@gmail.com'
__status__ = 'Development'

__all__ = [
    'dotransform'
]

#@superuser
@configure(
    label='Watcher - ARP scan',
    description='Performs an arp scan to determine devices on network',
    uuids=[ 'Watcher.v2.arp_scan_from_interface' ],
    inputs=[ ( 'Watcher', Interface ) ],
    debug=True
)
def dotransform(request, response):

    iface = request.value
    conf.iface = iface
    subnet = ''
    network = ''

    for x in conf.route.routes:
        if x[3] == iface and x[2] == '0.0.0.0':
            subnet = x[1]
            network = x[0]

    subnet = subnetAddress(subnet)
    cidr = cidr2subnet(subnet)
    network = networkAddress(network)

    ans, uans = arping(network + '/' + str(cidr), verbose=0)
    for send, rcv in ans:
        e = IPv4Address(rcv[ARP].psrc)
        e += Field('ethernet.hwaddr', rcv[Ether].src, displayname='Hardware Address')
        e.internal = True
        response += e
    return response