from pathlib import WindowsPath
from typing import Counter
import numpy as np
from numpy.lib import utils
import Algo1
import predictCnn
import torch
import torchvision.transforms
import cv2 as cv2
import matplotlib.pyplot as plt
import coarseGrained
import cv2
import config
import utils
import time
from scipy.ndimage import gaussian_filter

def CNN(model, cropped_frames, Other_bounding_box, CONF_THRESHOLD, NMS_IOU_THRESH, ori_frame_shape):
    bboxes = []

    for idx in range(len(cropped_frames)):
        c_fra = cropped_frames[idx]

        input_size = 416

        #Rezising of the input frame to fit the model
        if (np.shape(c_fra)[0] < input_size) and (np.shape(c_fra)[1] < input_size):
            pil_frame, sqaure_shape = Algo1.size_up(c_fra, input_size)
        else:
            pil_frame = cv2.resize(c_fra, (416,416))
        pil_frame = pil_frame.astype(np.uint8)

        #Uncomment to show input for the model
        """cv2.imshow("Input frame", fra)
        k = cv2.waitKey(3) & 0xFF
        if k == 27:
            break
        q = input("Pres enter to continue, n for next model, q to exit")
        if (q == "q"):
            cv2.destroyAllWindows()
            exit()
        if (q == "n"):
            break"""

        ANCHORS = config.ANCHORS
        pil_fra_min = np.min(pil_frame)
        pil_fra_max = np.max(pil_frame)
        pil_fra = torch.from_numpy(np.array([pil_frame]))
        pil_fra = pil_fra.permute(0,3,1,2)
        pil_fra = pil_fra.float()

        pil_fra = (pil_fra - pil_fra_min) / (pil_fra_max - pil_fra_min)

        var = predictCnn.get_bboxes(
            pil_fra,
            model,
            NMS_IOU_THRESH,
            ANCHORS,
            CONF_THRESHOLD
        )

        #Uncomment to show preds on cropped frames
        #draw_boxes(var[0], pil_frame_crop)

        if np.shape(var) == (1,0):
            continue
        else:
            bboxes.append(Algo1.scale_bboxes(var[0], ori_frame_shape, Other_bounding_box[idx], sqaure_shape))

    return bboxes

def main():

    paths = ['test_frames/test_I_IL_01', 'test_frames/test_I_SI_01', 'test_frames/test_O_OP_01',
            'test_frames/test_O_CM_01', 'test_frames/test_O_OF_01']
    data_sets = []
    for p in paths:
        data_sets.append(utils.load_images_from_folder(p))

    paths_label = ['test_labels/label_I_IL_01', 'test_labels/label_I_SI_01', 'test_labels/label_O_OP_01',
                    'test_labels/label_O_CM_01', 'test_labels/label_O_OF_01']
    GTs = []
    for p in paths_label:
        GTs.append(utils.load_labels(p))

    gt_shows = []
    for p in paths_label:
        gt_shows.append(utils.load_labels_test(p))

    maps = []
    f_measures = []

    total_time = []
    Coarse_time = []
    Algo1_time = []
    CNN_time = []

    for i in range(len(data_sets)):
        data_set = data_sets[i]
        GT = GTs[i]
        gt_show = gt_shows[i]
        model = 'model_weights.h5'
        model = torch.load(model, map_location=torch.device('cuda'))
        model.eval()
        count = 0
        col_bboxes = []
        while (len(data_set)-1):
            t0 = time.time()
            print("While loop :", count ,"out of", len(data_set), end="\r")
            if(count == len(data_set) -1):
                break

            old_frame = data_set[count]
            new_frame = data_set[count+1]
            count += 1

            ori_frame_shape = np.shape(new_frame)
            #if ret == False:
            #   break
            # Block 1: Coarse grained
            gauss_sigma = 5
            old_frame = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
            old_frame = gaussian_filter(old_frame, sigma=gauss_sigma)
            c_grained, n_fram = coarseGrained.dense_optical_flow(cv2.calcOpticalFlowFarneback,
                        gauss_sigma, 5, new_frame, old_frame,
                        [0.5, 20, 50, 7, 20, 1.1, 0], True, True)

            #Show output of Coarse Grained
            """cv2.imshow("Original frame", c_grained)
            k = cv2.waitKey(3) & 0xFF
            if k == 27:
                break
            q = input("Pres enter to continue, n for next model, q to exit")
            if (q == "q"):
                cv2.destroyAllWindows()
                exit()
            if (q == "n"):
                break"""

            t1 = time.time()
            # Block 2: Algorithm 1
            pixel_thresh = 15
            Bounding_box = Algo1.Algorithm1(c_grained, pixel_thresh)
            #print("bbox",Bounding_box)

            Other_bounding_box = Bounding_box

            Other_bounding_box = []
            for i in range(len(Bounding_box)):
                if (Bounding_box[i][1][0]-Bounding_box[i][0][0])*(Bounding_box[i][1][1]-Bounding_box[i][0][1]) > 2000:
                    Other_bounding_box.append(Bounding_box[i])

            if len(Other_bounding_box) < 1:
                continue
            else:

                cropped_frames = utils.crop_pic(Other_bounding_box, new_frame)

                # Block 3: CNN object recognition
                NMS_IOU_THRESH = 0.45
                CONF_THRESHOLD = 0.05
                t2 = time.time()
                bboxes = CNN(model, cropped_frames, Other_bounding_box, CONF_THRESHOLD, NMS_IOU_THRESH, ori_frame_shape)

                #### Present results for each frame ####

                #Uncomment the following line to see the prediction on the frame
                utils.draw_boxes(bboxes, new_frame)

                #Uncomment the following line to see the label on the frame
                #utils.draw_boxes(gt_show[count - 1], new_frame)
                save_bbox = bboxes.copy()
                for box in save_bbox:
                    col_bboxes.append([count] + box)
                t3 = time.time()

            total_time.append(t3 - t0)
            Coarse_time.append(t1 - t0)
            Algo1_time.append(t2 - t1)
            CNN_time.append(t3 - t2)

        #Calculate mAP and f-measure

        Map, f_measure = utils.map_pred(col_bboxes, GT)
        Map = Map.cpu().detach().numpy()
        f_measure = f_measure.cpu().detach().numpy()

        f_measures.append(f_measure)
        maps.append(Map)
        print("mAP value:", Map)
        print("f-measure value:", f_measure)

    print("Average time per frame:")
    print(sum(total_time) / len(total_time))
    print("Avg. Coarse grained time:")
    print(sum(Coarse_time) / len(Coarse_time))
    print("Avg. Algo1 time:")
    print(sum(Algo1_time) / len(Algo1_time))
    print("Avg. CNN time:")
    print(sum(CNN_time) / len(CNN_time))

if __name__ == '__main__':
    main()


from tkinter import *
def btn_hit():
    global msg_on
    if msg_on == False:
        msg_on = True
        x.set("顯示文字")
    else:
        msg_on = False
        x.set("")
window = Tk()
window.title("Global Variable")

msg_on = False
x = StringVar()

label = Label(window, textvariable=x,
              fg="blue", bg="lightyellow",
              font ="Verdana 16 bold",
              width=25, height=2).pack()
btn = Button(window, text="Hit", command=btn_hit).pack()
window.mainloop()


from constants import spaceCharacters, digits, hexDigits, EOF
from inputstream import XMLInputStream
import re

class XMLTokenizer(object):
    def __init__(self, stream, encoding=None):
        # The stream holds all the characters.
        self.stream = XMLInputStream(stream, self, encoding)

        # Set of states and the initial state
        self.states = {
          "data":self.dataState,
          "tag":self.tagState,
          "endTag":self.endTagState,
          "endTagName":self.endTagNameState,
          "endTagNameAfter":self.endTagNameAfterState,
          "pi":self.piState,
          "piTarget":self.piTargetState,
          "piTargetAfter":self.piTargetAfterState,
          "piContent":self.piContentState,
          "piAfter":self.piAfterState,
          "markupDeclaration":self.markupDeclarationState,
          "comment":self.commentState,
          "commentDash":self.commentDashState,
          "commentEnd":self.commentEndState,
          "cdata":self.cdataState,
          "cdataBracket":self.cdataBracketState,
          "cdataEnd":self.cdataEndState,
          "doctype":self.doctypeState,
          "doctypeRootNameBefore":self.doctypeRootNameBeforeState,
          "doctypeRootName":self.doctypeRootNameState,
          "doctypeRootNameAfter":self.doctypeRootNameAfterState,
          "doctypeIdentifierDoubleQuoted":self.doctypeIdentifierDoubleQuotedState,
          "doctypeIdentifierSingleQuoted":self.doctypeIdentifierSingleQuotedState,
          "doctypeInternalSubset":self.doctypeInternalSubsetState,
          "doctypeInternalSubsetAfter":self.doctypeInternalSubsetAfterState,
          "doctypeTag":self.doctypeTagState,
          "doctypeMarkupDeclaration":self.doctypeMarkupDeclarationState,
          "doctypeComment":self.doctypeCommentState,
          "doctypeCommentDash":self.doctypeCommentDashState,
          "doctypeCommentEnd":self.doctypeCommentEndState,
          "doctypeEntity":self.doctypeEntityState,
          "doctypeEntityTypeBefore":self.doctypeEntityTypeBeforeState,
          "doctypeEntityParameterBefore":self.doctypeEntityParameterBeforeState,
          "doctypeEntityParameter":self.doctypeEntityParameterState,
          "doctypeEntityName":self.doctypeEntityNameState,
          "doctypeEntityNameAfter":self.doctypeEntityNameAfterState,
          "doctypeEntityValDoubleQuoted":self.doctypeEntityValDoubleQuotedState,
          "doctypeEntityValSingleQuoted":self.doctypeEntityValSingleQuotedState,
          "doctypeEntityValAfter":self.doctypeEntityValAfterState,
          "doctypeEntityIdentifier":self.doctypeEntityIdentifierState,
          "doctypeEntityIdentifierDoubleQuoted":self.doctypeEntityIdentifierDoubleQuotedState,
          "doctypeEntityIdentifierSingleQuoted":self.doctypeEntityIdentifierSingleQuotedState,
          "doctypeAttlist":self.doctypeAttlistState,
          "doctypeAttlistNameBefore":self.doctypeAttlistNameBeforeState,
          "doctypeAttlistName":self.doctypeAttlistNameState,
          "doctypeAttlistNameAfter":self.doctypeAttlistNameAfterState,
          "doctypeAttlistAttrname":self.doctypeAttlistAttrnameState,
          "doctypeAttlistAttrnameAfter":self.doctypeAttlistAttrnameAfterState,
          "doctypeAttlistAttrtype":self.doctypeAttlistAttrtypeState,
          "doctypeAttlistAttrtypeAfter":self.doctypeAttlistAttrtypeAfterState,
          "doctypeAttlistAttrdeclBefore":self.doctypeAttlistAttrdeclBeforeState,
          "doctypeAttlistAttrdecl":self.doctypeAttlistAttrdeclState,
          "doctypeAttlistAttrdeclAfter":self.doctypeAttlistAttrdeclAfterState,
          "doctypeAttlistAttrvalDoubleQuoted":self.doctypeAttlistAttrvalDoubleQuotedState,
          "doctypeAttlistAttrvalSingleQuoted":self.doctypeAttlistAttrvalSingleQuotedState,
          "doctypeNotation":self.doctypeNotationState,
          "doctypeNotationIdentifier":self.doctypeNotationIdentifierState,
          "doctypeNotationIdentifierDoubleQuoted":self.doctypeNotationIdentifierDoubleQuotedState,
          "doctypeNotationIdentifierSingleQuoted":self.doctypeNotationIdentifierSingleQuotedState,
          "doctypePi":self.doctypePiState,
          "doctypePiAfter":self.doctypePiAfterState,
          "doctypeBogusComment":self.doctypeBogusCommentState,
          "tagName":self.tagNameState,
          "emptyTag":self.emptyTagState,
          "tagAttributeNameBefore":self.tagAttributeNameBeforeState,
          "tagAttributeName":self.tagAttributeNameState,
          "tagAttributeNameAfter":self.tagAttributeNameAfterState,
          "tagAttributeValueBefore":self.tagAttributeValueBeforeState,
          "tagAttributeValueDoubleQuoted":self.tagAttributeValueDoubleQuotedState,
          "tagAttributeValueSingleQuoted":self.tagAttributeValueSingleQuotedState,
          "tagAttributeValueUnquoted":self.tagAttributeValueUnquotedState,
          "bogusComment":self.bogusCommentState
        }
        self.state = self.states["data"]

        # The current token being created
        self.currentToken = None

        # Entities
        self.entities = {
          "lt":"<",
          "gt":">",
          "amp":"&",
          "apos":"'",
          "quot":"\""
        }
        self.parameterEntities = {}
        self.attributeNormalization = []

        # Dealing with entities
        self.entityValueLen = 0
        self.charCount = 0
        self.entityCount = 0

        # Tokens yet to be processed.
        self.tokenQueue = []

    def __iter__(self):
        self.stream.reset()
        self.tokenQueue = []

        # Start processing. When EOF is reached self.state will return False
        # instead of True and the loop will terminate.
        while self.state():
            while self.tokenQueue:
                yield self.tokenQueue.pop(0)

    def consumeNumberEntity(self, isHex):
        allowed = digits
        radix = 10
        if isHex:
            allowed = hexDigits
            radix = 16

        char = u"\uFFFD"

        # Consume all the characters that are in range while making sure we
        # don't hit an EOF.
        value = self.stream.charsUntil(allowed, True)

        # Convert the set of characters consumed to an int.
        charAsInt = int(value, radix)

        # No NULL characters.
        # XXX any other characters?
        if charAsInt == 0:
            charAsInt = 65533

        # Convert the int value to an actual char
        try:
            # XXX We should have a separate function that does "int" to
            # "unicodestring" conversion since this doesn't always work
            # according to hsivonen. Also, unichr has a limitation of 65535
            char = unichr(charAsInt)
        except:
            # XXX parse error
            pass

        # Discard the ; if present. Otherwise, put it back on the queue and
        # invoke parseError on parser.
        c = self.stream.char()
        if c != ";":
            # XXX parse error
            self.stream.queue.append(c)
        return char

    def consumeEntity(self, fromAttribute=False):
        # The result of this function is a tuple consisting of the entity
        # value and whether it needs to be inserted into the stream or
        # simply appended as character data.
        c = self.stream.char()
        if c == "#":
            # Character reference (numeric entity).
            value = "&#"
            c = self.stream.char()
            if c == "x":
                c = self.stream.char()
                if c in hexdigits:
                    # Hexadecimal entity detected.
                    self.stream.queue.insert(0, c)
                    value = self.consumeNumberEntity(True)
                else:
                    value += "x"
            elif c in digits:
                # Decimal entity detected.
                self.stream.queue.insert(0, c)
                value = self.consumeNumberEntity(False)
            elif c == EOF:
                # XXX parse error
                pass
            else:
                # XXX parse error
                value += c
            return "Characters", value
        # Break out if we reach the end of the file
        elif c == EOF:
            # XXX parse error
            return "Characters", "&"
        else:
            # Named entity.
            end = ";"
            name = c + self.stream.charsUntil(";")

            # Check whether or not the last character returned can be
            # discarded or needs to be put back.
            c = self.stream.char()
            if c != ";":
                # XXX parse error
                end = ""

            if name in self.entities:
                if self.entityCount < 16:
                    self.entityCount += 1
                    value = self.entities[name]
                    if fromAttribute:
                        # This is a hack to make things "work". Or is it
                        # really the only good solution?
                        value = re.sub("\n", "
", value)
                        value = re.sub("\r", "
", value)
                        value = re.sub("\t", "	", value)
                        value = re.sub(" ", " ", value)
                        value = re.sub("\"", """, value)
                        value = re.sub("'", "'", value)
                    self.entityValueLen += len(value)
                    return "Stream", value
                else:
                    # XXX parse error
                    return "Characters", ""
            else:
                # XXX parse error
                return "Characters", "&" + name + end
        assert 0

    def consumeNumberEntityOnly(self):
        c = self.stream.char()
        value = "&"
        if c == EOF:
            self.stream.queue.insert(0, c)
        elif c != "#":
            value += c
        else:
            value += "#"
            c = self.stream.char()
            if c == "x":
                c = self.stream.char()
                if c in hexdigits:
                    # Hexadecimal entity detected.
                    self.stream.queue.insert(0, c)
                    value = self.consumeNumberEntity(True)
                else:
                    value += "x"
            elif c in digits:
                # Decimal entity detected.
                self.stream.queue.insert(0, c)
                value = self.consumeNumberEntity(False)
            elif c == EOF:
                # XXX parse error
                pass
            else:
                # XXX parse error
                value += c
        return value

    def consumeParameterEntity(self):
        name = self.stream.charsUntil(";")
        c = self.stream.char()
        if c != ";":
            # XXX parse error
            pass

        if name in self.parameterEntities and self.entityCount < 16:
            self.entityCount += 1
            value = self.parameterEntities[name]
            self.entityValueLen += len(value)
            return value
        else:
            # XXX parse error
            return ""

    def attributeNameExists(self, name):
        for x,y in self.currentToken["attributes"]:
            if x == name:
                return True
        return False

    def emitCurrentToken(self):
        if (self.currentToken["type"] == "StartTag" or
          self.currentToken["type"] == "EmptyTag") and\
          self.attributeNormalization:
            for token in self.attributeNormalization:
                if token["name"] == self.currentToken["name"]:
                    for attr in token["attrs"]:
                        if attr["dv"] != "" and not self.attributeNameExists(attr["name"]):
                            self.currentToken["attributes"].append([attr["name"], attr["dv"]])
        self.tokenQueue.append(self.currentToken)
        self.state = self.states["data"]

    def appendEntity(self):
        assert self.currentToken
        name = self.currentToken["name"]
        value = self.currentToken["value"]
        type = self.currentToken["type"]
        if type == "entity":
            if name not in self.entities:
                self.entities[name] = value
        elif type == "parameterEntity":
            if name not in self.parameterEntities:
                self.parameterEntities[name] = value
        else:
            assert 0
        self.state = self.states["doctypeInternalSubset"]

    # Below are the various tokenizer states worked out.

    def dataState(self):
        data = self.stream.char()
        if data == "&":
            entity = self.consumeEntity()
            if entity[0] == "Characters":
                self.tokenQueue.append({"type":"Characters","data":entity[1]})
            else:
                i = 0
                for x in entity[1]:
                    self.stream.queue.insert(i, x)
                    i += 1
        elif data == "<":
            self.state = self.states["tag"]
        elif data == EOF:
            # Tokenization ends.
            return False
        else:
            self.tokenQueue.append({"type":"Characters","data":data})
        return True

    def tagState(self):
        data = self.stream.char()
        if data == "/":
            self.state = self.states["endTag"]
        elif data == "?":
            self.state = self.states["pi"]
        elif data == "!":
            self.state = self.states["markupDeclaration"]
        elif data in spaceCharacters\
          or data == "<"\
          or data == ">"\
          or data == ":"\
          or data == EOF:
            # XXX parse error
            self.tokenQueue.append({"type":"Characters", "data":"<"})
            self.stream.queue.insert(0, data)
            self.state = self.states["data"]
        else:
            self.currentToken = {"type":"StartTag", "name":data, "attributes":[]}
            self.state = self.states["tagName"]
        return True

    def endTagState(self):
        data = self.stream.char()
        if data == ">":
            self.tokenQueue.append({"type":"EndTagShort"})
            self.state = self.states["data"]
        elif data in spaceCharacters\
          or data == "<"\
          or data == ":"\
          or data == EOF:
            # XXX parse error
            # XXX catch more "incorrect" characters here?
            self.tokenQueue.append({"type":"Characters", "data":"</"})
            self.stream.queue.insert(0, data)
            self.state = self.states["data"]
        else:
            self.currentToken = {"type":"EndTag", "name":data}
            self.state = self.states["endTagName"]
        return True

    def endTagNameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["endTagNameAfter"]
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        elif data == ">":
            self.emitCurrentToken()
        else:
            self.currentToken["name"] += data
        return True

    def endTagNameAfterState(self):
        data = self.stream.char()
        if data == ">":
            self.emitCurrentToken()
        elif data in spaceCharacters:
            pass
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            # XXX parse error
            pass
        return True

    def piState(self):
        data = self.stream.char()
        if data in spaceCharacters\
          or data == EOF:
            # XXX parse error
            # XXX catch more "incorrect" characters here?
            self.stream.queue.append("?")
            self.stream.queue.append(data)
            self.state = self.states["bogusComment"]
        else:
            self.currentToken = {"type":"Pi", "name":data, "data":""}
            self.state = self.states["piTarget"]
        return True

    def piTargetState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["piTargetAfter"]
        elif data == EOF:
            # XXX parse error
            # XXX catch more "incorrect" characters here?
            self.emitCurrentToken()
        elif data == "?":
            self.state = self.states["piAfter"]
        else:
            self.currentToken["name"] += data
        return True

    def piTargetAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        else:
            self.stream.queue.append(data)
            self.state = self.states["piContent"]
        return True

    def piContentState(self):
        data = self.stream.char()
        if data == "?":
            self.state = self.states["piAfter"]
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["data"] += data
        return True

    def piAfterState(self):
        data = self.stream.char()
        if data == ">":
            self.emitCurrentToken()
        elif data == "?":
            self.currentToken["data"] += "?"
        else:
            self.stream.queue.append(data)
            self.state = self.states["piContent"]
        return True

    # Markup declarations.
    def markupDeclarationState(self):
        charStack = [self.stream.char(), self.stream.char()]
        if charStack == ["-", "-"]:
            self.currentToken = {"type":"Comment", "data":""}
            self.state = self.states["comment"]
        else:
            for x in xrange(5):
                charStack.append(self.stream.char())
            if not EOF in charStack:
                n = "".join(charStack)
                if n == "[CDATA[":
                    self.state = self.states["cdata"]
                    return True
                if n == "DOCTYPE":
                    # XXX parse error
                    self.state = self.states["doctype"]
                    return True
            # XXX parse error
            self.stream.queue.extend(charStack)
            self.state = self.states["bogusComment"]
        return True

    # Handling of comments. They end after a literal '-->' sequence.
    def commentState(self):
        data = self.stream.char()
        if data == "-":
            self.state = self.states["commentDash"]
        elif data == EOF:
            # XXX parse error
            self.tokenQueue.append(self.currentToken)
            self.state = self.states["data"]
        else:
            self.currentToken["data"] += data + self.stream.charsUntil("-")
        return True

    def commentDashState(self):
        data = self.stream.char()
        if data == "-":
            self.state = self.states["commentEnd"]
        elif data == EOF:
            # XXX parse error
            self.tokenQueue.append(self.currentToken)
            self.state = self.states["data"]
        else:
            self.currentToken["data"] += "-" + data +\
              self.stream.charsUntil("-")
            # Consume the next character which is either a "-" or an EOF as
            # well so if there's a "-" directly after the "-" we go nicely to
            # the "comment end state" without emitting a ParseError() there.
            self.stream.char()
        return True

    def commentEndState(self):
        data = self.stream.char()
        if data == ">":
            self.tokenQueue.append(self.currentToken)
            self.state = self.states["data"]
        elif data == "-":
            self.currentToken["data"] += "-"
        elif data == EOF:
            # XXX parse error
            self.tokenQueue.append(self.currentToken)
            self.state = self.states["data"]
        else:
            self.currentToken["data"] += "--" + data
            self.state = self.states["comment"]
        return True

    # These states handle the last bit of <![CDATA[ foo ]]> blocks.
    def cdataState(self):
        data = self.stream.char()
        if data == "]":
            self.state = self.states["cdataBracket"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.tokenQueue.append({"type":"Characters", "data":
              data + self.stream.charsUntil("]")})
        return True

    def cdataBracketState(self):
        data = self.stream.char()
        if data == "]":
            self.state = self.states["cdataEnd"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.tokenQueue.append({"type":"Characters", "data":
              "]" + data + self.stream.charsUntil("]")})
            # Consume the next character which is either a "]" or an EOF as
            # well so if there's a "]" directly after the "]" we go nicely to
            # the "cdata end state" without emitting a ParseError() there.
            self.stream.char()
        return True

    def cdataEndState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["data"]
        elif data == "]":
            self.tokenQueue.append({"type":"Characters", "data":data})
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.tokenQueue.append({"type":"Characters", "data":"]]" + data})
            self.state = self.states["cdata"]
        return True

    # XXX should we emit doctype tokens and such?
    def doctypeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeRootNameBefore"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            self.stream.queue.append(data)
            self.state = self.states["bogusComment"]
        return True

    def doctypeRootNameBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == ">":
            self.state = self.states["data"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            self.state= self.states["doctypeRootName"]
        return True

    def doctypeRootNameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeRootNameAfter"]
        elif data == ">":
            self.state = self.states["data"]
        elif data == "[":
            self.state = self.states["doctypeInternalSubset"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeRootNameAfterState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["data"]
        elif data == "\"":
            self.state = self.states["doctypeIdentifierDoubleQuoted"]
        elif data == "'":
            self.state = self.states["doctypeIdentifierSingleQuoted"]
        elif data == "[":
            self.state = self.states["doctypeInternalSubset"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeIdentifierDoubleQuotedState(self):
        data = self.stream.char()
        if data == "\"":
            self.state = self.states["doctypeRootNameAfter"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeIdentifierSingleQuotedState(self):
        data = self.stream.char()
        if data == "'":
            self.state = self.states["doctypeRootNameAfter"]
        elif data == EOF:
            # XXX parse error?
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeInternalSubsetState(self):
        data = self.stream.char()
        if data == "<":
            self.state = self.states["doctypeTag"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        elif data == "%":
            self.stream.queue.extend(self.consumeParameterEntity())
        elif data == "]":
            self.state = self.states["doctypeInternalSubsetAfter"]
        else:
            pass
        return True

    def doctypeInternalSubsetAfterState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["data"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeTagState(self):
        data = self.stream.char()
        if data == "!":
            self.state = self.states["doctypeMarkupDeclaration"]
        elif data == "?":
            self.state = self.states["doctypePi"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeMarkupDeclarationState(self):
        charStack = [self.stream.char(), self.stream.char()]
        if charStack == ["-", "-"]:
            self.state = self.states["doctypeComment"]
        else:
            for x in xrange(4):
                charStack.append(self.stream.char())
            if not EOF in charStack:
                if "".join(charStack) == "ENTITY":
                    self.state = self.states["doctypeEntity"]
                    return True
                data = self.stream.char()
                charStack.append(data)
                if data != EOF:
                    if "".join(charStack) == "ATTLIST":
                        self.state = self.states["doctypeAttlist"]
                        return True
                    data = self.stream.char()
                    charStack.append(data)
                    if data != EOF:
                        if "".join(charStack) == "NOTATION":
                             self.state = self.states["doctypeNotation"]
                             return True
            # XXX parse error
            self.stream.queue.extend(charStack)
            self.state = self.states["doctypeBogusComment"]
        return True

    # <!-- ....
    def doctypeCommentState(self):
        data = self.stream.char()
        if data == "-":
            self.state = self.states["doctypeCommentDash"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeCommentDashState(self):
        data = self.stream.char()
        if data == "-":
            self.state = self.states["doctypeCommentEnd"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeComment"]
        return True

    def doctypeCommentEndState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["doctypeInternalSubset"]
        elif data == "-":
            self.state = self.states["doctypeCommentDash"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeComment"]
        return True

    # <!ENTITY
    def doctypeEntityState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeEntityTypeBefore"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeEntityTypeBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == "%":
            self.state = self.states["doctypeEntityParameterBefore"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.currentToken = {"type":"entity", "name":data, "value":""}
            self.state = self.states["doctypeEntityName"]
        return True

    def doctypeEntityParameterBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeEntityParameter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeEntityParameterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.currentToken = {"type":"parameterEntity", "name":data,
              "value":""}
            self.state = self.states["doctypeEntityName"]
        return True

    def doctypeEntityNameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeEntityNameAfter"]
        elif data == EOF:
            # XXX parse error
            self.currentToken = None
            self.state = self.states["data"]
        else:
            self.currentToken["name"] += data
        return True

    def doctypeEntityNameAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == "\"":
            self.state = self.states["doctypeEntityValDoubleQuoted"]
        elif data == "'":
            self.state = self.states["doctypeEntityValSingleQuoted"]
        elif data == EOF:
            # XXX parse error
            self.currentToken == None
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeEntityIdentifier"]
        return True

    def doctypeEntityValDoubleQuotedState(self):
        data = self.stream.char()
        # XXX "&" and "%"
        if data == "\"":
            self.state = self.states["doctypeEntityValAfter"]
        elif data == "&":
            self.currentToken["value"] += self.consumeNumberEntityOnly()
        elif data == EOF:
            # XXX parse error
            self.currentToken == None
            self.state = self.states["data"]
        else:
            self.currentToken["value"] += data
        return True

    def doctypeEntityValSingleQuotedState(self):
        data = self.stream.char()
        # XXX "&" and "%"
        if data == "'":
            self.state = self.states["doctypeEntityValAfter"]
        elif data == "&":
            self.currentToken["value"] += self.consumeNumberEntityOnly()
        elif data == EOF:
            # XXX parse error
            self.currentToken == None
            self.state = self.states["data"]
        else:
            self.currentToken["value"] += data
        return True

    def doctypeEntityValAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == ">":
            self.appendEntity()
        elif data == EOF:
            # XXX parse error
            self.currentToken == None
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeEntityIdentifierState(self):
        data = self.stream.char()
        if data == ">":
            self.appendEntity()
        elif data == "\"":
            self.state = self.states["doctypeEntityIdentifierDoubleQuoted"]
        elif data == "'":
            self.state = self.states["doctypeEntityIdentifierSingleQuoted"]
        elif data == EOF:
            # XXX parse error
            self.currentToken = None
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeEntityIdentifierDoubleQuotedState(self):
        data = self.stream.char()
        if data == "\"":
            self.state = self.states["doctypeEntityIdentifier"]
        elif data == EOF:
            # XXX parse error
            self.currentToken = None
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeEntityIdentifierSingleQuotedState(self):
        data = self.stream.char()
        if data == "'":
            self.state = self.states["doctypeEntityIdentifier"]
        elif data == EOF:
            # XXX parse error
            self.currentToken = None
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeAttlistState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeAttlistNameBefore"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeAttlistNameBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization.append({"name":data, "attrs":[]})
            self.state = self.states["doctypeAttlistName"]
        return True

    def doctypeAttlistNameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeAttlistNameAfter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["name"] += data
        return True

    def doctypeAttlistNameAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == ">":
            self.state = self.states["doctypeInternalSubset"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["attrs"].append({"name":data, "type":"", "dv":""})
            self.state = self.states["doctypeAttlistAttrname"]
        return True

    def doctypeAttlistAttrnameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeAttlistAttrnameAfter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["attrs"][-1]["name"] += data
        return True

    def doctypeAttlistAttrnameAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["attrs"][-1]["type"] += data
            self.state = self.states["doctypeAttlistAttrtype"]
        return True

    def doctypeAttlistAttrtypeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeAttlistAttrtypeAfter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["attrs"][-1]["type"] += data
        return True

    def doctypeAttlistAttrtypeAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == "#":
            self.state = self.states["doctypeAttlistAttrdeclBefore"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeAttlistAttrdeclBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeBogusComment"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeAttlistAttrdecl"]
        return True

    def doctypeAttlistAttrdeclState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeAttlistAttrdeclAfter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeAttlistAttrdeclAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            pass
        elif data == ">":
            self.state = self.states["doctypeInternalSubset"]
        elif data == "\"":
            self.state = self.states["doctypeAttlistAttrvalDoubleQuoted"]
        elif data == "'":
            self.state = self.states["doctypeAttlistAttrvalSingleQuoted"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.attributeNormalization[-1]["attrs"].append({"name":data, "type":"", "dv":""})
            self.state = self.states["doctypeAttlistAttrname"]
        return True

    def doctypeAttlistAttrvalDoubleQuotedState(self):
        data = self.stream.char()
        if data == "\"":
            self.state = self.states["doctypeAttlistNameAfter"]
        elif data == "%":
            raise NotSupportedError
        elif data == "&":
            raise NotSupportedError
        else:
            self.attributeNormalization[-1]["attrs"][-1]["dv"] += data
        return True

    def doctypeAttlistAttrvalSingleQuotedState(self):
        data = self.stream.char()
        if data == "'":
            self.state = self.states["doctypeAttlistNameAfter"]
        elif data == "%":
            raise NotSupportedError
        elif data == "&":
            raise NotSupportedError
        else:
            self.attributeNormalization[-1]["attrs"][-1]["dv"] += data
        return True

    # <!NOTATION
    def doctypeNotationState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["doctypeNotationIdentifier"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypeBogusComment"]
        return True

    def doctypeNotationIdentifierState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["doctypeInternalSubset"]
        elif data == "\"":
            self.state = self.states["doctypeNotationIdentifierDoubleQuoted"]
        elif data == "'":
            self.state = self.states["doctypeNotationIdentifierSingleQuoted"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeNotationIdentifierDoubleQuotedState(self):
        data = self.stream.char()
        if data == "\"":
            self.state = self.states["doctypeNotationIdentifier"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypeNotationIdentifierSingleQuotedState(self):
        data = self.stream.char()
        if data == "'":
            self.state = self.states["doctypeNotationIdentifier"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypePiState(self):
        data = self.stream.char()
        if data == "?":
            self.state = self.states["doctypePiAfter"]
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            pass
        return True

    def doctypePiAfterState(self):
        data = self.stream.char()
        if data == ">":
            self.state = self.states["doctypeInternalSubset"]
        elif data == "?":
            pass
        elif data == EOF:
            # XXX parse error
            self.state = self.states["data"]
        else:
            self.state = self.states["doctypePiState"]
        return True

    # Bogus "comments" inside a doctype
    def doctypeBogusCommentState(self):
        self.stream.charsUntil(">")
        self.stream.char()
        self.state = self.states["doctypeInternalSubset"]
        return True

    # Tag name of a start or empty tag.
    def tagNameState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["tagAttributeNameBefore"]
        elif data == ">":
            self.emitCurrentToken()
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        elif data == "/":
            self.state = self.states["emptyTag"]
        else:
            self.currentToken["name"] += data
        return True

    def emptyTagState(self):
        data = self.stream.char()
        if data == ">":
            self.currentToken["type"] = "EmptyTag"
            self.emitCurrentToken()
        else:
            # XXX parse error
            self.stream.queue.insert(0, data)
            self.state = self.states["tagAttributeNameBefore"]
        return True

    def tagAttributeNameBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.stream.charsUntil(spaceCharacters, True)
        elif data == ">":
            self.emitCurrentToken()
        elif data == "/":
            self.state = self.states["emptyTag"]
        elif data == ":":
            # XXX parse error
            pass
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"].append([data, ""])
            self.state = self.states["tagAttributeName"]
        return True

    def tagAttributeNameState(self):
        data = self.stream.char()
        leavingThisState = True
        if data == "=":
            self.state = self.states["tagAttributeValueBefore"]
        elif data == ">":
            # Token is emitted after attributes are checked.
            pass
        elif data in spaceCharacters:
            self.state = self.states["tagAttributeNameAfter"]
        elif data == "/":
            self.state = self.states["emptyTag"]
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
            leavingThisState = False
        else:
            self.currentToken["attributes"][-1][0] += data
            leavingThisState = False

        if leavingThisState:
            # Attributes are not dropped at this stage. That happens when the
            # start tag token is emitted so values can still be safely appended
            # to attributes, but we do want to report the parse error in time.
            for name, value in self.currentToken["attributes"][:-1]:
                if self.currentToken["attributes"][-1][0] == name:
                    # XXX parse error
                    pass
            if data == ">":
                self.emitCurrentToken()
        return True

    def tagAttributeNameAfterState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.stream.charsUntil(spaceCharacters, True)
        elif data == "=":
            self.state = self.states["tagAttributeValueBefore"]
        elif data == ">":
            self.emitCurrentToken()
        elif data == "/":
            self.state = self.states["emptyTag"]
        elif data == ":":
            # XXX parse error
            pass
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"].append([data, ""])
            self.state = self.states["tagAttributeName"]
        return True

    def tagAttributeValueBeforeState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.stream.charsUntil(spaceCharacters, True)
        elif data == "\"":
            self.state = self.states["tagAttributeValueDoubleQuoted"]
        elif data == "'":
            self.state = self.states["tagAttributeValueSingleQuoted"]
        elif data == "&":
            self.stream.queue.append(data);
            self.state = self.states["tagAttributeValueUnquoted"]
        elif data == ">":
            self.emitCurrentToken()
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"][-1][1] += data
            self.state = self.states["tagAttributeValueUnquoted"]
        return True

    def tagAttributeValueDoubleQuotedState(self):
        data = self.stream.char()
        if data == "\"":
            self.state = self.states["tagAttributeNameBefore"]
        elif data == "&":
            entity = self.consumeEntity(True)
            if entity[0] == "Characters":
                self.currentToken["attributes"][-1][1] += entity[1]
            else:
                i = 0
                for x in entity[1]:
                    self.stream.queue.insert(i, x)
                    i += 1
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"][-1][1] += data +\
              self.stream.charsUntil(("\"", "&"))
        return True

    def tagAttributeValueSingleQuotedState(self):
        data = self.stream.char()
        if data == "'":
            self.state = self.states["tagAttributeNameBefore"]
        elif data == "&":
            entity = self.consumeEntity(True)
            if entity[0] == "Characters":
                self.currentToken["attributes"][-1][1] += entity[1]
            else:
                i = 0
                for x in entity[1]:
                    self.stream.queue.insert(i, x)
                    i += 1
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"][-1][1] += data +\
              self.stream.charsUntil(("'", "&"))
        return True

    def tagAttributeValueUnquotedState(self):
        data = self.stream.char()
        if data in spaceCharacters:
            self.state = self.states["tagAttributeNameBefore"]
        elif data == "&":
            entity = self.consumeEntity(True)
            if entity[0] == "Characters":
                self.currentToken["attributes"][-1][1] += entity[1]
            else:
                i = 0
                for x in entity[1]:
                    self.stream.queue.insert(i, x)
                    i += 1
        elif data == ">":
            self.emitCurrentToken()
        elif data == EOF:
            # XXX parse error
            self.emitCurrentToken()
        else:
            self.currentToken["attributes"][-1][1] += data +\
              self.stream.charsUntil(frozenset(("&", ">","<")) | spaceCharacters)
        return True

    # Consume everything up and including > and make it a comment.
    def bogusCommentState(self):
        self.tokenQueue.append({"type": "Comment", "data": self.stream.charsUntil(">")})
        self.stream.char()
        self.state = self.states["data"]
        return True


import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
from Functions import view, analysis, showScoreResults
# import face_extraction
# import sobel_features
# import hog_features
# import OCS_hog_train
# import OCS_sobel_train
# import SVC_hog_train
# import SVC_sobel_train

if __name__ == '__main__':

    path = "C:\\Users\\stav\\Desktop\\EmotionRecognitionAI\\venv\\src\\samples\\validation\\shock_9.jpg"
    view(path)
    analysis()
    showScoreResults()


from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    fig = plt.figure()
    ax = plt.axes(projection='3d')

    zline = np.linspace(0, 15, 1000)
    xline = np.sin(zline)
    yline = np.cos(zline)

    ax.plot3D(xline, yline, zline)

    plt.show()


# Main code
from sklearn.ensemble import RandomForestClassifier

from data.consts import *
from base import extract

if __name__ == "__main__":
    dt = extract(RandomForestClassifier,
                 CONFLICTS_PATH,
                 CONFLICTS_DATA_TYPES,
                 hasHeaders=CONFLICTS_HAS_HEADER,
                 headers=CONFLICTS_HEADERS)

    print(str(dt))


#!/usr/bin/env python3
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog

import xml.etree.ElementTree as ET

class GameState():
	"""Containing progress of a player - the state number and inventory."""
	def __init__(self):
		self.statenumber=1
		self.inventory=["Sword","Silver key","Plasma gun"]
		#self.inventory=[]

class MainWindow(tk.Frame):

	def __init__(self, master=None):
		"""Initializes the window, with all the widgets.
		Widgets are not visible outside of this method, but their communication variables are."""
		tk.Frame.__init__(self,master)
		self.grid()

		# Game state: statenumber, inventory
		self.gs = GameState()
		self.gs.statenumber=0

		loadGameButton=tk.Button(self, text="Load world", command=self.load_world_callback)
		loadGameButton.grid(row=0, column=0)

		loadProgressButton=tk.Button(self, text="Load progress", command=self.load_progress_callback)
		loadProgressButton.grid(row=0, column=1)

		saveProgressButton=tk.Button(self, text="Save progress", command=self.save_progress_callback)
		saveProgressButton.grid(row=0, column=2)

		showInventoryButton=tk.Button(self, text="Show inventory", command=self.show_inventory_callback)
		showInventoryButton.grid(row=0, column=3)

		showAboutButton=tk.Button(self, text="About", command=self.show_about_callback)
		showAboutButton.grid(row=0, column=4)

		showExitButton=tk.Button(self, text="Quit", command=self.quit)
		showExitButton.grid(row=0, column=5)

		self.stateDescriptionVar=tk.StringVar()
		stateDescription=tk.Label(self, width=60, height=8, textvariable=self.stateDescriptionVar)
		stateDescription.grid(row=1, column=0, columnspan=6)

		self.statePossibilitiesVar=tk.StringVar()
		statePossibilities=tk.Listbox(self, width=50, height=5, listvariable=self.statePossibilitiesVar)
		statePossibilities.grid(row=2, column=0, columnspan=5)

		chooseButton=tk.Button(self, text="Go", command=self.next_state_callback)
		chooseButton.grid(row=2, column=5)

		self.stateBarVar=tk.StringVar()
		self.stateBarVar.set("Insert copyright note here!")
		stateBar=tk.Label(self, textvariable=self.stateBarVar)
		stateBar.grid(row=3, column=0, columnspan=6)

	def load_world_callback(self):
		pathToFile=filedialog.askopenfilename(defaultextension=".xml", filetypes=[("Dungeon in XML",".xml")], title="Load world")
		if pathToFile!="":
			gs.statenumber=1
			gs.inventory=[]
			#parse XML
			self.xmlFile=ET.parse(pathToFile)
			#set current state

			self._load_state_data(1)

	def load_progress_callback(self):
		pathToFile=filedialog.askopenfilename(defaultextension=".dsw", filetypes=[("Saved game",".dsv")], title="Load progress")

	def save_progress_callback(self):
		pathToFile=filedialog.asksaveasfilename(defaultextension=".dsw", filetypes=[("Saved game",".dsv")], title="Save progress")

	def show_inventory_callback(self):
		inv_string=""
		for item in self.gs.inventory:
			inv_string=inv_string+item+"\n"
		messagebox.showinfo("Inventory",inv_string)

	def show_about_callback(self):
		messagebox.showinfo("About","Dungeons of XML, (C) Blah Blah 2016")

	def next_state_callback(self):
		pass

	"""Reads the state from XML, provides state description and possibilities"""
	def _load_state_data(self, sn):
		# iterate over the states to find the desired one
		for s in self.xmlFile:
			n=int(s.get("n"))
			if n==sn:
				#if this is the desired state
				desc=s.find("d").text
				self.stateDescriptionVar=desc

app = MainWindow()
app.master.title("Dungeons of XML")
app.mainloop()


# Two Pointers; string

# Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
#
# Input: "hello"
# Output: "holle"
# Example 2:
#
# Input: "leetcode"
# Output: "leotcede"
# Note:
# The vowels does not include the letter "y".
class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vow = 'aeiouAEIOU'
        vowList = []
        splitList = re.split('a|e|i|o|u|A|E|I|O|U',s)
        for i in range(len(s)):
            if s[i] in vow:
                vowList.append(s[i])
        output = splitList[0]
        for j in range(1,len(splitList)):
            output = output + vowList[j*-1] + splitList[j]
        return output

LeetCode/345 Reverse Vowels of a String.py


from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm
_nav = ["instructors","classes","projects","tools","about us","join us"]

def nav(request):
    return dict(
        current = request.path.split('/')[1] or 'home',
        nav = _nav,
        STATIC_URL = settings.STATIC_URL,
        auth_form = AuthenticationForm,
        app_path = "/admin/login/",
        next = request.path,
        settings = settings,
        )


# -*- coding: utf-8 -*-
import argparse
import pandas as pd
import print_result

def count_unk(path, UNK_TAG = '<unk>'):
    """
    path: Path to a space-separated file
    for [NT-OTH-1] in tech report
    """
    unk, total = 0, 0
    with open(path,'r',encoding='utf8') as f:
        tokens = [token for line in f.readlines() for token in line.split()]
        total = len(tokens)
        unk = sum([1 for token in tokens if UNK_TAG in token])
    return unk,total

def print_title(name, **kwargs):
    print(f"# Analysis of {name}")
    for kw,arg in kwargs.items():
        print(f"{kw}={arg}")

def parse_seg_file(seg_path):
    """
    Returns:
    -----------
        linenos: list of int. ordered by seg; corresponding to metadata
        temps2sents: dict. (states) -> [([phrases], lineno_in_seg_txt)]
            Example:
            key: (114, 201, 207, 184, 149, 252, 122, 75)
            value: [(['Each', 'banana', 'costs $ <num>',
                '. How much', 'do <num>', 'bananas', 'cost', '? <eos>'], 0)]
        top_temps: list of temps2sents keys, sorted by frequency of samples
    """
    from template_extraction import group_by_template
    linenos = []
    with open(seg_path,'r',encoding='utf8') as f:
        lines = f.readlines()
        for line in lines:
            if line.startswith('D label_train(): corpus.train_mb2linenos='): # HACK Don't contain '|'
                linenos = [ int(strno) for strno in line.strip().split('=')[1].split()]
                break
    temps2sents = group_by_template(seg_path,0) # startlineno=0; returns a label-tup -> [(phrase-list, lineno), ...] map
    top_temps = sorted(list(temps2sents.keys()), key=lambda x: -len(temps2sents[x]))
    return linenos, temps2sents, top_temps

def re_sort_metadata(metadata_path, linenos, new_idxname):
    try:
        metadata = pd.read_csv(metadata_path, sep='\t', header=0)
    except FileNotFoundError:
        return None

    # Sort metadata by linenos s.t. the idx match: metadata and temps2sents and seg file
    # 1. Sort linenos
    #   FROM  linenos[seg_index] = corresponding index in metadata
    #   TO    linenos[metadata] = corresponding index in seg_index
    linenos = [b for a,b in sorted(zip(linenos, range(len(linenos))), key=lambda x: x[0])]
    # 2. Add metadata col
    metadata[new_idxname] = linenos
    metadata = metadata.sort_values(by=new_idxname)
    metadata = metadata.set_index(new_idxname)
    return metadata

def analyze_seg(data,metadata_path,seg_path, k, n, pure_path=''):
    """
    Give statistics according to given metadata and segmentation
    """
    print_title("segmentation", metadata_path=metadata_path,seg_path=seg_path,k=k,n=n)

    def specific_top_templates(temps2sents,metadata, attribute, metadata_colnames,
            pure = False):
        """
        Parameters:
        -----------
            attribute:  str
                e.g. 'solution type'
            pure:  bool
                Whether print templates that is 'Addition' only (or so). Must match attribute
        """
        if metadata is None:
            return None

        # sort solution types (stype, e.g. 'Addition') by their frequencies (counts)
        from collections import Counter
        stype_counts = Counter(metadata[attribute])
        stypes = [stype for stype, count in sorted(list(stype_counts.items()), key=lambda x: -x[1])]

        # empty dictionary: stype -> { (temps) -> [sample sents] }
        stype2templates = dict(zip(stypes, [dict() for i in range(len(stypes))]))

        # stype -> [pure top_temps]
        pure_templates = dict()

        for temp, sents in temps2sents.items():
            for (phrases,lineno_in_seg_txt) in sents:
                stype = metadata[attribute][lineno_in_seg_txt]
                if temp not in stype2templates[stype]:
                    stype2templates[stype][temp] = []
                stype2templates[stype][temp].append((phrases,lineno_in_seg_txt))
        for stype in stypes:
            if stype_counts[stype] < 5:     # HACK to avoiding printing stypes of little samples
                continue
            print(f"## {stype} ({stype_counts[stype]} samples)")
            stype_temps2sents = stype2templates[stype]
            top_temps = sorted(list(stype_temps2sents.keys()), key=lambda x: -len(stype_temps2sents[x]))

            # For correct statistics, use temps2sents instead of stype_temps2sents below
            filters = {attribute:[stype]} if pure else None
            printed = print_result.top_templates_from_train(top_temps,temps2sents,metadata,
                metadata_colnames=metadata_colnames, n_toptemps=k, n_samples=n, filters=filters)
            if pure:
                pure_templates[stype] = [top_temps[p] for p in printed]

        if pure:
            with open(pure_path,'w') as f:
                f.writelines([f"{attribute}|{s}|||{' '.join([ ','.join([str(tt) for tt in t]) for t in pure_templates[s]])}\n" for s in stypes if s in pure_templates.keys()])

    linenos, temps2sents, top_temps = parse_seg_file(seg_path)
    metadata = re_sort_metadata(metadata_path, linenos, new_idxname='seg_linenos')

    # Evaluate the quality of segmentation
    print("# Overall - top templates")
    print_result.top_templates_from_train(top_temps, temps2sents, metadata, metadata_colnames=[],n_toptemps=k, n_samples=n) #'solution type','source','question'

    #print("# Solution type - top templates")
    #specific_top_templates(temps2sents,metadata, 'solution type', metadata_colnames=['solution type','source'], pure=False)

    #print('# Dataset - top templates')
    #specific_top_templates(temps2sents,metadata, 'source', metadata_colnames=['solution type','source'], pure=False)

    if pure_path is not '':
        print('# Pure templates: specific solution type')
        specific_top_templates(temps2sents,metadata, 'solution type', metadata_colnames=['solution type','source'], pure=True)

def analyze_gen(data, metadata_path, gen_path, startlineno=0, seg_path=''):
    """
    Give statistics according to metadata & generation file
    Adapted from group_by_template(fi, startlineno) in template_extraction.py
    1. Statistics: How many samples use which template? Compare to training data distribution?
    """

    print_title("generation", data=data, metadata_path=metadata_path, gen_path=gen_path)

    _,seg_temps2sents,_ = parse_seg_file(seg_path) if seg_path!='' else None,{},None

    import re
    from collections import defaultdict
    seg_patt = re.compile('([^\|]+)\|(\d+)') # detects segments
    temps2sents = defaultdict(list)
    lineno = startlineno

    try:
        metadata = pd.read_csv(metadata_path, sep='\t', header=0)
        conditions = ['' for i in range(metadata.shape[0])] # metadata.shape == (#rows, #cols)
    except FileNotFoundError:
        metadata = None

    #metadata = None #HACK  # cuz the linenos aren't for #alltmplt gen

    with open(gen_path, 'r', encoding='utf-8') as f:
        for line in f:
            if line.startswith('__start'):
                state = None
                condition = []
                for token in line.split():
                    if token.startswith('__start'):
                        assert state == None
                        state = token[8:-2]
                    elif token.startswith('__end'):
                        assert state == token[6:-2]
                        if metadata is not None:
                            conditions[lineno] += f'{state}:{" ".join(condition)}  '
                        state = None
                        condition = []
                    else:
                        condition.append(token)
            elif '|||' in line:
                mwp, seqs = line.split('|||')
                seq = seg_patt.findall(seqs.strip())
                wordseq, labeseq = zip(*seq) # 2 tuples
                wordseq = [phrs.strip() for phrs in wordseq]
                labeseq = tuple(int(labe) for labe in labeseq)
                temps2sents[labeseq].append((wordseq, lineno))  #mwp,
                lineno += 1

    top_temps = sorted(list(temps2sents.keys()), key=lambda x: -len(temps2sents[x]))
    if metadata is not None:
        metadata['conditions'] = conditions
        print_result.top_templates_from_train(top_temps, temps2sents, metadata,
            metadata_colnames=['conditions'], n_toptemps=999, n_samples=99999, seg_temps2sents=seg_temps2sents, n_examples=2)
    else:
        print_result.top_templates_from_train(top_temps, temps2sents, None,
            metadata_colnames=[], n_toptemps=999, n_samples=99999, seg_temps2sents=seg_temps2sents, n_examples=2)

#: err print
def eprint(*args, **kwargs):
    #print(*args, file=sys.stderr, **kwargs)
    pass

def get_pure_toptemps(pure_path, some_types):
    pure_temps = [] # [(attr,stype,[temps])]    e.g. ('solution type','Addition',[(0,1,2),(3,4,5)] )
    with open(pure_path) as f:
        for line in f:
            info , temps = line.split('|||')
            attr, stype = info.split('|')   # 'solution type', 'Addition'
            temps = [tuple(int(i) for i in t.split(',')) for t in temps.split(' ')]
            if stype in some_types:
                pure_temps.extend(temps)
    return pure_temps

parser = argparse.ArgumentParser(description='')
parser.add_argument('-data', type=str, default='', help='path to data dir')
parser.add_argument('-tagged_fi', type=str, default='', help='path to tagged file i.e. segmentation')
parser.add_argument('-gen_fi', type=str, default='', help='path to generation file')
parser.add_argument('-pure', type=str, default='', help='path to pure_temps')

parser.add_argument('-a_seg', action='store_true', help='Analysis segmentation file')
parser.add_argument('-a_gen', action='store_true', help='Analyze generation file')

if __name__ == '__main__':
    args = parser.parse_args()
    print(args)

    #org_unk, org_ttl = count_unk('segs/seg-otherTrain-100-55-5-far-NER-no_test.txt')
    #new_unk, new_ttl = count_unk('segs/seg-otherTrain-100-55-5-far-NER-no_test-unk.txt')
    #print(org_unk,org_ttl,org_unk/org_ttl)
    #print(new_unk,new_ttl,new_unk/new_ttl)
    DATA = args.data
    SEG = args.tagged_fi
    GEN = args.gen_fi
    PURE = args.pure
    #DATA='/Users/shanglinghsu/mwp/Datasets/ai2-ilds-train-valid/ai2-ilds-train-valid-concated'
    #SEG = '/Users/shanglinghsu/mwp/ntg2/segs/seg-ai2-cmds-100-55-5-far-NER.txt'
    #GEN = '/Users/shanglinghsu/mwp/ntg2/gens/gen-ai2-ilds-100-55-5-far-NER-pure_add-sub.md'
    if args.a_seg:
        analyze_seg(data=DATA, metadata_path=DATA+'/metadata_train.tsv', seg_path=SEG,
            k=100, n=10, pure_path=PURE)
    if args.a_gen:
        analyze_gen(data=DATA, metadata_path=DATA+'/metadata_valid.tsv', gen_path=GEN, seg_path=SEG)

    #PURE = 'pure_temps.txt'
    #get_pure_toptemps(PURE,'Addition')


'''
问题描述：给一个<Point>的List p，
求满足p[i].x+p[j].x和p[i].y+p[j].y（i < j)都能被2整除的(i,j)对数。
示例：
输入: p = [[1,2],[3,4],[5,6]]
输出: 3
解释:
p[0],p[1],p[2]两两组合，他们x与y之和都能被2整除。
思路：扫描p，计算 <奇数，奇数> <偶数，偶数> <奇数，偶数> <偶数，奇数>的组合有多少个

'''

def pairNumbers(p):
    # Write your code here
    odd_odd = 0
    even_even = 0
    odd_even = 0
    even_odd = 0
    for i in range(len(p)):
        #
        if p[i].x % 2 == 1 and p[i].y % 2 == 1:
            odd_odd += 1
        elif p[i].x % 2 == 0 and p[i].y % 2 == 0:
            even_even += 1
        elif p[i].x % 2 == 1 and p[i].y % 2 == 0:
            odd_even += 1
        else:
            even_odd += 1

    sum = int(
        odd_odd * (odd_odd - 1) / 2 + even_even * (even_even - 1) / 2 + even_odd * (even_odd - 1) / 2 + odd_even * (
                    odd_even - 1) / 2)
    return sum


from itertools import chain, combinations, compress, groupby, product
from math import comb
from typing import List, Optional

import numpy as np
from pymatgen.analysis.interface_reactions import InterfacialReactivity
from pymatgen.analysis.phase_diagram import GrandPotentialPhaseDiagram, PhaseDiagram
from pymatgen.core.composition import Element
from pymatgen.entries.computed_entries import ComputedEntry
from tqdm.auto import tqdm

from rxn_network.core import Enumerator, Reaction
from rxn_network.costs.calculators import Calculator, ChempotDistanceCalculator
from rxn_network.entries.entry_set import GibbsEntrySet
from rxn_network.enumerators.utils import (
    apply_calculators,
    filter_entries_by_chemsys,
    get_computed_rxn,
    get_entry_by_comp,
    get_open_computed_rxn,
    get_total_chemsys,
    group_by_chemsys,
    initialize_calculators,
    initialize_entry,
)
from rxn_network.reactions import ComputedReaction
from rxn_network.thermo.chempot_diagram import ChempotDiagram

class MinimizeGibbsEnumerator(Enumerator):
    """
    Enumerator for finding all reactions between two reactants that are predicted by
    thermodynamics; i.e., they appear when taking the convex hull along a straight
    line connecting any two phases in G-x phase space. Identity reactions are
    automatically excluded.
    """

    def __init__(
        self,
        precursors: Optional[List[str]] = None,
        target: Optional[str] = None,
        calculators: Optional[List[str]] = None,
    ):
        """
        Args:
            precursors: Optional formulas of precursors.
            target: Optional formula of target; only reactions which make this target
                will be enumerated.
            calculators: Optional list of Calculator object names; see calculators
                module for options (e.g., ["ChempotDistanceCalculator])
        """
        super().__init__(precursors, target, calculators)

    def enumerate(self, entries):
        """
        Calculate all possible reactions given a set of entries. If the enumerator
        was initialized with a target, only reactions to this target will be considered.

        Args:
            entries: the set of all entries to enumerate from

        Returns:
            List of unique computed reactions.
        """
        entries = GibbsEntrySet(entries)

        target = None
        if self.target:
            target = initialize_entry(self.target, entries)
            entries.add(target)
            target_elems = {str(e) for e in target.composition.elements}

        precursors = None
        if self.precursors:
            precursors = {initialize_entry(f, entries) for f in self.precursors}
            for p in precursors:
                entries.add(p)
            precursor_elems = {
                str(elem) for p in precursors for elem in p.composition.elements
            }

        if "ChempotDistanceCalculator" in self.calculators:
            entries = entries.filter_by_stability(e_above_hull=0.0)
            self.logger.info(
                "Filtering by stable entries due to use of 'ChempotDistanceCalculator'"
            )

        combos = list(combinations(entries, 2))
        combos_dict = group_by_chemsys(combos)

        rxns = []
        for chemsys, combos in tqdm(combos_dict.items()):
            elems = chemsys.split("-")
            if (
                (target and not target_elems.issubset(elems))
                or (precursors and not precursor_elems.issuperset(elems))
                or len(elems) >= 10
            ):
                continue

            chemsys_entries = filter_entries_by_chemsys(entries, chemsys)
            pd = PhaseDiagram(chemsys_entries)
            calculators = initialize_calculators(self.calculators, chemsys_entries)

            for e1, e2 in combos:
                if precursors and {e1, e2} != precursors:
                    continue
                predicted_rxns = self._react_interface(
                    e1.composition, e2.composition, pd, calculators=calculators
                )
                rxns.extend(predicted_rxns)

        return list(set(rxns))

    def estimate_num_reactions(self, entries: List[ComputedEntry]) -> int:
        """
        Estimate the upper bound of the number of possible reactions. This will
        correlate with the amount of time it takes to enumerate reactions.

        Args:
            entries: A list of all entries to consider

        Returns: The upper bound on the number of possible reactions
        """
        return comb(len(entries), 2)

    def _react_interface(
        self, r1, r2, pd, grand_pd=None, open_entry=None, calculators=None
    ):
        "Simple API for InterfacialReactivity module from pymatgen."
        if grand_pd:
            interface = InterfacialReactivity(
                r1,
                r2,
                grand_pd,
                norm=True,
                include_no_mixing_energy=False,
                pd_non_grand=pd,
                use_hull_energy=True,
            )
            chempots = grand_pd.chempots

        else:
            interface = InterfacialReactivity(
                r1,
                r2,
                pd,
                norm=False,
                include_no_mixing_energy=False,
                pd_non_grand=None,
                use_hull_energy=True,
            )

        rxns = []
        for _, _, _, rxn, _ in interface.get_kinks():
            if grand_pd:
                rxn = get_open_computed_rxn(rxn, pd.all_entries, chempots)
            else:
                rxn = get_computed_rxn(rxn, pd.all_entries)

            if rxn.is_identity or rxn.lowest_num_errors > 0:
                continue

            if self.target and self.target not in rxn.product_entries:
                continue

            rxn = apply_calculators(rxn, calculators)
            rxns.append(rxn)

        return rxns

class MinimizeGrandPotentialEnumerator(MinimizeGibbsEnumerator):
    """
    Enumerator for finding all reactions between two reactants and an open element
    that are predicted by thermo; i.e., they appear when taking the
    convex hull along a straight line connecting any two phases in Phi-x
    phase space. Identity reactions are excluded.
    """

    def __init__(
        self,
        open_elem: Element,
        mu: float,
        precursors: Optional[List[str]] = None,
        target: Optional[str] = None,
        calculators: Optional[str] = None,
    ):
        super().__init__(precursors=precursors, target=target, calculators=calculators)
        self.open_elem = Element(open_elem)
        self.mu = mu

    def enumerate(self, entries):
        entries = GibbsEntrySet(entries)

        target = None
        if self.target:
            target = initialize_entry(self.target, entries)
            entries.add(target)
            target_elems = {str(e) for e in target.composition.elements}

        precursors = None
        if self.precursors:
            precursors = {initialize_entry(f, entries) for f in self.precursors}
            for p in precursors:
                entries.add(p)
            precursor_elems = {
                str(elem) for p in precursors for elem in p.composition.elements
            }

        if "ChempotDistanceCalculator" in self.calculators:
            entries = entries.filter_by_stability(e_above_hull=0.0)
            self.logger.info(
                "Filtering by stable entries due to use of 'ChempotDistanceCalculator'"
            )

        open_entry = sorted(
            filter(lambda e: e.composition.elements == [self.open_elem], entries),
            key=lambda e: e.energy_per_atom,
        )[0]
        entries_no_open = GibbsEntrySet(entries)
        entries_no_open.remove(open_entry)
        combos = list(combinations(entries_no_open, 2))
        combos_dict = group_by_chemsys(combos, self.open_elem)

        rxns = []
        for chemsys, combos in tqdm(combos_dict.items()):
            elems = chemsys.split("-")
            if (
                (target and not target_elems.issubset(elems))
                or (precursors and not precursor_elems.issuperset(elems))
                or len(elems) >= 10
            ):
                continue

            chemsys_entries = filter_entries_by_chemsys(entries, chemsys)
            pd = PhaseDiagram(chemsys_entries)

            calculators = initialize_calculators(self.calculators, chemsys_entries)

            grand_pd = GrandPotentialPhaseDiagram(
                chemsys_entries, {self.open_elem: self.mu}
            )
            for e1, e2 in combos:
                if precursors and {e1, e2} != precursors:
                    continue
                predicted_rxns = self._react_interface(
                    e1.composition,
                    e2.composition,
                    pd,
                    grand_pd,
                    open_entry,
                    calculators,
                )
                rxns.extend(predicted_rxns)

        return list(set(rxns))


import json

import requests
from django.conf import settings

from core.models import Configuration

def newsletter_registration(email):
    configuration = Configuration.get_solo()

    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "api-key": settings.SIB_API_KEY,
    }

    data = {
        "email": email,
        # "attributes": {
        #     "FIRSTNAME": "",
        #     "LASTNAME": ""
        # },
        "includeListIds": [int(settings.SIB_NEWSLETTER_LIST_ID)],
        "templateId": int(settings.SIB_NEWSLETTER_DOI_TEMPLATE_ID),
        "redirectionUrl": configuration.application_frontend_url + "?newsletter=confirmed",
        "updateEnabled": True,
    }

    return requests.post(settings.SIB_CONTACT_DOI_ENDPOINT, headers=headers, data=json.dumps(data))


import FWCore.ParameterSet.Config as cms

process = cms.Process("Ntupler")

process.load("FWCore.MessageService.MessageLogger_cfi")

process.source = cms.Source ("PoolSource",fileNames = cms.untracked.vstring(
'file:/eos/uscms/store/mc/Phys14DR/DYJetsToLL_M-50_13TeV-madgraph-pythia8/MINIAODSIM/PU20bx25_PHYS14_25_V1-v1/00000/0432E62A-7A6C-E411-87BB-002590DB92A8.root',
)
)
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )
process.MessageLogger.cerr.FwkReport.reportEvery=cms.untracked.int32(10)
process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(False) )

process.ntupler = cms.EDAnalyzer('ElectronNtuplerEventStructure',
                                 packed = cms.InputTag("packedGenParticles"),
                                 pruned = cms.InputTag("prunedGenParticles"),
                                 vertices = cms.InputTag("offlineSlimmedPrimaryVertices"),
                                 pileup = cms.InputTag("addPileupInfo"),
                                 electrons = cms.InputTag("slimmedElectrons"),
				 rho = cms.InputTag("fixedGridRhoFastjetAll"),
                                 photons = cms.InputTag("slimmedPhotons"),

                                 )

process.TFileService = cms.Service("TFileService",
                                   fileName = cms.string('Tree_DY.root')
                                   )

process.p = cms.Path(process.ntupler)


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

from State import State

class Block():

    def __init__(self, init_state):
        self.states = {}
        self.init_state = init_state

    def add_state(self, args):
        name = args[0]

        transition = args[1:]
        if name in self.states:
            self.states[name].add_transition(transition)
        else:
            self.states[name] = State(transition)


# -*- coding: utf-8 -*-
from mao import Mao

class BlackJack(object):

	def __init__(self, baralho):
		self.fichas = 100
		self.baralho = baralho
		self.naipes = baralho.getNaipes()

	# Mostra o título do jogo no CLI
	def mostra_titulo(self):
		print("{} {} Bem vindo(a)s ao Jogo de BlackJack {} {}"
			.format(
				self.naipes[0]['simbolo'],
				self.naipes[1]['simbolo'],
				self.naipes[2]['simbolo'],
				self.naipes[3]['simbolo']))

	# Inicia o jogo
	def init(self):
		self.distribuiCartas()

	def fazAposta(self):
		aposta = 0
		print("Quantas fichas gostaria de apostar?")
		while aposta == 0:
			aposta = int(input())
			if aposta > 0:
				self.fichas -= aposta
				break
			else:
				print("O número de fichas da aposta deve ser válido!")
		print("Você possui {} fichas para apostar além das {} apostadas".format(
			str(self.fichas),
			aposta))

	def distribuiCartas(self):

		self.baralho.embaralhaCartas()

		mao_jogador = Mao()
		mao_dealer = Mao()

		# Duas cartas para o Jogador
		mao_jogador.addCarta(baralho.pegaCarta())
		mao_jogador.addCarta(baralho.pegaCarta())

		# Duas cartas para o Dealer
		mao_dealer.addCarta(baralho.pegaCarta())
		mao_dealer.addCarta(baralho.pegaCarta())


from django.urls import path
from . import views
urlpatterns = [
   # artists
   path('', views.artist_list, name='artist_list'),
   path('artists/<int:pk>' , views.artist_detail , name = 'artist_detail' ),
   path('artists/new', views.artist_create, name='artist_create'), # new artists
   path('artists/<int:pk>/edit', views.artist_edit, name='artist_edit'), # edit artist
   path('artists/<int:pk>/delete', views.artist_delete, name='artist_delete'), #delete artist

   path('songs/', views.songs_list, name='song_list'),
   path('songs/<int:pk>' , views.song_detail , name = 'song_detail' ),
   path('songs/new', views.song_create, name='song_create'),
   path('songs/<int:pk>/edit', views.song_edit, name='song_edit'),
   path('songs/<int:pk>/delete', views.song_delete, name='song_delete'),

   path('home/' , views.home , name = "home" ) ,
   path('about/' , views.about) ,
   path('user/<int:id>' , views.show_one_user)
]


from lib.utils import util
from lib.base_controller import CommandHelp, ShellException

from .live_cluster_command_controller import LiveClusterCommandController

@CommandHelp(
    '"asinfo" provides raw access to the info protocol.',
    "  Options:",
    "    -v <command>   - The command to execute",
    "    -p <port>      - Port to use in the case of an XDR info command and XDR is",
    "                     not in asd",
    '    -l             - Replace semicolons ";" with newlines. If output does',
    '                     not contain semicolons "-l" will attempt to use',
    '                     colons ":" followed by commas ",".',
    "    --no_node_name - Force to display output without printing node names.",
)
class ASInfoController(LiveClusterCommandController):
    def __init__(self):
        self.modifiers = set(["with", "like"])

    @CommandHelp("Executes an info command.")
    def _do_default(self, line):
        mods = self.parse_modifiers(line)
        line = mods["line"]
        nodes = self.nodes

        value = None
        line_sep = False
        xdr = False
        show_node_name = True

        tline = line[:]

        try:
            while tline:
                word = tline.pop(0)
                if word == "-v":
                    value = tline.pop(0)
                elif word == "-l":
                    line_sep = True
                elif word == "-p":
                    port = tline.pop(0)
                    if port == "3004":  # ugly Hack
                        xdr = True
                elif word == "--no_node_name":
                    show_node_name = False
                else:
                    raise ShellException(
                        "Do not understand '%s' in '%s'" % (word, " ".join(line))
                    )
        except Exception:
            self.logger.warning(
                "Do not understand '%s' in '%s'" % (word, " ".join(line))
            )
            return
        if value is not None:
            value = value.translate(str.maketrans("", "", "'\""))

        if xdr:
            results = self.cluster.xdr_info(value, nodes=nodes)
        else:
            results = self.cluster.info(value, nodes=nodes)

        return util.Future(
            self.view.asinfo, results, line_sep, show_node_name, self.cluster, **mods
        )


import numpy as np
import h5py
import networkx as nx
import argparse
import itertools
import random
import pickle

import neurokernel.mpi_relaunch
import neurokernel.core_gpu as core

from neurokernel.LPU.InputProcessors.StepInputProcessor import StepInputProcessor
from neurokernel.LPU.InputProcessors.FileInputProcessor import FileInputProcessor
from neurokernel.tools.logging import setup_logger
from neurokernel.LPU.LPU import LPU

(comp_dict, conns) = LPU.lpu_parser('neuroballad_temp_graph.gexf.gz')
with open('run_parameters.pickle', 'rb') as f:
    run_parameters = pickle.load(f)
with open('record_parameters.pickle', 'rb') as f:
    record_parameters = pickle.load(f)
dur = 1.0
dt = 1e-4
dur = run_parameters[0]
dt = run_parameters[1]
fl_input_processor = FileInputProcessor('neuroballad_temp_model_input.h5')

from neurokernel.LPU.OutputProcessors.FileOutputProcessor import FileOutputProcessor
output_processor = FileOutputProcessor(record_parameters, 'neuroballad_temp_model_output.h5', sample_interval=1)

#Parse extra arguments
parser = argparse.ArgumentParser()
parser.add_argument('--debug', default=True,
                    dest='debug', action='store_true',
                    help='Write connectivity structures and inter-LPU routed data in debug folder')
parser.add_argument('-l', '--log', default='both', type=str,
                    help='Log output to screen [file, screen, both, or none; default:none]')
parser.add_argument('-r', '--time_sync', default=False, action='store_true',
                    help='Time data reception throughput [default: False]')
parser.add_argument('-g', '--gpu_dev', default=[0], type=int, nargs='+',
                    help='GPU device numbers [default: 0]')
parser.add_argument('-d', '--disconnect', default=False, action='store_true',
                    help='Run with disconnected LPUs [default: False]')
args = parser.parse_args()
file_name = None
screen = False
if args.log.lower() in ['file', 'both']:
    file_name = 'neurokernel.log'
if args.log.lower() in ['screen', 'both']:
    screen = True
logger = setup_logger(file_name=file_name, screen=screen)
man = core.Manager()

man.add(LPU, 'lpu', dt, comp_dict, conns,
        input_processors=[fl_input_processor],
        output_processors=[output_processor], device=args.gpu_dev[0],
        debug=True)

steps = int(dur/dt)
man.spawn()
man.start(steps = steps)
man.wait()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('fb360', '0059_auto_20151023_1106'),
    ]

    operations = [
        migrations.AddField(
            model_name='qualitativeresponse',
            name='fb',
            field=models.ForeignKey(default=2, to='fb360.FB360', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='response',
            name='fb',
            field=models.ForeignKey(default=2, to='fb360.FB360', null=True),
            preserve_default=True,
        ),
    ]