# Import the dependencies.
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime as dt

#################################################
# Database Setup
#################################################

engine = create_engine(r"sqlite:///C:\Users\MichaelaJohnson\OneDrive\Desktop\Edu\challenges\SQLalchemy_challenge\Starter_Code\Starter_Code\Resources\hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()

# reflect the tables
Base.prepare(autoload_with=engine)

session = Session(bind=engine)

# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station

#################################################
# Flask Setup
#################################################
app = Flask(__name__)

#################################################
# Flask Routes
#################################################

@app.route("/")
def welcome():
    print("Server requesting welcome")
    return (
        f"Welcome to the Hawaii Climate Homepage
"
        f"Available Routes:
"
        f"/api/v1.0/precipitation
"
        f"/api/v1.0/station
"
        f"/api/v1.0/tobs= dt.date(2016, 8, 23)).all()
    session.close()
    prcp_list = []
    for date, prcp in results_prcp:
        prcp_dict= {}
        prcp_dict["date"] = date
        prcp_dict["prcp"] = prcp
        prcp_list.append(prcp_dict)
        #List of precipitation data from 2016-8-23 to 2017-8-23
    return jsonify(prcp_list)

@app.route("/api/v1.0/station")
def station():
    results_station = session.query(Station.station).all()
    session.close()
    stations = list(np.ravel(results_station))
    #List of all Stations
    return jsonify(stations)

@app.route("/api/v1.0/tobs")
def tobs():
    results_tobs = session.query(Measurement.date, Measurement.tobs).filter(Measurement.station == 'USC00519281').filter(Measurement.date >= dt.date(2016, 8, 23)).all()
    session.close()
    temp_list = []
    for date, tobs in results_tobs:
        temp_dict = {}
        temp_dict["date"] = date
        temp_dict["tobs"] = tobs
        temp_list.append(temp_dict)
    #List of temperatures for Station USC00519281 from 2016-8-23 to 2017-8-23
    return jsonify(temp_list)

@app.route("/api/v1.0/start")
def start():
    sel = (Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs))
    results_start = session.query(*sel).filter(Measurement.date == dt.date(2010, 1, 1)).order_by(Measurement.date).all()
    session.close()
    start_data = list(np.ravel(results_start))
    #Min, Average, and Max temperature data from 2010-01-01
    return jsonify(start_data)

@app.route("/api/v1.0/end")
def end():
    sel = (Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs))
    results_end = session.query(*sel).filter(Measurement.date == dt.date(2017, 8, 23)).order_by(Measurement.date).all()
    session.close()
    end_data = list(np.ravel(results_end))
    #Min, Average, and Max temperature data from 2017-08-23
    return jsonify(end_data)

if __name__ == "__main__":
    app.run(debug=True)


from setuptools import setup, find_packages
import os

version = '0.8.dev0'

setup(name='adi.dropdownmenu',
      version=version,
      description="A dropdownmenu that is configurable for site administrators and mirrows your folderstructures.",
      long_description=open("README.txt").read() + "\n" +
                       open(os.path.join("docs", "HISTORY.txt")).read(),
      # Get more strings from
      # http://pypi.python.org/pypi?:action=list_classifiers
      classifiers=[
        "Framework :: Plone",
        "Programming Language :: Python",
        ],
      keywords='',
      author='Ida Ebkes',
      author_email='contakt@ida-ebkes.eu',
      url='http://svn.plone.org/svn/collective/adi.dropdownmenu',
      license='GPL',
      packages=find_packages(exclude=['ez_setup']),
      namespace_packages=['adi'],
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          'setuptools',
          'Products.ContentWellPortlets',
          'collective.portlet.sitemap',
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-

      [z3c.autoinclude.plugin]
      target = plone
      """,
      setup_requires=["PasteScript"],
      paster_plugins=["ZopeSkel"],
      )


"""The code editor of GraphDonkey, with a few features:

- Syntax Highlighting
- Error Highlighting
- Line Numbers
    Based on https://stackoverflow.com/questions/2443358/how-to-add-lines-numbers-to-qtextedit
- Selection/Line Events (Duplicate, Copy, Cut, Comment/Uncomment, Auto-Indent, Indent/Unindent...)
- Parenthesis Matching
    Based on QtQuarterly 31: https://doc.qt.io/archives/qq/QtQuarterly31.pdf
- Auto-Expand Squiggly and Square brackets

Author: Randy Paredis
Date:   12/14/2019
"""
from dbm import error

from PyQt5 import QtGui, QtWidgets, QtCore

from main.extra import Constants, left
from main.extra.IOHandler import IOHandler
from main.editor.Highlighter import BaseHighlighter
from main.extra.GraphicsView import GraphicsView
from main.Preferences import bool
from main.plugins import PluginLoader
from main.editor.Intellisense import Types, ICONS
import os

pluginloader = PluginLoader.instance()
Config = IOHandler.get_preferences()

class StatusBar(QtWidgets.QStatusBar):
    def __init__(self, wrapper, parent=None):
        super(StatusBar, self).__init__(parent)
        self.wrapper = wrapper
        self.statusMessage = QtWidgets.QLabel("")
        self.statusMessage.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignBaseline)

        self.positionIndicator = QtWidgets.QLabel(":")
        self.positionIndicator.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)

        self.leCombo = QtWidgets.QComboBox()
        self.seps = {
            "Posix (LF)": '\n',
            "Mac OS [Pre-OSX] (CR)": '\r',
            "Windows (CRLF)": '\r\n'
        }
        for name in self.seps:
            self.leCombo.addItem(name, self.seps[name])
        self.setLineSep(os.linesep)

        self.encCombo = QtWidgets.QComboBox()
        self.encCombo.addItem("UTF-8", "utf-8")
        self.encCombo.addItem("UTF-16", "utf-16")
        self.encCombo.addItem("ASCII", "ascii")
        self.encCombo.addItem("ISO-8859-1", "latin1")

        self.ftCombo = QtWidgets.QComboBox()

        rdr = QtWidgets.QLabel("Render with:")
        rdr.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.rendererCombo = QtWidgets.QComboBox()

        self.addPermanentWidget(QtWidgets.QLabel(" "))
        self.addPermanentWidget(self.statusMessage, 7)
        self.addPermanentWidget(self.positionIndicator, 1)
        self.addPermanentWidget(self.leCombo, 1)
        self.addPermanentWidget(self.encCombo, 1)
        self.addPermanentWidget(self.ftCombo, 0)
        self.addPermanentWidget(rdr, 1)
        self.addPermanentWidget(self.rendererCombo, 0)
        self.addPermanentWidget(QtWidgets.QLabel(" "))

    def setLineSep(self, sep):
        seps = {self.seps[n]: n for n in self.seps}
        self.leCombo.setCurrentText(seps.get(sep, ""))

class EditorWrapper(QtWidgets.QWidget):
    def __init__(self, parent):
        super(EditorWrapper, self).__init__(parent)
        self._layout = QtWidgets.QGridLayout()
        self.editor = CodeEditor(self)
        self.mainwindow = parent
        self.types = []
        self.statusBar = StatusBar(self)
        self.filetype = self.statusBar.ftCombo
        self.engine = self.statusBar.rendererCombo
        self.linesep = self.statusBar.leCombo
        self.encoding = self.statusBar.encCombo

        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(self.editor, 0, 0, 1, -1)
        self.filetype.currentIndexChanged.connect(self.alter)
        self.setTypes()
        self.setLayout(self._layout)

    def setTypes(self):
        self.types = pluginloader.getFileTypes()
        txt = self.filetype.currentText()
        self.filetype.clear()
        for type in self.types:
            name, klass = self.types[type]
            self.filetype.addItem(name, klass)
        # TODO: determine filetype based on extension
        self.filetype.setCurrentText(txt)

    def alter(self, idx):
        self.engine.clear()
        if idx >= 0:
            data = self.filetype.itemData(idx)
            self.editor.alter(data(self.editor.document(), self.editor))
            self.editor.highlighter.rehighlight()
            ens = pluginloader.getEnginesForFileType(self.filetype.itemText(idx))
            for en in ens:
                self.engine.addItem(en)
            self.engine.setCurrentText(Config.value("view/engine"))
        self.mainwindow.displayGraph()

    def setType(self, type):
        self.filetype.setCurrentText(self.types[type][0])

class CodeEditor(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.mainwindow = parent.parent()
        self.wrapper = parent
        self.lineNumberArea = LineNumberArea(self)

        self.undoAvailable.connect(self.mainwindow.setUndoEnabled)
        self.redoAvailable.connect(self.mainwindow.setRedoEnabled)

        self.blockCountChanged.connect(self.lineNrChanged)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.positionChangedSlot)
        self.textChanged.connect(self.textChangedSlot)

        self.updateLineNumberAreaWidth()
        self.highlightCurrentLine()
        self.highlighter = BaseHighlighter(self.document(), self)

        self.matches = []
        self.errors = []

        self.setMouseTracking(True)

        self.filename = ""
        self.filecontents = ""

        self.completer = None
        self.setCompleter()

        self.treeView = None

        # Optimize performance of user experience; big files are slow when editing every change event
        self.stTimer = QtCore.QTimer(self)
        self.stTimer.setSingleShot(True)
        self.stTimer.timeout.connect(self.stoppedTyping)

    def textChangedSlot(self):
        txt = self.toPlainText()
        if bool(Config.value("editor/emptyline")) and not txt.endswith(Constants.LINE_ENDING) \
                and not txt.endswith('\n'):
            curs = self.textCursor()
            curs.movePosition(QtGui.QTextCursor.End)
            curs.insertText(Constants.LINE_ENDING)
            curs = self.textCursor()
            curs.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)
            if len(curs.selectedText()) == 0:
                curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
                self.setTextCursor(curs)

    def alter(self, highlighter):
        self.highlighter.deleteLater()
        self.highlighter = highlighter

    def convert(self, engine):
        curs = self.textCursor()
        return self.highlighter.parser.convert(self.toPlainText(), engine,
                                               line=curs.block().blockNumber() + 1, col=curs.columnNumber())

    def stoppedTyping(self):
        self.highlighter.storeErrors()
        if bool(Config.value("editor/useParser", True)):
            self.highlightErrors()

    def positionChangedSlot(self):
        self.stTimer.start(int(Config.value("editor/autoreparse", 100)))
        if bool(Config.value("editor/highlightCurrentLine")):
            self.highlightCurrentLine()
        if bool(Config.value("editor/parentheses")):
            self.matchBrackets()
        self.highlightMatches()
        self.updateIndicator()
        self.mainwindow.updateTitle()

    def lineNrChanged(self):
        self.updateLineNumberAreaWidth()
        self.highlighter.rehighlight()

    def contextMenuEvent(self, event: QtGui.QContextMenuEvent):
        menu = QtWidgets.QMenu(self)
        menu.addAction(self.mainwindow.action_Undo)
        menu.addAction(self.mainwindow.action_Redo)
        menu.addSeparator()
        menu.addAction(self.mainwindow.action_Copy)
        menu.addAction(self.mainwindow.action_Paste)
        menu.addAction(self.mainwindow.action_Cut)
        menu.addAction(self.mainwindow.action_Delete)
        menu.addSeparator()
        menu.addAction(self.mainwindow.action_Select_All)
        menu.exec_(event.globalPos())

    def isSaved(self):
        """Returns True if the file was saved."""
        txt = self.toPlainText()
        if self.filename != "":
            return txt == self.filecontents
        if bool(Config.value("editor/emptyline")):
            txt = txt[:-len(os.linesep)]
        return txt == ""

    def save(self):
        self.filecontents = self.toPlainText()
        if self.treeView is not None and self.treeView.isVisible():
            self.viewParseTree(False)

    def clearContents(self):
        self.selectAll()
        self.insertPlainText("")

    def clearFile(self):
        self.filename = ""
        self.filecontents = ""

    def setCompleter(self):
        self.completer = QtWidgets.QCompleter(self)
        table = QtWidgets.QTableView()
        table.horizontalHeader().hide()
        table.verticalHeader().hide()
        table.setShowGrid(False)
        table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.completer.setPopup(table)
        self.completer.setModel(QtGui.QStandardItemModel())
        self.completer.setFilterMode(QtCore.Qt.MatchContains)
        self.completer.setModelSorting(QtWidgets.QCompleter.CaseInsensitivelySortedModel)
        self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer.setWrapAround(False)
        self.completer.setWidget(self)
        self.completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)

    def insertCompletion(self, completion):
        comp, _ = self.highlighter.parser.visitor.completer.get(completion)
        if len(comp) == 0:
            text = completion
        else: # In case of snippets, use the value (not the name)
            text = comp[0][0] if comp[0][2] is None else comp[0][2]

        cursor = self.textCursor()
        cursor.select(QtGui.QTextCursor.WordUnderCursor)
        cursor.insertText(text)
        self.setTextCursor(cursor)

    def encapsulateText(self, o, c):
        curs = self.textCursor()
        s = curs.selectionStart()
        e = curs.selectionEnd()
        curs.beginEditBlock()
        curs.setPosition(s)
        self.setTextCursor(curs)
        self.insertPlainText(o)

        mc = True
        if s == e:
            ci = curs.block().userData().indexOf(curs.positionInBlock())
            cpos = self.getClosingBracketPos((o, c), curs.block(), ci)
            if cpos >= 0:
                curs.setPosition(cpos)
                oi = curs.block().userData().indexOf(curs.positionInBlock())
                opos = self.getOpeningBracketPos((o, c), curs.block(), oi - 1)
                if opos == s or opos == -1:
                    mc = False
        if mc:
            curs.setPosition(e + len(o))
            self.setTextCursor(curs)
            self.insertPlainText(c)
        curs.setPosition(s + len(o))
        curs.setPosition(e + len(o), QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def keyPressEvent(self, event: QtGui.QKeyEvent):
        paired = pluginloader.getPairedBrackets(self.wrapper.filetype.currentText())

        if self.completer.popup().isVisible():
            if event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, QtCore.Qt.Key_Tab]:
                completion = self.completer.popup().currentIndex().data(QtCore.Qt.UserRole)
                self.insertCompletion(completion)
                self.completer.popup().hide()
            elif event.key() == QtCore.Qt.Key_Escape:
                self.completer.popup().hide()
            else:
                QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
                self.completer.popup().hide()
                self.complete()
        elif event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return]:
            self.insertPlainText(Constants.LINE_ENDING)
            self.autoIndent()
            cursor = self.textCursor()
            cursor.beginEditBlock()
            pos = cursor.position()
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText().lstrip()
            cursor.setPosition(pos)
            cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
            if len(txt) > 0 and txt[0] in [x[1] for x in paired] and len(cursor.selectedText()) == 0:
                cursor.setPosition(pos)
                cursor.insertText(Constants.LINE_ENDING)
                cursor.movePosition(QtGui.QTextCursor.Up, QtGui.QTextCursor.KeepAnchor)
                self.setTextCursor(cursor)
                self.autoIndent()
                cursor.setPosition(pos)
                cursor.movePosition(QtGui.QTextCursor.EndOfLine)
                self.setTextCursor(cursor)
            cursor.endEditBlock()
        elif event.key() == QtCore.Qt.Key_Home:
            cursor = self.textCursor()
            end = cursor.selectionEnd()
            cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            if len(txt.strip()) == 0 != len(txt):
                cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            else:
                cursor.movePosition(QtGui.QTextCursor.StartOfLine)
                cursor.movePosition(QtGui.QTextCursor.NextWord)
            cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
        elif event.key() == QtCore.Qt.Key_Backspace:
            if bool(Config.value("editor/pairedBrackets")):
                curs = self.textCursor()
                s = curs.selectionStart()
                e = curs.selectionEnd()
                if s == e:
                    curs.movePosition(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
                    prev = curs.selectedText()
                    curs.setPosition(s)
                    curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                    next = curs.selectedText()
                    curs.setPosition(s)
                    if (prev, next) in paired:
                        curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
                        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor, 2)
                        self.setTextCursor(curs)
            QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
        elif event.key() not in [QtCore.Qt.Key_Delete, QtCore.Qt.Key_Tab]:
            if bool(Config.value("editor/pairedBrackets")):
                et = event.text()
                if et in [x[0] for x in paired]:    # OPEN
                    pair = [x for x in paired if et in x][0]
                    if pair[0] == pair[1]:
                        curs = self.textCursor()
                        s = curs.selectionStart()
                        e = curs.selectionEnd()
                        if s == e:
                            curs.setPosition(e)
                            curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                            txt = curs.selectedText()
                            if txt != pair[0]:
                                self.encapsulateText(*pair)
                            else:
                                curs.setPosition(e)
                                curs.movePosition(QtGui.QTextCursor.NextCharacter)
                                self.setTextCursor(curs)
                        else:
                            self.encapsulateText(*pair)
                    else:
                        self.encapsulateText(*pair)
                elif et in [x[1] for x in paired]:  # CLOSE
                    pair = [x for x in paired if et in x][0]
                    curs = self.textCursor()
                    s = curs.selectionStart()
                    e = curs.selectionEnd()
                    if s == e:
                        curs.setPosition(e)
                        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
                        txt = curs.selectedText()
                        if txt != pair[1]:
                            self.insertPlainText(pair[1])
                        else:
                            curs.setPosition(e)
                            curs.movePosition(QtGui.QTextCursor.NextCharacter)
                            self.setTextCursor(curs)
                    else:
                        self.insertPlainText(pair[1])
                else:
                    QtWidgets.QPlainTextEdit.keyPressEvent(self, event)
            else:
                QtWidgets.QPlainTextEdit.keyPressEvent(self, event)

    def event(self, event: QtCore.QEvent):
        if event.type() == QtCore.QEvent.ShortcutOverride:
            return False
        return QtWidgets.QPlainTextEdit.event(self, event)

    def setText(self, text):
        self.document().setPlainText(text)

    def mouseMoveEvent(self, event: QtGui.QMouseEvent):
        pos = event.pos()
        cursor = self.cursorForPosition(pos)
        cursor.select(QtGui.QTextCursor.WordUnderCursor)
        tpos = cursor.position()
        for start, size, msg in self.errors:
            if start <= tpos <= start + size:
                QtWidgets.QToolTip.showText(event.globalPos(), msg, self)
        return QtWidgets.QPlainTextEdit.mouseMoveEvent(self, event)

    def delete(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt == "":
            cursor.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
        self.insertPlainText("")

    def _cc(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt == "":
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)

    def copy(self):
        self._cc()
        QtWidgets.QPlainTextEdit.copy(self)

    def cut(self):
        self._cc()
        QtWidgets.QPlainTextEdit.cut(self)

    def duplicate(self):
        cursor = self.textCursor()
        txt = cursor.selectedText()
        posE = cursor.selectionEnd()
        if txt == "":   # Duplicate line
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            cursor.insertText(txt + Constants.LINE_ENDING + txt)
        else:           # Duplicate selection
            cursor.insertText(txt + txt)
            cursor.setPosition(posE)
            cursor.setPosition(posE + len(txt), QtGui.QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)

    def lines(self, func, state=None):
        cursor = self.textCursor()
        posS = cursor.selectionStart()
        posE = cursor.selectionEnd()

        cursor.beginEditBlock()
        cursor.setPosition(posS)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine)
        cursor.setPosition(posE, QtGui.QTextCursor.KeepAnchor)
        cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        otxt = cursor.selectedText()
        txt = otxt.split(Constants.LINE_ENDING)
        add = 0
        for i in range(len(txt)):
            state, line = func(txt[i], state)
            if i == 0:
                add = len(line) - len(txt[i])
            txt[i] = line
        ntxt = Constants.LINE_ENDING.join(txt)
        cursor.setPosition(posS)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine)
        cursor.setPosition(posE, QtGui.QTextCursor.KeepAnchor)
        if cursor.selectedText() == Constants.LINE_ENDING or posS == posE:
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        cursor.insertText(ntxt)
        cursor.setPosition(posS + add)
        cursor.setPosition(posE + len(ntxt) - len(otxt), QtGui.QTextCursor.KeepAnchor)
        cursor.endEditBlock()
        self.setTextCursor(cursor)

        return cursor

    def comment(self):
        # TODO: identify indents before/after comment signs
        def cmnt(line, state):
            txt = line
            if txt[:2] == "//" and state in [True, None]:
                txt = txt[2:]
                state = True
            elif len(txt) > 0 and txt[0] == "#" and state in [True, None]:
                txt = txt[1:]
                state = True
            elif state in [False, None]:
                txt = "//" + txt
                state = False
            return state, txt

        self.lines(cmnt)

    def indent(self):
        tab = '\t'
        if bool(Config.value("editor/spacesOverTabs")):
            tab = ' ' * int(Config.value("editor/tabwidth"))

        def func(line, state):
            return state, tab + line

        cursor = self.textCursor()
        txt = cursor.selectedText()
        if txt != "":
            self.lines(func)
        else:
            self.insertPlainText(tab)

    def unindent(self):
        # 1) take all left whitespace;
        # 2) replace tabs with spaces (w.r.t. Config);
        # 3) remove 1 character;
        # 4) reduce string length until length % tablength == 0;
        # 5) this is new whitespace length
        ws = (' ', '\t')
        useSpaces = bool(Config.value("editor/spacesOverTabs"))
        tablength = int(Config.value("editor/tabwidth"))

        def func(line, state):
            txt = line
            lft = left(txt, ws)
            if useSpaces:
                lft = lft.replace("\t", " " * tablength)
                if len(lft) > 0:
                    lft = lft[:-1]
                lft = lft[:(len(lft) // tablength) * tablength]
                txt = lft + txt.lstrip()
            else:
                if len(lft) > 0 and lft[-1] in ws:
                    txt = lft[:-1] + txt.lstrip()
            return state, txt

        self.lines(func)

    def autoIndent(self):
        cursor = self.textCursor()
        posS = cursor.selectionStart()
        cursor.setPosition(posS)
        s = cursor.movePosition(QtGui.QTextCursor.Up)
        linenr = 0
        indent = 0
        tw = int(Config.value("editor/tabwidth"))
        sot = bool(Config.value("editor/spacesOverTabs"))
        if s:
            linenr = cursor.blockNumber() + 1
            cursor.movePosition(QtGui.QTextCursor.StartOfLine)
            cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
            txt = cursor.selectedText()
            for c in txt:
                if c == ' ':
                    indent += 1
                elif c == '\t':
                    indent += tw
                else:
                    break

        if not sot:
            indent //= tw

        vis = self.highlighter.parser.visitor

        def indentLine(line, state):
            vobt = vis.obtain(state, linenr)
            txt = line.lstrip()
            if sot:
                inc = indent + (vobt * tw)
                line = (" " * inc) + txt
            else:
                inc = indent + vobt
                line = ("\t" * inc) + txt
            state += 1
            return state, line

        self.lines(indentLine, linenr + 1)

    def moveUp(self):
        curs = self.textCursor()
        curs.beginEditBlock()
        start = curs.selectionStart()
        end = curs.selectionEnd()
        curs.setPosition(start)
        curs.movePosition(QtGui.QTextCursor.PreviousBlock)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.movePosition(QtGui.QTextCursor.PreviousCharacter)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
        curs.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        txt = curs.selectedText()
        curs.removeSelectedText()
        start -= len(txt)
        end -= len(txt)
        curs.setPosition(end)
        curs.movePosition(QtGui.QTextCursor.EndOfLine)
        curs.insertText(txt)
        curs.setPosition(start)
        curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def moveDown(self):
        curs = self.textCursor()
        curs.beginEditBlock()
        start = curs.selectionStart()
        end = curs.selectionEnd()
        curs.setPosition(end)
        curs.movePosition(QtGui.QTextCursor.NextBlock)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
        txt = curs.selectedText()
        curs.removeSelectedText()
        curs.setPosition(start)
        curs.movePosition(QtGui.QTextCursor.StartOfLine)
        curs.insertText(txt)
        start += len(txt)
        end += len(txt)
        curs.setPosition(start)
        curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
        curs.endEditBlock()
        self.setTextCursor(curs)

    def complete(self):
        cursor = self.textCursor()
        cursor.setPosition(cursor.selectionStart())
        cursor.movePosition(QtGui.QTextCursor.StartOfWord, QtGui.QTextCursor.KeepAnchor)
        prefix = cursor.selectedText()

        ctr = self.highlighter.parser.visitor.completer

        # Reload the completion set
        ctr.clear()
        self.highlighter.storeErrors()

        tp = self.wrapper.filetype.currentText()
        for p in pluginloader.get():
            snps = p.types.get(tp, {}).get("snippets", {})
            for n in snps:
                ctr.add(n, Types.SNIPPET, snps[n])
        snps = self.mainwindow.snippets.snippets
        for n in snps.get(tp, {}):
            ctr.add(n, Types.SNIPPET, snps[tp].get(n, None))
        completions, prefix = ctr.get(prefix)

        mdl = self.completer.model()
        mdl.clear()
        for px, ty, v in completions:
            if px == prefix: continue
            pth = [px.index(x) for x in prefix]
            itc = "".join(["<b>%s</b>" % px[s] if s in pth else px[s] for s in range(len(px))])
            ite = ""
            if v is not None:
                ite = "<div align='right'>%s </div>" % v
            it = QtGui.QStandardItem(itc)
            ico = ICONS[ty]
            if ico is not None:
                it.setIcon(ico)
            it.setData(px, QtCore.Qt.UserRole)
            mdl.appendRow([it, QtGui.QStandardItem(ite)])

        if len(completions) == 0:
            return

        if self.completer.popup().currentIndex().row() == -1 or prefix != self.completer.completionPrefix():
            self.completer.setCompletionPrefix(prefix)
            self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0))

        cr = self.cursorRect()
        cr.setLeft(cr.left() + self.completer.popup().verticalScrollBar().sizeHint().width() * 3)
        cr.setWidth(self.mainwindow.width() / 4)
        # TODO: Completer font size
        self.completer.popup().horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.completer.popup().setItemDelegate(HTMLDelegate(self.completer.popup()))
        self.completer.complete(cr)

        if self.completer.popup().currentIndex().row() == -1 or prefix != self.completer.completionPrefix():
            self.completer.setCompletionPrefix(prefix)
            self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0))

    def matchBrackets(self):
        paired = pluginloader.getPairedBrackets(self.wrapper.filetype.currentText())
        bopen = [x[0] for x in paired]
        bclose = [x[1] for x in paired]

        curs = self.textCursor()
        data = curs.block().userData()
        if data:
            infos = data.parenthesis

            pos = curs.block().position()
            curPos = curs.positionInBlock()
            block = curs.block()
            for i in range(len(infos)):
                info = infos[i]
                if info.at(curPos):
                    oidx = bopen.index(info.char) if info.char in bopen else -1
                    cidx = bclose.index(info.char) if info.char in bclose else -1
                    if info.char in bopen:
                        cpos = self.getClosingBracketPos(paired[oidx], block, i + 1)
                        if cpos >= 0:
                            curs.setPosition(cpos)
                            j = curs.block().userData().indexOf(curs.positionInBlock())
                            opos = self.getOpeningBracketPos(paired[oidx], curs.block(), j - 1)
                            if info.pos == opos - pos:
                                self.highlightBrackets(opos, len(paired[oidx][0]))
                                self.highlightBrackets(cpos, len(paired[oidx][1]))
                    if info.char in bclose:
                        opos = self.getOpeningBracketPos(paired[cidx], block, i - 1)
                        if opos >= 0:
                            curs.setPosition(opos)
                            j = curs.block().userData().indexOf(curs.positionInBlock())
                            cpos = self.getClosingBracketPos(paired[cidx], curs.block(), j + 1)
                            if info.pos == cpos - pos:
                                self.highlightBrackets(cpos, len(paired[cidx][1]))
                                self.highlightBrackets(opos, len(paired[cidx][0]))

    def getOpeningBracketPos(self, pair, block, i, num=0):
        data = block.userData()
        infos = data.parenthesis

        docPos = block.position()
        for j in range(i, -1, -1):
            if len(infos) == 0:
                break
            info = infos[j]

            if info.char == pair[1] and pair[0] != pair[1]:
                num += 1
                continue
            if info.char == pair[0]:
                if num == 0:
                    return docPos + info.pos
                num -= 1

        block = block.previous()
        if block.isValid():
            return self.getOpeningBracketPos(pair, block, 0, num)

        return -1

    def getClosingBracketPos(self, pair, block, i, num=0):
        if i < 0:
            return -1
        data = block.userData()
        infos = data.parenthesis

        docPos = block.position()
        for j in range(i, len(infos)):
            info = infos[j]

            if info.char == pair[0] and pair[0] != pair[1]:
                num += 1
                continue
            if info.char == pair[1]:
                if num == 0:
                    return docPos + info.pos
                num -= 1

        block = block.next()
        if block.isValid():
            return self.getClosingBracketPos(pair, block, 0, num)

        return -1

    def highlightBrackets(self, pos, size=1):
        selection = QtWidgets.QTextEdit.ExtraSelection()
        selection.format.setBackground(QtGui.QColor(Config.value("col/clnb")))
        selection.format.setForeground(QtGui.QColor(Config.value("col/clnf")))

        curs = self.textCursor()
        curs.setPosition(pos)
        curs.movePosition(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor, size)
        selection.cursor = curs

        selections = self.extraSelections()
        selections.append(selection)
        self.setExtraSelections(selections)

    def highlightMatches(self):
        selections = self.extraSelections()

        for start, end, _ in self.matches:
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format.setBackground(QtGui.QColor(Config.value("col/find")))

            curs = self.textCursor()
            curs.setPosition(start)
            curs.setPosition(end, QtGui.QTextCursor.KeepAnchor)
            selection.cursor = curs
            selections.append(selection)

        self.setExtraSelections(selections)

    def highlightErrors(self):
        selections = self.extraSelections()
        for start, size, message in self.errors:
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format = BaseHighlighter.format_error()

            curs = self.textCursor()
            curs.setPosition(start)
            curs.setPosition(start + size, QtGui.QTextCursor.KeepAnchor)
            selection.cursor = curs
            selections.append(selection)
        self.setExtraSelections(selections)

    def highlightCurrentLine(self):
        selections = []
        if not self.isReadOnly():
            selection = QtWidgets.QTextEdit.ExtraSelection()
            selection.format.setBackground(QtGui.QColor(Config.value("col/cline")))
            selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
            selection.cursor = self.textCursor()
            selection.cursor.clearSelection()
            selections.append(selection)

        self.setExtraSelections(selections)

    def lineNumberAreaPaintEvent(self, event):
        self.verticalScrollBar().setSliderPosition(self.verticalScrollBar().sliderPosition())
        painter = QtGui.QPainter(self.lineNumberArea)
        painter.fillRect(event.rect(), QtGui.QColor(Config.value("col/lnb")))

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + round(self.blockBoundingRect(block).height())

        currentBlockNumber = self.textCursor().block().blockNumber()

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = str(blockNumber + 1)
                if currentBlockNumber == blockNumber:
                    painter.fillRect(QtCore.QRect(0, top, self.lineNumberArea.width(), self.fontMetrics().height()),
                                     QtGui.QColor(Config.value("col/clnb")))
                    painter.setPen(QtGui.QColor(Config.value("col/clnf")))
                else:
                    painter.setPen(QtGui.QColor(Config.value("col/lnf")))
                painter.drawText(0, top, self.lineNumberArea.textWidth(), self.fontMetrics().height(),
                                 QtCore.Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + round(self.blockBoundingRect(block).height())
            blockNumber += 1

    def lineNumberAreaWidth(self):
        if not bool(Config.value("editor/showLineNumbers", True)):
            return 0
        digits = 1
        _max = max(1, self.document().blockCount())
        while _max >= 10:
            _max /= 10
            digits += 1

        return 13 + self.fontMetrics().width('9') * digits + self.lineNumberArea.offset

    def resizeEvent(self, event):
        QtWidgets.QPlainTextEdit.resizeEvent(self, event)
        cr = self.contentsRect()
        self.lineNumberArea.setGeometry(QtCore.QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))

    def updateIndicator(self):
        if isinstance(self.mainwindow.statusBar(), StatusBar):
            text = ""
            cursor = self.textCursor()
            if cursor.selectedText() != "":
                text = "[%i chars]" % len(cursor.selectedText())
            self.mainwindow.statusBar().positionIndicator\
                .setText("%s      %i:%i" % (text, cursor.blockNumber() + 1, cursor.columnNumber() + 1))

    def updateLineNumberAreaWidth(self, newBlockCount=0):
        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

    def updateLineNumberArea(self, rect, dy):
        self.verticalScrollBar().setSliderPosition(self.verticalScrollBar().sliderPosition())

        if dy:
            self.lineNumberArea.scroll(0, dy)
        else:
            self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())

        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth()

    def viewParseTree(self, focus=True):
        txt = self.toPlainText()
        T = self.highlighter.parser.parse(txt, True)
        if T is not None:
            if self.treeView is None:
                self.treeView = QtWidgets.QDialog(self.parent(), flags=QtCore.Qt.Window)
                layout = QtWidgets.QGridLayout()
                view = GraphicsView(self.mainwindow, self.parent())
                layout.addWidget(view)
                self.treeView.setLayout(layout)
            self.treeView.setWindowTitle("Lark LALR Parse Tree of %s" % self.filename)
            view = self.treeView.layout().itemAtPosition(0, 0).widget()
            view.setControls(bool(Config.value("view/controls")))
            view.setMinZoomLevel(float(Config.value("view/zoomMin")) / 100)
            view.setMaxZoomLevel(float(Config.value("view/zoomMax")) / 100)
            view.setZoomFactorBase(float(Config.value("view/zoomFactor")))
            view.clear()

            ename = self.wrapper.engine.currentText()
            T = self.highlighter.parser.parse(self.toPlainText())
            engine = pluginloader.getEngines()[ename]
            if T is not None:
                if "AST" in engine:
                    bdata = engine["AST"](T)
                    view.add(bdata)
                else:
                    engine = pluginloader.getEngines().get("Graphviz", {})
                    if "AST" in engine:
                        bdata = engine["AST"](T)
                        view.add(bdata)
                    else:
                        self.mainwindow.error("Error!", "The current rendering engine '%s' does not support the "
                                                        "rendering of Abstract Syntax Trees and the fallback renderer "
                                                        "'Graphviz' cannot be found.\n\nCurrently unable to display the"
                                                        " AST." % ename)
                        return

            if not self.treeView.isVisible():
                self.treeView.show()
            if focus:
                self.treeView.activateWindow()
                self.treeView.raise_()
                self.treeView.setFocus()
        else:
            self.mainwindow.warn("Warning!", "It looks like your file contains some errors. Impossible to render AST.")
            if self.treeView is not None and self.treeView.isVisible():
                self.treeView.close()

class LineNumberArea(QtWidgets.QWidget):
    def __init__(self, editor):
        super(LineNumberArea, self).__init__(editor)
        self.editor = editor
        self.offset = 10

    def textWidth(self):
        return self.width() - self.offset

    def sizeHint(self):
        return QtCore.QSize(self.editor.lineNumberAreaWidth(), 0)

    def paintEvent(self, QPaintEvent):
        self.editor.lineNumberAreaPaintEvent(QPaintEvent)

class HTMLDelegate(QtWidgets.QStyledItemDelegate):
    """Delegate inspired by:

    https://stackoverflow.com/questions/1956542/how-to-make-item-view-render-rich-html-text-in-qt/1956781#1956781
    """
    def paint(self, painter, options, QModelIndex):
        self.initStyleOption(options, QModelIndex)
        style = QtWidgets.QApplication.style() if options.widget is None else options.widget.style()

        doc = QtGui.QTextDocument()
        col = Config.value("col/foreground")
        if self.parent().currentIndex().row() == QModelIndex.row():
            col = Config.value("col/highlightedText")
        doc.setHtml("<nobr><font color='%s'>%s</font></nobr>" % (col, options.text))
        doc.setTextWidth(options.rect.width())

        options.text = ""
        # options.showDecorationSelected = False
        # options.features ^= QtWidgets.QStyleOptionViewItem.HasDisplay
        # style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()

        painter.save()
        rh = options.rect.height()
        iconSize = QtCore.QSize(rh, rh) * 0.8
        isize = iconSize * 0.8
        pt = options.rect.topLeft()
        o = (rh - isize.height()) / 2
        pt += QtCore.QPoint(o, o)
        options.icon.paint(painter, QtCore.QRect(pt, isize))
        painter.translate(options.rect.left() + iconSize.width(), options.rect.top())
        clip = QtCore.QRectF(0, 0, options.rect.width() + iconSize.width(), options.rect.height())
        painter.setClipRect(clip)
        ctx.clip = clip
        doc.documentLayout().draw(painter, ctx)

        painter.restore()

    def sizeHint(self, options, QModelIndex):
        self.initStyleOption(options, QModelIndex)

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())

        return QtCore.QSize(doc.idealWidth(), doc.size().height())


import random
from enum import IntEnum
from random import randint
import numpy as np
from keras.models import load_model
import cv2
import time

class items(IntEnum):
     Nothing =0
     Paper    =1
     Rock   =2
     Scissors=3

class game:
    def __init__(self):
        self.model = load_model('keras_model.h5', compile=False)
        self.cap = cv2.VideoCapture(0)
        self.data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
        self.round=0
        self.user_score=0
        self.computer_score=0

    def user_intro(self):
        self.user_name= input("Please enter your name: ")
        print(f"Welcome {self.user_name} to this game")
        return self.user_name

    def user_choices(self):
        prediction = self.model.predict(self.data)
        print(prediction)
        chooses = np.argmax(prediction[0])
        print(chooses)
        self.user_choice = items(chooses)
        print(self.user_choice)
        return self.user_choice

    def compu_prediction(self):
        comp_input=random.randint(1, len(items)-1)
        self.comp_pick= items(comp_input)
        print(self.comp_pick)
        return self.comp_pick

    def who_won(self,user_choice,comp_pick):
        if user_choice == comp_pick:
            self.winner="its a tire"
            self.round+=1
        elif user_choice == items.Rock and comp_pick == items.Scissors:
            self.winner=self.user_name
            self.user_score+=1
            self.round+=1

        elif user_choice == items.Rock and comp_pick == items.Paper:
            self.winner="computer"
            self.computer_score+=1
            self.round+=1

        elif user_choice == items.Paper and comp_pick == items.Rock:
            self.winner=self.user_name
            self.user_score+=1
            self.round+=1

        elif user_choice == items.Paper and comp_pick == items.Scissors:
            self.winner="computer"
            self.computer_score+=1
            self.round+=1

        elif user_choice == items.Scissors and comp_pick == items.Paper:
            self.winner=self.user_name
            self.user_score+=1
            self.round+=1

        elif user_choice == items.Scissors and comp_pick == items.Rock:
            self.winner="computer"
            self.computer_score+=1
            self.round+=1

        else:
            self.winner='No winner'
            print(self.winner)
            print('Play Aain')

        return self.winner

    def begin_game(self):
        self.data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
        ret, self.frame = self.cap.read()
        #if self.frame is None:
        #    print('No image')
        #else:
        #    self.frame = self.frame[32:, 188:]
        #resize the frame
        resized_frame = cv2.resize(self.frame, (224,224), interpolation = cv2.INTER_AREA)
        image_np = np.array(resized_frame)
        normalized_image = (image_np.astype(np.float32)/127.0) - 1 #normalize the image
        self.data[0] = normalized_image
        #cv2.imshow('frame',self.frame)
        #cv2.waitKey(1)

        #initial instruction
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.rectangle(self.frame, (10,10), (600,120), (255,255,0), -1)
        screen_message= "Current_Round: " + str(self.round) + " " + "Current Score" +str(self.user_score) + " CPU:" + str(self.computer_score)
        cv2.putText(self.frame, screen_message, (10,30), 1, 1.5, (0,0,0))
        cv2.putText(self.frame, "Press q to quit", (20,70), 1,1.5, (255,0,0))
        cv2.imshow("frame",self.frame)

    def end_game(self):
        self.cap.release()
        if self.computer_score == 3 or self.user_score == 3:
            print('Game over')
        else:
            print('you left the game')

        cv2.waitKey(1)
        cv2.destroyAllWindows()
        cv2.waitKey(1)

def play_game():
    game1=game()
    game1.user_intro()

    while True:
        count_time=5
        #open the game
        game1.begin_game()
        # press s to start the game

        if cv2.waitKey(80) & 0xFF == ord('s'):
            prev_time= time.time()
            while count_time > 0:
                game1.begin_game()
                cv2.putText(game1.frame, str(count_time), (190,420), 1, 1.5, (0,0,0))
                cv2.imshow('frame',game1.frame)
                cv2.waitKey(1)

                #count down
                current_time= time.time()
                if current_time - prev_time >=1:
                    prev_time = current_time
                    count_time -= 1

            else:
                user_input=game1.user_choices()
                compu_input=game1.compu_prediction()
                game1.who_won(user_input,compu_input)

                #output winner
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(game1.frame, f"{game1.user_name}'s choice : {game1.user_choice}",
                            (10, 200), font, 0.7, (0,0,0), 1, cv2.LINE_AA)
                cv2.putText(game1.frame, f"Computer's choice : {game1.comp_pick}",
                            (270, 200), font, 0.7, (0,0,0), 1, cv2.LINE_AA)
                cv2.putText(game1.frame, f"winner : {game1.winner}",
                            (10, 250), font, 1.2, (0,0,0), 1, cv2.LINE_AA)
                cv2.imshow('frame', game1.frame)
                cv2.waitKey(2000)

                if  game1.computer_score == 3:
                    game1.begin_game()
                    cv2.rectangle(game1.frame,(10,400), (150, 160), (180,170,50), -1)
                    cv2.putText(game1.frame, "Game Over", (10,400), 3 ,1, (0,0,0))
                    cv2.putText(game1.frame, "Computer wins over human", (10,450), 3 ,1, (0,0,0))
                    cv2.imshow('frame',game1.frame)
                    cv2.waitKey(6000)
                    game1.end_game()
                    break
                elif game1.user_score == 3:
                    game1.begin_game()
                    cv2.rectangle(game1.frame,(10,400), (150, 160), (180,170,50), -1)
                    cv2.putText(game1.frame, "Game Over", (10,400), 3 ,1, (0,0,0))
                    cv2.putText(game1.frame, "Congratulation You won", (10,450), 3 ,1, (0,0,0))
                    cv2.imshow('frame',game1.frame)
                    cv2.waitKey(6000)
                    game1.end_game()
                    break
               # if cv2.waitKey(1) & 0xFF == ord('q'):
                #        break

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

play_game()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 14:23:03 2020

@author: Narahari B M
"""

import sys, os
sys.path.insert(0, "/home/fractaluser/Narahari/Personal/Consulting/hinglish_text_mining")
sys.path.insert(0, "/home/ec2-user/hinglish_text_mining")

from flask import Flask, request
from flask_cors import CORS
from importlib import reload
import src.api.api_handler as api_handler
import jsondata

app = Flask(__name__)
CORS(app)

sample_options = {'level1': 'brand', 'level1_val': 'mi', 'level2': 'models', 'level2_val': 'all', 'level3': 'issues', 'clip_max_labels': 15}

@app.route('/aggregates', methods=['POST'])
def aggregate_handler():

    if request.method == "POST":

        data_recieved = request.get_json()

        print(data_recieved)

        response = api_handler.serve_aggregation(data_recieved)

    return response

@app.route('/labels')
def get_all_labels():

    response = api_handler.serve_labels()

    return response

@app.route('/timeseries', methods=['POST', 'GET'])
def timeseries_handler():

    data_recieved = request.get_json()

    print(data_recieved)

    response = api_handler.serve_timeseries(data_recieved)

    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0')


"""Entrypoint for the USB-TCP bridge application."""
import logging
from . import systemd
from .cli import build_root_parser
import uvicorn  # type: ignore[import]

LOG = logging.getLogger(__name__)

if __name__ == "__main__":
    args = build_root_parser().parse_args()
    systemd.configure_logging(level=args.log_level.upper())
    LOG.info(f"Starting system server on {args.host}:{args.port}")
    systemd.notify_up()
    uvicorn.run(
        app="system_server:app",
        host=args.host,
        port=args.port,
        reload=args.reload,
        log_level=args.log_level,
    )


#app.py
from flask import Flask, flash, request, redirect, url_for, render_template
import urllib.request
import os
from werkzeug.utils import secure_filename
import collect_fea_style as cfs
import img_style_transform as ist

app = Flask(__name__)

UPLOAD_FOLDER_content = 'static/uploads/content'
UPLOAD_FOLDER_style = 'static/uploads/style'
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER_content'] = UPLOAD_FOLDER_content
app.config['UPLOAD_FOLDER_style'] = UPLOAD_FOLDER_style
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

def allowed_file(file):
    file_content = file[0]
    file_style = file[1]
    file_cname = file_content.filename
    file_sname = file_style.filename
    a = '.' in file_cname and file_cname.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    b = '.' in file_sname and file_sname.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    return a & b

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_image():
    print('get')
    if 'content-file' and 'style-file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    content_file = request.files['content-file']
    style_file = request.files['style-file']
    print('content name :',content_file.filename)
    print('style name :',style_file.filename)
    file = [content_file, style_file]
    if file[0].filename == '' or file[1].filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file):
        filename_content = secure_filename(file[0].filename)
        filename_style = secure_filename(file[1].filename)
        content_pure_name = filename_content.split('.')[0]
        style_pure_name = filename_style.split('.')[0]
        file[0].save(os.path.join(app.config['UPLOAD_FOLDER_content'], filename_content))
        file[1].save(os.path.join(app.config['UPLOAD_FOLDER_style'], filename_style))
        cfs.style_model_train(style_pure_name)
        ist.img_style_transform(content_pure_name,style_pure_name)
        #print('upload_image filename: ' + filename)
        flash('Image successfully uploaded and displayed below')
        content_path = app.config['UPLOAD_FOLDER_content']+ '/'+ filename_content
        style_path = app.config['UPLOAD_FOLDER_style'] +'/' + filename_style
        output_path = 'static/uploads/output/' + content_pure_name+'_'+style_pure_name +'.jpg'
        params = {
            'content': content_path,
            'style':style_path,
            'output' : output_path
        }
        return render_template('success.html', **params)
    else:
        flash('Allowed image types are - png, jpg, jpeg, gif')
        return redirect(request.url)

if __name__ == "__main__":
    app.run()


"""
Helpers for sending emails.
"""
import functools
import os

import sendgrid
from sendgrid.helpers import mail

_SENDGRID_API_ENV = 'SENDGRID_API_KEY'

@functools.lru_cache()
def _sg() -> sendgrid.SendGridAPIClient:
    """Returns a cached SendGridAPIClient."""
    return sendgrid.SendGridAPIClient(api_key=os.environ.get(_SENDGRID_API_ENV))

def send_email(
        from_email: str, to_email: str, subject: str, content: str) -> None:
    """Sends an email."""
    from_email = mail.Email(from_email)
    to_email = mail.To(to_email)
    subject = subject
    content = mail.Content("text/html", content)
    the_mail = mail.Mail(from_email, to_email, subject, content)
    response = _sg().client.mail.send.post(request_body=the_mail.get())
    assert response.status_code == 202


import sys, itertools, collections
from utils import read_file, timer

def step(board):
    N, M = len(board), len(board[0])
    result = [[None]*M for i in range(N)]

    for i in range(N):
        for j in range(M):
            counts = collections.Counter()
            for dx in range(-1, 2):
                for dy in range(-1, 2):
                    if dx == 0 and dy == 0:
                        continue
                    i2, j2 = i + dx, j + dy
                    if 0 <= i2 < N and 0 <= j2 < M:
                        counts[board[i2][j2]] += 1
            if board[i][j] == '.':
                result[i][j] = '|' if counts['|'] >= 3 else '.'
            elif board[i][j] == '|':
                result[i][j] = '#' if counts['#'] >= 3 else '|'
            else:
                result[i][j] = '#' if (counts['#'] >= 1 and counts['|'] >= 1) else '.'

    return result

@timer
def solve():
    input = read_file("18")
    board = []
    for line in input:
        board.append(line)
    minutes = 1000000000
    for i in range(1, minutes + 1):
        board = step(board)
    counts = collections.Counter()
    for row in board:
        for c in row:
            counts[c] += 1
    return counts['#'] * counts['|']

result = solve()
print(f'Solution: {result}')


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 17:56:08 2023

@author: shada
"""

import torch
import torch.nn as nn

class MLP(nn.Module):
    def __init__(self, state_dim, action_dim):
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(state_dim, 64)
        self.fc2 = nn.Linear(64, 48)
        self.fc3 = nn.Linear(48, 24)
        self.fc4 = nn.Linear(24, action_dim)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = torch.relu(self.fc3(x))
        x = self.fc4(x)
        return x


"""
Combine ESR Leavers data sets into a single file.
Steps:
1. Find files in Trust_data/ESR_Leavers
2. Calculate the Termination Year-Month
3. Group by Year-Month, Ward and Leaving Reason and calculate leavers frequency
4. Drop all columns except Organisation, Termination Month, Leaving Reason, Frequency.
5. Save to file Leavers_Monthly_Frequencies.csv
"""
import pandas as pd
import numpy as np

from .utilities import check_file_names, ScriptFactory
from .config import EXTRACT_PATH, ALLOCATE_WARD_COLUMN

FILE_NAME = "ESR_Leavers"

def monthly_frequency(data):
    """
    Reduce a data set to a frequency table.
    Parameters
    ----------
    data: pandas.DataFrame
        ESR Leavers data set.
    Returns
    -------
    pandas.DataFrame
    """
    grps = data.groupby([ALLOCATE_WARD_COLUMN, "Termination Month", "Leaving Reason", "Staff Group"])
    result = pd.DataFrame(
        [np.concatenate((i, j.shape))[:-1] for i, j in grps]
    )
    result.columns = ["Organisation", "Termination Month", "Leaving Reason", "Staff Group", "Count"]
    return result

tasks = {
    "Load data": dict(path="Trust_data", name="ESR_Leavers"),
    "To datetime": dict(columns=["Termination Date"]),
    "Manipulate column": dict(
        new_column="Termination Month",
        old_column="Termination Date",
        function=lambda x: "{}-{}".format(x.year, x.month)
    ),
    "Apply function": dict(function=monthly_frequency),
    "To file": dict(extract_path=EXTRACT_PATH, file_name="Leavers_Monthly_Frequencies")
}

if __name__ == '__main__':

    routine = ScriptFactory(EXTRACT_PATH, "ESR_Leavers", tasks)
    check_file_names("ESR_Leavers")
    routine.process_script()


import dataclasses
import numpy as np
import typing
import datetime

import covid19sim.inference.message_utils as mu

class RiskLevelBoundsCheckedType(mu.RiskLevelType):
    """
    Wrapper class aliasing RiskLevelType to bound check passed data to
    RiskLevelType
    """
    lo_bound = 0
    hi_bound = mu.risk_level_mask

    def __new__(cls, *args, **kargs):
        self = super(RiskLevelBoundsCheckedType, cls).__new__( \
                                                        cls, *args, **kargs)
        value = self.item()
        if not cls.lo_bound <= value <= cls.hi_bound:
            raise ValueError(
                "{} {} is out of its expected boundaries [{},{}]".format(
                    cls.__name__,
                    value,
                    cls.lo_bound,
                    cls.hi_bound
                )
            )
        return self

@dataclasses.dataclass
class ObservedRisk:
    """
    A mapping from encountered tick to the observed data at that tick. It
    includes a mandatory field risk_level and an optional list of update
    signatures, i.e., update_risk_levels, update_ticks, and update_reasons
    for update messages to be related to the former encountered message.
    """
    start_time = mu.TimestampDefault
    time_offset = datetime.timedelta(days=1)

    @staticmethod
    def toff(t: typing.Union[int, np.int64]):
        """
        translates discrete time according to daily time offsets
        """
        return ObservedRisk.start_time + t * ObservedRisk.time_offset

    @dataclasses.dataclass
    class _UpdateMessage:
        """
        container for update messages of observed risks
        """
        update_tick: typing.Union[int, np.int64]
        update_risk_level: RiskLevelBoundsCheckedType
        update_reason: typing.Optional[str] = None

    encounter_tick: typing.Union[int, np.int64]
    encounter_risk_level: RiskLevelBoundsCheckedType
    update_signatures: typing.List[_UpdateMessage] = \
        dataclasses.field(default_factory=list, init=False)

    def __post_init__(self):
        """
        post initialization of encounter_risk_level to make sure
        the its bounds are checked
        """
        self.encounter_risk_level = RiskLevelBoundsCheckedType(
                                            self.encounter_risk_level)

    def update(self,
               update_tick: typing.Union[int, np.int64],
               update_risk_level: typing.Union[int, RiskLevelBoundsCheckedType],
               update_reason: typing.Optional[str] = None,
               ):
        """
        adds an update message following an encounter message and the updates
        that followed it
        """
        # validate the passed update tick does not belong to a time older than
        # the last update
        if len(self.update_signatures) > 0:
            if update_tick < self.update_signatures[-1].update_tick:
                raise ValueError(
                    'passed update tick {} < last update tick {}'.format(
                        update_tick,
                        self.update_signatures[-1].update_tick
                    )
                )
        else:
            if update_tick < self.encounter_tick:
                raise ValueError(
                    'passed update tick {} < encounter tick {}'.format(
                        update_tick,
                        self.encounter_tick
                    )
                )
        # validate the bounds of the passed update_risk_level
        update_risk_level = RiskLevelBoundsCheckedType(update_risk_level)

        self.update_signatures.append(
            ObservedRisk._UpdateMessage(
                update_tick=update_tick,
                update_risk_level=update_risk_level,
                update_reason=update_reason
            ))
        return self

    def to_user_messages(self,
                         uid: mu.UIDType,
                         real_uid_counter: mu.RealUserIDType,
                         exposure_tick: typing.Union[int, np.int64] = np.inf,
                         ) -> typing.List[mu.GenericMessageType]:
        """
        converting observed risk levels for a contacted user
        into a list of encounter and update messages
        """
        encounter_time = ObservedRisk.toff(self.encounter_tick)
        encounter_message = mu.EncounterMessage(
            uid=uid,
            risk_level=self.encounter_risk_level,
            encounter_time=encounter_time,
            _sender_uid=real_uid_counter,
            _receiver_uid=None,
            _real_encounter_time=encounter_time,
            _exposition_event=(
                self.encounter_tick >= exposure_tick),
        )

        messages: typing.List[mu.GenericMessageType] = [encounter_message]
        last_risk = encounter_message.risk_level
        for update_signature in self.update_signatures:
            update_time = ObservedRisk.toff(update_signature.update_tick)
            update_message = mu.UpdateMessage(
                uid=uid,
                old_risk_level=last_risk,
                new_risk_level=update_signature.update_risk_level,
                encounter_time=encounter_time,
                update_time=update_time,
                _sender_uid=encounter_message._sender_uid,
                _receiver_uid=encounter_message._receiver_uid,
                _real_encounter_time=encounter_time,
                _real_update_time=update_time,
                _exposition_event=encounter_message._exposition_event,
                _update_reason=update_signature.update_reason,
            )

            messages.append(update_message)
            last_risk = update_signature.update_risk_level
        return messages

class MessageContextManager():
    """
    A context manager to generate batch of encounter and update
    messages that interface.
    Each public method call counts as one distinct user sending
    messages to a protagonist receiving these messages.
    """

    def __init__(self, max_tick):
        self.max_tick = max_tick
        self.max_history_offset = ObservedRisk.time_offset * max_tick
        self.real_uid_counter: mu.RealUserIDTypel = 0
        self._contact_messages = []

    def insert_messages(
        self,
        observed_risks: typing.Union[ObservedRisk, typing.List[ObservedRisk]],
        tick_to_uid_map: typing.Dict[int, mu.UIDType] = {},
        exposure_tick: typing.Union[int, np.int64] = np.inf,
    ) -> typing.List[mu.GenericMessageType]:
        """
        inserting a batch of observed_risks to the message context
        :param tick_to_uid_map: the uids to force ticks to adopt,
        random otherwise
        :param exposure_tick: the tick on which all the following messages
        (inclusive) are set in _exposition_event flag in messages' debugging
        attributes this doesn't ensure the risk levels that are passed
        via observed_risks reflect this
        """
        if isinstance(observed_risks, ObservedRisk):
            observed_risks = [observed_risks]
        for observed_risk in observed_risks:
            encounter_tick = observed_risk.encounter_tick
            # uid validation
            uid = tick_to_uid_map.get(encounter_tick)
            if uid is None:
                uid = mu.create_new_uid()
                tick_to_uid_map[encounter_tick] = uid
            self._contact_messages.extend(
                observed_risk.to_user_messages(
                    uid,
                    self.real_uid_counter,
                    exposure_tick=exposure_tick
                )
            )
        self.real_uid_counter += 1

    @staticmethod
    def _chronological_key(message: mu.GenericMessageType):
        """
        Returns a message key that is used to generate chronological sorting
        of messages (from old to new)
        """
        if isinstance(message, mu.UpdateMessage):
            return (message.update_time, 1)
        else: # mu.EncounterMessage
            return (message.encounter_time, 0)

    @property
    def contact_messages(self, sort=True):
        """
        Returns a batch of contact messages sorted in chronological order
        by default. If sort is otherwise set to False, then returns unsorted
        contact messages.
        All generated messages in this manager are to be accessed using this
        property
        """
        if sort:
            self._contact_messages.sort(key=self._chronological_key)
        return self._contact_messages

    def insert_random_messages(
            self,
            n_encounter: int,
            n_update: int,
            exposure_tick: typing.Union[int, np.int64] = np.inf,
            min_risk_level: RiskLevelBoundsCheckedType = 0,
            max_risk_level: RiskLevelBoundsCheckedType = mu.risk_level_mask
    ) -> typing.List[mu.GenericMessageType]:
        """
        Returns a set of random encounter/update messages from a single user
        :param exposure_tick: the tick on which all the following messages
        (inclusive) are set in _exposition_event flag in messages' debugging
        attributes this doesn't ensure the risk levels that are passed
        via observed_risks reflect this
        """
        # argument validation
        if n_encounter < 1:
            raise ValueError("n_encounter must be at least 1, passed: " +
                             str(n_encounter))
        if not min_risk_level <= max_risk_level <= mu.risk_level_mask:
            raise ValueError("min_risk_level {} should be less than or equal \
                to max_risk_level {} which in turn should be less than or \
                    equal to risk_level_mask {}".format(
                min_risk_level,
                max_risk_level,
                mu.risk_level_mask
            ))
        n_message = n_encounter + n_update
        risk_levels = np.random.randint(
            min_risk_level, max_risk_level + 1,
            size=n_message).astype(RiskLevelBoundsCheckedType)
        message_ticks = np.random.choice(
            self.max_tick, size=n_message).astype(int)
        partitions = np.random.choice(np.arange(1, n_message),
                                      size=n_encounter-1, replace=False)
        partitions.sort()
        risk_levels = np.split(risk_levels, partitions)
        message_ticks = np.split(message_ticks, partitions)
        observed_risks = [None] * n_encounter
        for i in range(n_encounter):
            message_ticks[i].sort()
            n_encounter_update = message_ticks[i].shape[0] - 1

            encounter_risk = risk_levels[i][0]
            encounter_tick = message_ticks[i][0]

            update_risks = risk_levels[i][1:]
            update_ticks = message_ticks[i][1:]

            observed_risks[i] = ObservedRisk(
                encounter_tick=encounter_tick,
                encounter_risk_level=encounter_risk
            )
            for j in range(n_encounter_update):
                update_tick = update_ticks[j]
                update_risk_level = update_risks[j]
                observed_risks[i].update(
                    update_tick=update_tick,
                    update_risk_level=update_risk_level
                )
        self.insert_messages(observed_risks, exposure_tick=exposure_tick)

    def _generate_linear_saturation_observed_risks(
        self,
        negative_saturation_tick: typing.Union[int, np.int64],
        init_risk_level: RiskLevelBoundsCheckedType,
        final_risk_level: RiskLevelBoundsCheckedType,
        rate: int = 1
    ) -> typing.List[mu.GenericMessageType]:
        """
        Returns the observed risks belonging to a linear saturation curve (_/¯)
        :param negative_saturation_tick: the last tick before observing an
        increase in the risk levels
        :param init_risk_level: the initial risk level
        :param final_risk_level: the final risk level if reachable given
        negative_saturation_tick and rate
        :param rate: the rate of increase of ticks over a unit of
        increase of init_risk_level to final_risk_level
        """
        if not negative_saturation_tick:
            negative_saturation_tick = self.max_tick + 1
        # setting the last tick of the increasing pattern in the risk levels
        positive_saturation_tick = negative_saturation_tick + \
            (final_risk_level - init_risk_level) * rate

        if positive_saturation_tick <= self.max_tick:
            observed_risks = [None] * self.max_tick
            for t in range(self.max_tick):
                if t <= negative_saturation_tick:
                    observed_risks[t] = ObservedRisk(
                        encounter_tick=t,
                        encounter_risk_level=init_risk_level,
                    )
                elif t >= positive_saturation_tick:
                    observed_risks[t] = ObservedRisk(
                        encounter_tick=t,
                        encounter_risk_level=final_risk_level,
                    )
                else:
                    observed_risks[t] = ObservedRisk(
                        encounter_tick=t,
                        encounter_risk_level= \
                            (t - negative_saturation_tick) / rate,
                    ).update(
                        update_tick=positive_saturation_tick,
                        update_risk_level=final_risk_level
                    )
        else:
            observed_risks = [
                ObservedRisk(
                    encounter_tick=t,
                    encounter_risk_level=init_risk_level
                )
                for t in range(self.max_tick)
            ]
        return observed_risks

    def insert_linear_saturation_risk_messages(
            self,
            n_encounter: int,
            exposure_tick: typing.Union[int, np.int64] = np.inf,
            init_risk_level: RiskLevelBoundsCheckedType = 0,
            final_risk_level: RiskLevelBoundsCheckedType = mu.risk_level_mask,
    ) -> typing.List[mu.GenericMessageType]:
        """
        Returns a set of random encounter/update messages from a single user
        with observed risks belonging to a linear saturation curve (_/¯)
        :param exposure_tick: the tick on which the risk level start rising
        this tick also marks the debugging flag of _exposition_event in all
        messages happening on and following ticks (inclusive)
        :param init_risk_level: the initial risk level
        :param final_risk_level: the final risk level if reachable given
        negative_saturation_tick and rate
        """
        # argument validation
        if not init_risk_level <= final_risk_level <= mu.risk_level_mask:
            raise ValueError("init_risk_level {} should be less than or equal \
                to final_risk_level {} which in turn should be less than or \
                    equal to risk_level_mask {}".format(
                init_risk_level,
                final_risk_level,
                mu.risk_level_mask
            ))
        # create at least one encounter
        linear_saturation_risks = \
            self._generate_linear_saturation_observed_risks(
                negative_saturation_tick=exposure_tick,
                init_risk_level=init_risk_level,
                final_risk_level=final_risk_level,
            )

        idxs = np.random.choice(
            self.max_tick, size=n_encounter)
        sample_risks = [linear_saturation_risks[idx] for idx in idxs]
        self.insert_messages(sample_risks, exposure_tick=exposure_tick)


import csv
import re
from stemming.porter2 import stem
from check_list import *
from data_learner import *

# csv_path = "sample.csv"
# colom = 'Complaint Text'
output = [['Complaint area']]
unwanted_words_list = conjuctions + prepositions + pronouns + omit_verbs + ordinals +  months + omit_words
known_words_list = unwanted_words_list + negative_words + service_related_words + damage_related_words + car_parts

def get_unique(list1, list2):
    unique = []
    for item in list1:
        if item not in list2:
            unique.append(item)
    return unique

def preprocess(data):
    # Remove special characters
    data = re.sub('\W+',' ', data)
    # Remove digits
    data = ''.join(filter(lambda x: not x.isdigit(), data))
    # Remove unwanted words - conjuctions, ordinals etc.
    return get_unique(data.split(), unwanted_words_list)

def data_analyser(data):
    output.append([])
    if len(data) < 3:
        output[-1].append('Incomplete complaint')
        return
    complaints = {
        'dealer': 'Feedback against Dealer / showroom',
        'dealer_neg': 'Complaint against Dealer / showroom',
        'service': 'Complaint against service by Dealer / showroom',
        'damage': 'Car part damage / repair realted complaint',
        'generic': 'Customer Dissatisfaction',
        'unable': 'Unable to analyze the complaint from the given data'
    }
    service_complaint_added = False
    for each_word in data:
        word = stem(each_word)
        pos = data.index(each_word)
        if word in service_related_words and not service_complaint_added:
            service_complaint_added = True
            # Find if the comment is negative about the dealer
            key = 'dealer_neg' if (set(data[pos-1:pos+3]).intersection(negative_words)) else 'dealer'
            output[-1].append(complaints.get(key))
        # Add showroom / dealer name
            if 'motors' in data:
                output[-1][-1] + (': ' + data[data.index('motors') -1])
        if word in damage_related_words:
            output[-1].append(complaints.get('damage'))
    damage = set(data).intersection(car_parts)
    if len(damage) > 0:
        output[-1].append(complaints.get('damage') + ': ' + ','.join(damage))
        if complaints.get('damage') in output[-1]:
            output[-1].remove(complaints.get('damage'))

    if len(output[-1]) == 0 and len(set(data).intersection(negative_words)) > 0:
        output[-1].append(complaints.get('generic'))
    if len(output[-1]) == 0:
        output[-1].append(complaints.get('unable'))

def complaints_reader(file_obj, colom):
    data = []
    reader = csv.reader(file_obj)
    selected_colom = next(reader).index(colom)
    for row in reader:
        # Reduce the data as much as possible
        content = preprocess(row[selected_colom].lower())
        # Analyse each data
        data_analyser(content)

        # Learn from each data
        data_learner(content)
    data.append(content)
    return data

if __name__ == "__main__":

    csv_path = raw_input("Please enter the path of csv file")
    colom = raw_input("Please enter the heading of colom to be analyzed")
    with open(csv_path, "rb") as f_obj:
        complaints = complaints_reader(f_obj, colom)

    with open(csv_path, 'r+') as f_obj:
        reader = csv.reader(f_obj, delimiter=',')
        out_lines = [row + [','.join(output[i])] for i, row in enumerate(reader)]
        f_obj.seek(0)
        csv.writer(f_obj, delimiter=',').writerows(out_lines)
    new_list = get_new_words_list()

    # Write list of all new words with count to a file
    with open('new_words.csv', 'wb') as f_obj:
        writer = csv.writer(f_obj, delimiter=',')
        for data in new_list:
            writer.writerow(data)


from flask_restful import Resource, reqparse
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from pytorch_helper.resnet34 import load_model, predict
from pytorch_helper.constants import SF_CARS, INDIA_CARS, INDCARS_PARAM, SFCARS_PARAM
import os

class Predict(Resource):
    ALLOWED_EXTENTIONS = {'jpeg', 'jpg', 'png'}

    def __allowedfile(self, filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in Predict.ALLOWED_EXTENTIONS

    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('image', type=FileStorage, location='files', required=True)
        parse.add_argument('model', required=True, choices=(SFCARS_PARAM, INDCARS_PARAM),
                           help=f"Model should be '{SFCARS_PARAM}' or '{INDCARS_PARAM}'")
        args = parse.parse_args()
        image_file = args['image']
        model_name = args['model']
        print(image_file.filename)
        if image_file and self.__allowedfile(image_file.filename):
            try:
                filename = secure_filename(image_file.filename)
                loc = os.path.join('uploads', filename)
                image_file.save(loc)
                if model_name.strip() == SFCARS_PARAM:
                    model = load_model(SF_CARS, chkpt_model=SFCARS_PARAM)
                    res, total_cars = predict(model=model, fileloc=loc, chkpt_model=SFCARS_PARAM)
                elif model_name.strip() == INDCARS_PARAM:
                    model = load_model(INDIA_CARS, chkpt_model=INDCARS_PARAM)
                    res, total_cars = predict(model=model, fileloc=loc, chkpt_model=INDCARS_PARAM)
                else:
                    os.remove(loc)
                    return {"message": {'error': "Invalid Model Name", 'status': 404}}, 404
                os.remove(loc)
                return {'predictions': res, 'total_cars': total_cars, 'status': 200}, 200
            except Exception as e:
                return {"message": {'error': f"Internal Server Error {str(e)}", 'status': 500}}, 500

        else:
            return {"message": {'error': "Invalid Filename", 'status': 404}}, 404


import itertools

from gavo import base
from gavo import rscdef
from gavo import svcs
from gavo import utils
from gavo.registry.model import VS

_VOTABLE_TO_SIMPLE_TYPE_MAP = {
	"char": "char",
	"bytea": "char",
	"unicodeChar": "char",
	"short": "integer",
	"int": "integer",
	"long": "integer",
	"float": "real",
	"double": "real",
}

def simpleDataTypeFactory(dbType):
	type, length, xtype = base.sqltypeToVOTable(dbType)
	if length=='1':
		length = None
	return VS.dataType(arraysize=length)[
		_VOTABLE_TO_SIMPLE_TYPE_MAP.get(type, "char")]

def voTableDataTypeFactory(dbType):
	type, length, xtype = base.sqltypeToVOTable(dbType)
	return VS.voTableDataType(arraysize=length)[type]

def getSchemaForRD(rd):
	"""returns a VS.schema instance for an rd.

	No tables are added.  You need to pick and choose them yourself.
	"""
	return VS.schema[
		VS.name[rd.schema.lower()],
		VS.title[base.getMetaText(rd, "title")],
		VS.description[base.getMetaText(rd, "description")],
	]

def getForeignKeyForForeignKey(fk, namesInSet):
	"""returns a VS.foreignKey for a rscdef.ForeignKey.

	If the target table's name is not in nameInSet, the foreign key
	is not created.
	"""
# XXX TODO: we don't need to expand any more as soon as we've done away with
# the table attribute of foreignKey
	targetName = fk.parent.expand(fk.destTableName).lower()
	if targetName not in namesInSet:
		return None

	return VS.foreignKey[
		VS.targetTable[targetName], [
			VS.fkColumn[
				VS.fromColumn[fromColName.lower()],
				VS.targetColumn[toColName.lower()]]
			for fromColName,toColName in zip(fk.source, fk.dest)]]

def getTableColumnFromColumn(column, typeFactory):
	"""returns a VS.column instance for an rscdef.Column instance.

	typeElement is a factory for types that has to accept an internal (SQL)
	type as child and generate whatever is necessary from that.

	This module contains simpleDataTypeFactory, voTableDataTypeFactory,
	and should soon contain tapTypeFactory.
	"""
	if isinstance(column.name, utils.QuotedName):
		colName = str(column.name)
	else:
		colName = column.name.lower()

	flags = []
	if column.isIndexed():
		flags.append("indexed")
	if column.isPrimary():
		flags.append("primary")
	elif not column.required:
		flags.append("nullable")

	return VS.column[
		VS.name[colName],
		VS.description[column.description],
		VS.unit[column.unit],
		VS.ucd[column.ucd],
		VS.utype[column.utype],
		typeFactory(column.type),
		[VS.flag[f] for f in flags]]

def getEffectiveTableName(tableDef):
	"""returns the "effective name" of tableDef.

	This is mainly for fudging the names of output tables since,
	by default, they're ugly (and meaningless on top of that).
	"""
	if isinstance(tableDef, svcs.OutputTableDef):
		return "output"
	else:
		return tableDef.getQName().lower()

def getTableForTableDef(tableDef, namesInSet):
	"""returns a VS.table instance for a rscdef.TableDef.

	namesInSet is a set of lowercased qualified table names; we need this
	to figure out which foreign keys to create.
	"""
	name = getEffectiveTableName(tableDef)

	# Fake type=output on the basis of the table name.  We'll have
	# to do something sensible here if this "type" thing ever becomes
	# more meaningful.
	type = None
	if name=="output":
		type = "output"

	res = VS.table(type=type)[
		VS.name[name],
		VS.title[base.getMetaText(tableDef, "title", propagate=False)],
		VS.description[base.getMetaText(tableDef, "description", propagate=True)],
		VS.utype[base.getMetaText(tableDef, "utype")], [
			getTableColumnFromColumn(col, voTableDataTypeFactory)
				for col in tableDef], [
			getForeignKeyForForeignKey(fk, namesInSet)
				for fk in tableDef.foreignKeys]]
	return res

def getTablesetForSchemaCollection(schemas, rootElement=VS.tableset):
	"""returns a vs:tableset element from a sequence of (rd, tables) pairs.

	In each pair, rd is used to define a VODataService schema, and tables is
	a sequence of TableDefs that define the tables within that schema.
	"""
	# we don't want to report foreign keys into tables not part of the
	# service's tableset (this is for consistency with TAP_SCHEMA,
	# mainly).  Hence, we collect the table names given.
	namesInSet = set(getEffectiveTableName(td).lower()
		for td in itertools.chain(*(tables for rd, tables in schemas)))

	res = rootElement()
	for rd, tables in schemas:
		res[VS.schema[
			VS.name[rd.schema],
			VS.title[base.getMetaText(rd, "title")],
			VS.description[base.getMetaText(rd, "description")],
			VS.utype[base.getMetaText(rd, "utype", None)],
			[getTableForTableDef(td, namesInSet)
				for td in tables]]]
	return res

def getTablesetForService(resource, rootElement=VS.tableset):
	"""returns a VS.tableset for a service or a published data resource.

	This is for VOSI queries and the generation of registry records.
	Where it actually works on services, it uses the service's getTableset
	method to find out the service's table set; if it's passed a TableDef
	of a DataDescriptor, it will turn these into tablesets.

	Sorry about the name.
	"""
	if isinstance(resource, rscdef.TableDef):
		tables = [resource]

	elif isinstance(resource, rscdef.DataDescriptor):
		tables = list(resource.iterTableDefs())

	else:
		tables = resource.getTableSet()

	if not tables:
		return rootElement[
			VS.schema[
				VS.name["default"]]]

	# it's possible that multiple RDs define the same schema (don't do
	# that, it's going to cause all kinds of pain).  To avoid
	# generating bad tablesets in that case, we have the separate
	# account of schema names; the schema meta is random when
	# more than one RD exists for the schema.
	bySchema, rdForSchema = {}, {}
	for t in tables:
		bySchema.setdefault(t.rd.schema, []).append(t)
		rdForSchema[t.rd.schema] = t.rd

	schemas = []
	for schemaName, tables in sorted(bySchema.iteritems()):
		schemas.append((rdForSchema[schemaName], tables))

	return getTablesetForSchemaCollection(schemas, rootElement)


from sqlalchemy import Table, Column, String, Integer

from utils.datetime import naive_now
from .base import metadata, TimeStamp

SubscriptionItemsTable = Table(
    "subscription_items",
    metadata,
    Column("id", String(32), primary_key=True),
    Column("created_at", TimeStamp(), index=True, default=naive_now),
    Column("deleted_at", TimeStamp()),
    Column("sub_id", String(32)),
    Column("price_id", String(32)),
    Column("quantity", Integer),
)


from functools import partial
from random import randint

import torch
import numpy

from models.point_completion import OccupancyModel
from train import MODEL_FILENAME, SHAPENET_CLASS_DIR
from utils.constants import DEVICE, POINTCLOUD_N
from utils.data_loader import generate_data_loader

def generate_grid(ncuts, xl, xr, yl, yr, zl, zr):
    # The unit cube centered at 0
    # Subdivided into a grid of 32^3 "voxels"
    x = numpy.linspace(xl, xr, ncuts)
    y = numpy.linspace(yl, yr, ncuts)
    z = numpy.linspace(zl, zr, ncuts)
    xg, yg, zg = numpy.meshgrid(x, y, z)
    x = torch.tensor(xg)
    y = torch.tensor(yg)
    z = torch.tensor(zg)
    # Convert to a grid of 3 dimensional coordinate
    tgrid = torch.stack([x, y, z], dim=3).permute(1, 0, 2, 3)
    # A cube is made up the 8 vertices
    # Convert to a list where every 8 coords denote a cube
    gridpts = torch.zeros(8*(ncuts-1)*(ncuts-1)*(ncuts-1), 3)

    '''
    Vertex Order for marching cubes is
    (0,0,0):(1,0,0):(1,1,0):(0,1,0):(0,0,1):(1,0,1):(1,1,1):(0,1,1)
    '''
    gpt = 0
    for i in range(ncuts-1):
        for j in range(ncuts-1):
            for k in range(ncuts-1):
                gridpts[gpt] = tgrid[i][j][k]
                gridpts[gpt+1] = tgrid[i+1][j][k]
                gridpts[gpt+2] = tgrid[i+1][j+1][k]
                gridpts[gpt+3] = tgrid[i][j+1][k]
                gridpts[gpt+4] = tgrid[i][j][k+1]
                gridpts[gpt+5] = tgrid[i+1][j][k+1]
                gridpts[gpt+6] = tgrid[i+1][j+1][k+1]
                gridpts[gpt+7] = tgrid[i][j+1][k+1]
                gpt = gpt + 8

    return gridpts

def generate_adaptive_grid(ncuts, xl, xh, yl, yh, zl, zh, limit, mesh_funct, onCuda):
    if not limit:
        return None
    g = generate_grid(ncuts, xl, xh, yl, yh, zl, zh)
    ag = g.view(-1, 3)

    final_grid = []
    # divide list of coordinates into cubes
    for i in range(0, int(ag.size()[0]), 8):
        # marking one active if occupancies differ on the vertices
        active = False
        for k in range(0, 8):
            coord = ag[i + k]
            if onCuda:
                coord = coord.cuda()
            active ^= mesh_funct(coord)
        if (active):
            # near left coordinate is v0
            nl = ag[i]
            # top right coordinate is v6
            tr = ag[i + 6]

            # subdivide this cube into 8 subvoxels
            g = generate_adaptive_grid(3, nl[0], tr[0], nl[1], tr[1], nl[2], tr[2], limit - 1, mesh_funct, onCuda)
            # replace this grid where the cube was
            if g is not None:
                final_grid.append(g)
            # or keep this cube
            else:
                final_grid.append(ag[i: i + 8])
        else:
            final_grid.append(ag[i:i + 8])
    for i in range(len(final_grid)):
        final_grid[i] = final_grid[i].view(-1, 3)
    final_grid = torch.cat(final_grid)

    return final_grid

def over_model_threshold(model, sample_pointcloud, pts):
    pts = pts.view(-1, 1, 3, 1).permute(0, 2, 1, 3)
    x = model(pts, sample_pointcloud)
    x = x.squeeze(-1)
    x = torch.sigmoid(x)
    return (x[0] > 0.6).item()

def write_point_cloud_to_xyz(pointcloud, filename):
    with open(filename, 'w') as fh:
        fh.write(f"{pointcloud[0].shape[0]}\n")
        for points in pointcloud[0]:
            fh.write(f"{points[0].item()} {points[1].item()} {points[2].item()}\n")

if __name__ == "__main__":
    model = OccupancyModel()
    model.load_state_dict(torch.load(MODEL_FILENAME, map_location=DEVICE))
    model.cuda()
    model.eval()

    test_loader = generate_data_loader(SHAPENET_CLASS_DIR, 'test.lst', batch_size=1)

    for batch_idx, data in enumerate(test_loader):
        pts, occupancies, sample_pointcloud, org_pointcloud = data

        write_point_cloud_to_xyz(org_pointcloud, './data/original_point_cloud_2.xyz')
        write_point_cloud_to_xyz(sample_pointcloud, './data/sample_point_cloud_2.xyz')

        torch.save(sample_pointcloud, './data/sample_pointcloud.pt')
        sample_pointcloud = sample_pointcloud.view(-1, POINTCLOUD_N, 3, 1).permute(0, 2, 1, 3).cuda()

        # f = partial(over_model_threshold, model, sample_pointcloud)
        # print('generating adaptive grid')
        # g = generate_adaptive_grid(32, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 3, f, True)
        # adaptive_grid_fn = 'phone_ag_32_3.txt'
        # print(f'saving adaptive grid to {generate_adaptive_grid}')
        # numpy.savetxt(generate_adaptive_grid, g.detach().numpy())

        g = generate_grid(32, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5)

        # uncomment to serialize grid to disk
        # non_adaptive_grid_fn = 'phone_g_32_3.txt'
        # print(f'saving adaptive grid to {non_adaptive_grid_fn}')
        # numpy.savetxt(non_adaptive_grid_fn, g.detach().numpy())

        occ = []
        with torch.no_grad():
            for p in g:
                c = p.view(-1, 1, 3, 1).permute(0, 2, 1, 3).cuda()
                pred = model(c, sample_pointcloud)
                c.cpu()
                occ.append(pred.cpu())
        print('saving results')
        numpy.savetxt('./data/phone_g_preds_32_3.txt', occ)

        pred = torch.tensor(numpy.loadtxt('./data/phone_g_preds_32_3.txt'), dtype=torch.float)
        pts = torch.tensor(numpy.loadtxt('./data/phone_g_32_3.txt'), dtype=torch.float)
        mask = pred > 0.6
        pointCloud = pts[mask]
        numpy.savetxt('./data/phone_32_3_ptcloud.xyz', pointCloud.detach().numpy())
        break


from itertools import tee
import numpy as np
import math

def distance_between_points(a, b):
    """
    Calculates the Euclidean distance between two points
    :param a: first point
    :param b: second point
    :return: Euclidean distance between a and b
    """
    return np.linalg.norm(np.array(b) - np.array(a))

def pairwise(iterable):
    """
    Returns an iterator over all pairs of elements in iterable
    :param iterable: iterable to iterate over
    :return: s -> (s0, s1), (s1, s2), (s2, s3), ...
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def es_points_along_line(start, end, r):
    """
    Equally spaced points along a line defined by start, end, and r
    :param start: start point
    :param end: end point
    :param r: maximum distance between points
    :return: list of equally spaced points along the line, separated by distance r
    """
    d = distance_between_points(start, end)
    n_points = int(np.ceil(d / r))
    if n_points > 1:
        step = d / (n_points - 1)
        for i in range(n_points):
            next_point = steer(start, end, step * i)
            yield next_point

def steer(start, end, d):
    """
    Return a point in the direction of end, that is distance away from start
    :param start: start point
    :param end: end point
    :param d: distance away from start
    :return: point in the direction of end, that is distance away from start
    """
    start, end = np.array(start), np.array(end)
    v = end - start
    u = v / (np.sqrt(np.sum(v ** 2)))
    steered_point = start + u * d
    return tuple(steered_point)

def check_node_in_ellipse(node, x_ellipse, y_ellipse, a, b, angle):
    """
    Check if node is within ellipse
    :param node: node to check
    :param x_ellipse: ellipse x coordinate
    :param y_ellipse: ellipse y coordinate
    :param a: ellipse a parameter
    :param b: ellipse b parameter
    :param angle: ellipse angle in radians
    :return: boolean, True if node is within ellipse, False otherwise
    """
    return (((((math.cos(angle)*(node[0] - x_ellipse) + math.sin(angle)*(node[1] - y_ellipse))**2)/(a**2)) + (((math.sin(angle)*(node[0] - x_ellipse) - math.cos(angle)*(node[1] - y_ellipse))**2)/(b**2))) <= 1)


# Native imports
import logging
import logging.config
from os import getenv
from os.path import exists
from yaml import safe_load

# Imports
from main import create_app

# Authorship Information
__author__ = "Islam Elkadi"
__copyright__ = "Copyright 2021, Thea Manager"
__credits__ = ["Islam Elkadi"]
__license__ = "N/A"
__version__ = "1.0.0"
__maintainer__ = "Islam Elkadi"
__email__ = "islam@theamanager.com"
__status__ = "Prototype"

# ---------------------------------------------------------------
#                           Configure Logging
# ---------------------------------------------------------------

def setup_logging(
    default_path="log_config.yaml", default_level=logging.INFO, env_key="LOG_CFG"
):
    """
    Setup logging configuration

    Parameters
    ----------

        default_path: str [required]
            file path to read logging configurations from

        default_level: required
            default logging level

        env_key: str [required]
            environment key for logging configuration
    """
    path = default_path
    value = getenv(env_key, None)

    if value:
        path = value

    if exists(path):
        with open(path, "rt") as f:
            configuration = safe_load(f.read())
        logging.config.dictConfig(configuration)
    else:
        logging.basicConfig(level=default_level)

# App object
application = create_app()

# Entry point
if __name__ == "__main__":
    setup_logging()
    application.run(host="0.0.0.0", port=5000, debug=True)


from datetime import datetime
from flask import request, session, Blueprint, make_response, render_template, redirect
from .models import Hacker
from hacker_server import db

bp = Blueprint('hacker_main', __name__, url_prefix='/')

@bp.route('/', methods=["POST", "GET"])
def index():
    '''초기 접속 시 실행할 함수'''
    return redirect('/hacker_home')

@bp.route('/hacker_home', methods=["POST", "GET"])
def hacker_home():
    '''해커 홈'''
    hacker = Hacker.query.order_by(Hacker.create_date.desc())
    context = hacker.paginate(per_page=10)
    return render_template(
        'index.html',
        context=context,
    )

@bp.route('/xss/', methods=["POST", "GET"])
def xss():
    hacker = Hacker()
    hacker.create_date = datetime.now()
    hacker.title = request.args.get('title')
    hacker.content = request.args.get('content')
    db.session.add(hacker)
    db.session.commit()
    return redirect(request.referrer)