Beispiel #1
0
def _makeTree(node, xMasterList, yMasterList):
    for key in node.children:
        childNode = node.children[key]
        #print '_maketree '+ key;
        attrDict = fp.attrDictMaster
        #xMasterList =fp.xList;
        #yMasterList = fp.getYValueMatrix();
        xList = _getXList(childNode.indexList, xMasterList)
        yList = _getYList(childNode.indexList, yMasterList)
        entrObj = calcEntropy(yList)
        initEntropy = entrObj.getEntropy()
        #print 'entropy :'+str(initEntropy);
        if (initEntropy == 0.0):
            childNode.setAttribute(yList[0])
            #print childNode.attrName;
            #print yList;
            childNode.setEntropy(initEntropy)
            calEffObj.registerClassification(yList, childNode.attrName)
            #print 'end';
            continue
        sa = SelectAttribute(attrDict, xList, yList, initEntropy,
                             childNode.attrTaken)
        #print sa.maxGainAttr;
        childNode.setAttribute(sa.maxGainAttr)
        childNode.setEntropy(initEntropy)
        childNode.attrTaken[sa.maxGainAttr] = 'y'
        indexDict = sa.indexDict
        for key1 in indexDict.keys():
            child = Nodes()
            child.indexList = indexDict[key1]
            child.attrTaken = childNode.attrTaken
            child.key = key1
            childNode.children[key1] = child
        _makeTree(childNode, xList, yList)
Beispiel #2
0
def _makeTree1(node, xMasterList, yMasterList):
    for key in node.children:
        childNode = node.children[key]
        attrDict = fp.attrDictMaster
        xList = _getXList(childNode.indexList, xMasterList)
        yList = _getYList(childNode.indexList, yMasterList)
        entrObj = VarImpurityGain(yList)
        initEntropy = entrObj.getVarImpurity()
        if (initEntropy == 0.0):
            childNode.setAttribute(yList[0])
            childNode.setEntropy(initEntropy)
            calEffObj.registerClassification(yList, childNode.attrName)
            continue
        sa = SelectAttributeImpurity(attrDict, xList, yList, initEntropy,
                                     childNode.attrTaken)
        childNode.setAttribute(sa.maxGainAttr)
        childNode.setEntropy(initEntropy)
        childNode.attrTaken[sa.maxGainAttr] = 'y'
        indexDict = sa.indexDict
        for key1 in indexDict.keys():
            child = Nodes()
            child.indexList = indexDict[key1]
            child.attrTaken = childNode.attrTaken
            child.key = key1
            childNode.children[key1] = child
        _makeTree1(childNode, xList, yList)
Beispiel #3
0
def _createLeaf(yList):
    entrObj = calcEntropy(yList)
    print entrObj.getEntropy()
    if (entrObj.getEntropy() == 0.0):
        leave = Nodes()
        return leave
    else:
        return None
Beispiel #4
0
    def create_content(self, parent):
        self.panes = ttk.Panedwindow(parent, orient=HORIZONTAL)
        self.panes.pack(side=TOP, fill=BOTH, expand=Y)
        parent.rowconfigure(1, weight=1, minsize=300)
        self.panes.grid(row=1, column=0, sticky=NSEW)

        self.tree = ContentTree(self.panes, popup=self.tree_popup, \
              selchange=self.tree_selchange, \
              expanding=self.tree_expanding)
        self.nodes = Nodes(self.tree)

        self.content = ttk.Notebook(self.panes)
        self.details = ScrollableText(self.content, "", True)
        self.details_tab = 0
        self.content.add(self.details, text="Details")
        self.hexdump = ScrollableText(self.content, "", True)
        self.hexdump_tab = 1
        self.content.add(self.hexdump, text="Hex dump")

        self.panes.add(self.tree)
        self.panes.add(self.content)
    def doCalculation(self):
        # Create first node

        y_1 = Rules.getInstance().valueOfY_firstRule

        z_1 = Rules.getInstance().totalValue_firstRule

        y_2 = Rules.getInstance().valueOfY_secondRule

        z_2 = Rules.getInstance().totalValue_secondRule

        if Rules.getInstance().valueOfX_secondRule > Rules.getInstance(
        ).valueOfX_firstRule:
            if Rules.getInstance().valueOfX_firstRule == 1:
                y_1 = Rules.getInstance(
                ).valueOfY_firstRule * Rules.getInstance().valueOfX_secondRule

                z_1 = Rules.getInstance(
                ).totalValue_firstRule * Rules.getInstance(
                ).valueOfX_secondRule
            else:
                if Rules.getInstance().valueOfX_secondRule % Rules.getInstance(
                ).valueOfX_firstRule != 0:
                    y_1 = Rules.getInstance(
                    ).valueOfY_firstRule * Rules.getInstance(
                    ).valueOfX_secondRule
                    z_1 = Rules.getInstance(
                    ).totalValue_firstRule * Rules.getInstance(
                    ).valueOfX_secondRule

                    y_2 = Rules.getInstance(
                    ).valueOfY_secondRule * Rules.getInstance(
                    ).valueOfX_firstRule
                    z_2 = Rules.getInstance(
                    ).totalValue_secondRule * Rules.getInstance(
                    ).valueOfX_firstRule

                else:
                    aConversionValue = Rules.getInstance(
                    ).valueOfX_secondRule / Rules.getInstance(
                    ).valueOfX_firstRule

                    y_1 = Rules.getInstance(
                    ).valueOfY_firstRule * aConversionValue
                    z_1 = Rules.getInstance(
                    ).totalValue_firstRule * aConversionValue

        elif Rules.getInstance().valueOfX_secondRule < Rules.getInstance(
        ).valueOfX_firstRule:
            if Rules.getInstance().valueOfX_secondRule == 1:
                y_2 = Rules.getInstance(
                ).valueOfY_secondRule * Rules.getInstance().valueOfX_secondRule

            else:
                if Rules.getInstance().valueOfX_firstRule % Rules.getInstance(
                ).valueOfX_secondRule != 0:
                    y_1 = Rules.getInstance(
                    ).valueOfY_firstRule * Rules.getInstance(
                    ).valueOfX_secondRule
                    z_1 = Rules.getInstance(
                    ).totalValue_firstRule * Rules.getInstance(
                    ).valueOfX_secondRule

                    y_2 = Rules.getInstance(
                    ).valueOfY_secondRule * Rules.getInstance(
                    ).valueOfX_firstRule
                    z_2 = Rules.getInstance(
                    ).totalValue_secondRule * Rules.getInstance(
                    ).valueOfX_firstRule

                else:
                    aConversionValue = Rules.getInstance(
                    ).valueOfX_firstRule / Rules.getInstance(
                    ).valueOfX_secondRule

                    y_2 = Rules.getInstance(
                    ).valueOfY_secondRule * aConversionValue
                    z_2 = Rules.getInstance(
                    ).totalValue_secondRule * aConversionValue

        elif Rules.getInstance().valueOfX_secondRule == Rules.getInstance(
        ).valueOfX_firstRule:
            y_1 = Rules.getInstance().valueOfY_firstRule
            z_1 = Rules.getInstance().totalValue_firstRule

            y_2 = Rules.getInstance().valueOfY_secondRule
            z_2 = Rules.getInstance().totalValue_secondRule

        getY_Value = abs(z_1 - z_2) / abs(y_1 - y_2)

        getX_Value = (Rules.getInstance().totalValue_firstRule -
                      (Rules.getInstance().valueOfY_firstRule *
                       getY_Value)) / Rules.getInstance().valueOfX_firstRule
        totalValue = (Rules.getInstance().valueOfX *
                      getX_Value) + (Rules.getInstance().valueOfY * getY_Value)

        self.node = Model_Nodes(0, getX_Value, getY_Value, totalValue)

        doLoopForCreateTree = True

        numberOfChildNode = 1
        parrentNode = 0
        startGetConstraintFrom = "y"

        listOfPosibleValueNode = dict()

        while doLoopForCreateTree:

            getParentValue = {
                'x': self.node.getValueOfSelectedNode(parrentNode)['x'],
                'y': self.node.getValueOfSelectedNode(parrentNode)['y']
            }
            getMaxValue = max(getParentValue.keys(),
                              key=(lambda k: getParentValue[k]))

            if self.number_of_digits_post_decimal(
                    getParentValue['x']
            ) != None and self.number_of_digits_post_decimal(
                    getParentValue['y']) != None:
                getMaxValue = max(getParentValue.keys(),
                                  key=(lambda k: getParentValue[k]))
            else:
                if self.number_of_digits_post_decimal(
                        getParentValue['x']
                ) != None and self.number_of_digits_post_decimal(
                        getParentValue['y']) == None:
                    getMaxValue = 'x'

                elif self.number_of_digits_post_decimal(
                        getParentValue['x']
                ) == None and self.number_of_digits_post_decimal(
                        getParentValue['y']) != None:
                    getMaxValue = 'y'

            # if self.number_of_digits_post_decimal(getParentValue[getMinValue]) == None :
            #     if getMinValue == 'x' :
            #         getMinValue = 'y'
            #     elif getMinValue == 'y':
            #         getMinValue = 'x'

            if startGetConstraintFrom == "x":
                getX_Value_right = int(getParentValue[getMaxValue])

                getY_Value_right = (Rules.getInstance().totalValue_secondRule -
                                    (Rules.getInstance().valueOfX_secondRule *
                                     getX_Value_right)
                                    ) / Rules.getInstance().valueOfY_secondRule

                getZ_Value_right = (
                    Rules.getInstance().valueOfX * getX_Value_right) + (
                        Rules.getInstance().valueOfY * getY_Value_right)

                if getZ_Value_right > self.node.getValueOfSelectedNode(0)['z']:
                    self.node.setNodesRight(numberOfChildNode,
                                            getX_Value_right, getY_Value_right,
                                            getZ_Value_right, parrentNode,
                                            "infeasible")

                else:
                    self.node.setNodesRight(numberOfChildNode,
                                            getX_Value_right, getY_Value_right,
                                            getZ_Value_right, parrentNode)

                getX_Value_left = int(getParentValue[getMaxValue]) + 1

                getY_Value_left = (
                    Rules.getInstance().totalValue_firstRule -
                    (Rules.getInstance().valueOfX_firstRule *
                     getX_Value_left)) / Rules.getInstance().valueOfY_firstRule

                getZ_Value_left = (
                    Rules.getInstance().valueOfX * getX_Value_left) + (
                        Rules.getInstance().valueOfY * getY_Value_left)

                if getZ_Value_left > self.node.getValueOfSelectedNode(0)['z']:
                    self.node.setNodesLeft(numberOfChildNode + 1,
                                           getX_Value_left, getY_Value_left,
                                           getZ_Value_left, parrentNode,
                                           "infeasible")

                else:
                    self.node.setNodesLeft(numberOfChildNode + 1,
                                           getX_Value_left, getY_Value_left,
                                           getZ_Value_left, parrentNode)

            elif startGetConstraintFrom == "y":
                getY_Value_right = int(getParentValue[getMaxValue]) + 1

                getX_Value_right = (Rules.getInstance().totalValue_secondRule -
                                    (Rules.getInstance().valueOfY_secondRule *
                                     getY_Value_right)
                                    ) / Rules.getInstance().valueOfX_secondRule

                getZ_Value_right = (
                    Rules.getInstance().valueOfX * getX_Value_right) + (
                        Rules.getInstance().valueOfY * getY_Value_right)

                if getZ_Value_right > self.node.getValueOfSelectedNode(0)['z']:
                    self.node.setNodesRight(numberOfChildNode,
                                            getX_Value_right, getY_Value_right,
                                            getZ_Value_right, parrentNode,
                                            "infeasible")

                else:
                    self.node.setNodesRight(numberOfChildNode,
                                            getX_Value_right, getY_Value_right,
                                            getZ_Value_right, parrentNode)

                getY_Value_left = int(getParentValue[getMaxValue])

                getX_Value_left = (
                    Rules.getInstance().totalValue_firstRule -
                    (Rules.getInstance().valueOfY_firstRule *
                     getY_Value_left)) / Rules.getInstance().valueOfX_firstRule

                getZ_Value_left = (
                    Rules.getInstance().valueOfX * getX_Value_left) + (
                        Rules.getInstance().valueOfY * getY_Value_left)

                if getZ_Value_left > self.node.getValueOfSelectedNode(0)['z']:
                    self.node.setNodesLeft(numberOfChildNode + 1,
                                           getX_Value_left, getY_Value_left,
                                           getZ_Value_left, parrentNode,
                                           "infeasible")

                else:
                    self.node.setNodesLeft(numberOfChildNode + 1,
                                           getX_Value_left, getY_Value_left,
                                           getZ_Value_left, parrentNode)

            if self.node.getValueOfSelectedNode(
                    numberOfChildNode + 1
            )['status'] != "infeasible" and self.number_of_digits_post_decimal(
                    getZ_Value_left) == None:
                listOfPosibleValueNode[numberOfChildNode +
                                       1] = self.node.getValueOfSelectedNode(
                                           numberOfChildNode + 1)['z']

            if self.node.getValueOfSelectedNode(
                    numberOfChildNode
            )['status'] != "infeasible" and self.number_of_digits_post_decimal(
                    getZ_Value_right) == None:
                listOfPosibleValueNode[
                    numberOfChildNode] = self.node.getValueOfSelectedNode(
                        numberOfChildNode)['z']

            if getZ_Value_right > getZ_Value_left:

                if self.node.getValueOfSelectedNode(
                        numberOfChildNode + 1
                )['status'] != "infeasible" and self.number_of_digits_post_decimal(
                        getZ_Value_left) != None:
                    parrentNode = numberOfChildNode + 1
                else:
                    if self.node.getValueOfSelectedNode(
                            numberOfChildNode
                    )['status'] != "infeasible" and self.number_of_digits_post_decimal(
                            getZ_Value_right) != None:
                        parrentNode = numberOfChildNode
                    else:
                        doLoopForCreateTree = False
                        break

            elif getZ_Value_right < getZ_Value_left:

                if self.node.getValueOfSelectedNode(
                        numberOfChildNode
                )['status'] != "infeasible" and self.number_of_digits_post_decimal(
                        getZ_Value_right) != None:
                    parrentNode = numberOfChildNode
                else:
                    doLoopForCreateTree = False
                    break

            numberOfChildNode = numberOfChildNode + 2

            if startGetConstraintFrom == "x":
                startGetConstraintFrom = "y"
            elif startGetConstraintFrom == "y":
                startGetConstraintFrom = "x"

            # if numberOfChildNode == 7 :
            #     doLoopForCreateTree = False
            #     break

        self.node.showDetail()

        getNode = max(listOfPosibleValueNode.keys(),
                      key=(lambda k: listOfPosibleValueNode[k]))
        print("node yang memenuhi persyaratan adalah: \n")
        print("Number of node: " +
              str(self.node.getValueOfSelectedNode(getNode)['NumberNode']))
        print("X value: " +
              str(self.node.getValueOfSelectedNode(getNode)['x']))
        print("Y value: " +
              str(self.node.getValueOfSelectedNode(getNode)['y']))
        print("Z value: " +
              str(self.node.getValueOfSelectedNode(getNode)['z']))
        print("Status: " +
              str(self.node.getValueOfSelectedNode(getNode)['status']))
def read_excel_file(filename):
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_index(0)
    nodes = []
    temp_node = Nodes()
    depot = Nodes()
    for rows in range(sheet.nrows):
        print str(sheet.cell_value(rows, 0))
        if "pot" in str(sheet.cell_value(rows, 0)):
            depot.nodeNames = str(sheet.cell_value(rows, 0))
            depot.nodeId = int(sheet.cell_value(rows, 1))
            depot.nodeX = int(sheet.cell_value(rows, 2))
            depot.nodeY = int(sheet.cell_value(rows, 3))
            depot.nodePickup = int(sheet.cell_value(rows, 4))
            depot.nodeDelivery = int(sheet.cell_value(rows, 5))
        else:
            temp_node.nodeNames = str(sheet.cell_value(rows, 0))
            temp_node.nodeId = int(sheet.cell_value(rows, 1))
            temp_node.nodeX = int(sheet.cell_value(rows, 2))
            temp_node.nodeY = int(sheet.cell_value(rows, 3))
            temp_node.nodePickup = int(sheet.cell_value(rows, 4))
            temp_node.nodeDelivery = int(sheet.cell_value(rows, 5))
            nodes.append(copy(temp_node))

    return nodes, depot
Beispiel #7
0
def running():

    current_time = 0
    end_time = 90000
    time_interval = 600
    nodes_list = []
    entire_transaction_list = []
    num_of_blocks_in_fork = []
    dict_num_of_blocks_in_fork = {}
    converge_progress = {}

    min_cfreq_range, max_cfreq_range = cal_contact_frequency_range(
        GC.CONTACT_FREQ, time_interval)
    if not GC.RANDOM_TRANS:
        current_period_end_time = 10000
        current_transactions_within_10000 = []
        f = open(
            os.getcwd() + "\\Created_data_trace\\transaction_nodes_" +
            str(GC.NUM_OF_NODES) + ".txt", 'r')

    if not GC.RANDOM_WINNERS:
        current_period_end_time = 10000
        current_winners_within_10000 = []
        f2 = open(
            os.getcwd() + "\\Created_data_trace\\nodes" +
            str(GC.NUM_OF_NODES) + "_winners" + str(GC.NUM_OF_WINNERS) +
            "_long.txt", 'r')

    for i in range(GC.NUM_OF_NODES):
        nodes_list.append(
            Nodes(i, min_cfreq_range, max_cfreq_range,
                  GC.RANDOM_START_CONNECT_TIME, GC.RANDOM_CONNECT_TIME))

    if GC.HETERO_RC:
        hetero_groups = hetero_disconnection_time_assign(
            nodes_list.copy(), time_interval)

# for node in nodes_list:
# print(node.server_connect_time_interval)
    while current_time < end_time or not is_only_one_blockchain_left(
            nodes_list):
        # fetch transaction
        if current_time < end_time:
            if GC.RANDOM_TRANS:
                current_transactions = generate_transactions(
                    current_time, time_interval)
            else:
                if not current_transactions_within_10000:
                    current_transactions_within_10000 = retrieve_records_from_file(
                        f, current_period_end_time)
                current_transactions = retrieve_records_from_temp_storage(
                    current_transactions_within_10000, current_time,
                    time_interval)
        if current_transactions:
            for t in current_transactions:
                node1 = get_node(t[1], nodes_list)
                transaction = {
                    'sender': t[1],
                    'recipient': t[2],
                    'amount': t[3],
                    'timestamp': t[0],
                }
                node1.blockchain.add_new_transaction(transaction)
                entire_transaction_list.append(transaction)

        if GC.RANDOM_WINNERS:
            winners = random_select_winner(current_time, GC.NUM_OF_WINNERS)
        else:
            if not current_winners_within_10000:
                current_winners_within_10000 = retrieve_records_from_file(
                    f2, current_period_end_time)
            winners = retrieve_records_from_temp_storage(
                current_winners_within_10000, current_time, time_interval)
            if not winners:
                winners = random_select_winner(current_time, GC.NUM_OF_WINNERS)

        if winners:
            for winner_index in range(len(winners)):
                winner = get_node(winners[winner_index][1], nodes_list)
                winner.blockchain.add_new_block(winners[winner_index][0])

        for node1 in nodes_list:
            for node2 in nodes_list:
                if (node1 != node2
                        and current_time <= node1.next_server_contact_time <=
                        current_time + time_interval
                        and current_time <= node2.next_server_contact_time <=
                        current_time + time_interval):
                    node1.blockchain.broadcast_transactions(node2.blockchain)
                    node2.blockchain.broadcast_transactions(node1.blockchain)
                    num_of_block_after_tran_in_fork_1 = node1.blockchain.resolve_conflict(
                        node2.blockchain)
                    num_of_block_after_tran_in_fork_2 = node2.blockchain.resolve_conflict(
                        node1.blockchain)

                    num_of_blocks_in_fork, dict_num_of_blocks_in_fork = \
                        stats_of_num_of_blocks_after_revoked_transactions(num_of_block_after_tran_in_fork_1,
                                                                          num_of_blocks_in_fork,
                                                                          dict_num_of_blocks_in_fork)
                    num_of_blocks_in_fork, dict_num_of_blocks_in_fork = \
                        stats_of_num_of_blocks_after_revoked_transactions(num_of_block_after_tran_in_fork_2,
                                                                          num_of_blocks_in_fork,
                                                                          dict_num_of_blocks_in_fork)

        progress = cal_converge_progress(nodes_list)
        progress -= progress % 10
        progress = int(progress)
        if progress not in converge_progress.keys() and progress % 20 == 0:
            converge_progress[progress] = current_time
        current_time += time_interval
        current_transactions = []

        if (not GC.RANDOM_WINNERS or not GC.RANDOM_TRANS
            ) and current_period_end_time < current_time:
            current_period_end_time += 10000

        for node in nodes_list:
            node.update_next_connect_time(current_time)

    blockchain_list, blockchain_owner = FileWritting.get_statistics(nodes_list)
    # FileWritting.write_statistics_into_file(blockchain_list, blockchain_owner, entire_transaction_list,
    # num_of_blocks_in_fork)
    FileWritting.write_csv_statistics_file(blockchain_list,
                                           num_of_blocks_in_fork,
                                           dict_num_of_blocks_in_fork)
    if GC.HETERO_RC:
        FileWritting.write_heterogeneity_log_into_file(blockchain_list,
                                                       hetero_groups)
    print("FINISH")
Beispiel #8
0
def main1():

    attrDict = fp.getAttrDict()
    xList = fp.getXValueMatrix()
    yList = fp.getYValueMatrix()
    entrObj = calcEntropy(yList)
    initEntropy = entrObj.getEntropy()
    sa = SelectAttribute(attrDict, xList, yList, initEntropy)
    print sa.maxGainAttr
    print sa.maxGain
    #recObj = PopulateTree();
    #recObj.recursion(0);
    root = Nodes()
    root.attrName = sa.maxGainAttr
    root.entropy = initEntropy
    root.attrTaken[root.attrName] = 'y'
    indexDict = sa.indexDict
    for key in indexDict.keys():
        child = Nodes()
        child.indexList = indexDict[key]
        child.attrTaken = root.attrTaken
        root.children[key] = child
    print root.children
    _makeTree(root, xList, yList)
    travrse = TraverseTree(root)
    print calEffObj.calculateEfficiency(yList)
    fp1.getAttrDict()
    xMaster = fp1.getXValueMatrix()
    yMaster = fp1.getYValueMatrix()
    root.indexList = None
    predict(root, xMaster, yMaster)
    accuracy = calEffObj1.calculateEfficiency(fp1.getYValueMatrix())
    print len(fp1.getYValueMatrix())
    print calEffObj1.wrong
    print calEffObj1.calculateEfficiency(fp1.getYValueMatrix())
    prune = PruneTree(root, accuracy, calEffObj1, yMaster, xMaster,
                      fp1.attrDictMaster)
    #travrse = TraverseTree(root);

    root1 = Nodes()
    impurityObj = VarImpurityGain(yList)
    initImpurity = impurityObj.getVarImpurity()
    sa1 = SelectAttributeImpurity(attrDict, xList, yList, initImpurity)
    root1.attrName = sa1.maxGainAttr
    root1.entropy = initImpurity
    root1.attrTaken[root1.attrName] = 'y'
    indexDict1 = sa1.indexDict
    for key in indexDict.keys():
        child = Nodes()
        child.indexList = indexDict[key]
        child.attrTaken = root1.attrTaken
        root1.children[key] = child
    _makeTree1(root1, xList, yList)
    TraverseTree(root1)
 def addNode(self, bcp=None):
     i = len(self.nodes)
     self.nodes.append(Nodes(id=i, bcap=bcp))
Beispiel #10
0
                                                                    == "p"):
        break
    else:
        print("Incorrect value entered, try again.")

if (version == "C") or (version == "c"):
    playerOneName = input("Enter your name: ")
    playerTwoName = "Computer"
    startGame = Game(playerOneName, playerTwoName,
                     True)  #Creating an object of type Game
    # Plays the game with the computer
    print("Here's the initial board:")
    startGame.getBoard().printBoardColors()
    print(Style.RESET_ALL + "=====")
    print("Let's get started!")
    testing = Nodes(startGame, startGame.getBoard(), startGame.getPlayer1(),
                    startGame.getPlayer2())  #NOTE: USED FOR TESTING
    testing.generateChildren(1)  #NOTE: USED FOR TESTING
    #print(startGame.computerPlaceToken()) For testing
    startGame.playGameWithComputer()

if (version == "P") or (version == "p"):
    playerOneName = input("Enter player one's name: ")
    playerTwoName = input("Enter player two's name: ")
    startGame = Game(playerOneName, playerTwoName,
                     False)  #Creating an object of type Game
    # Plays the game
    print("Here's the initial board:")
    startGame.getBoard().printBoardColors()
    print(Style.RESET_ALL + "=====")
    print("Let's get started!")
    startGame.playGame()
Beispiel #11
0
class Application(ttk.Frame):

    extract_to = None  # If empty, will extract to path ZIP is located, else to relative path
    nodes = None

    def __init__(self, master=None):
        super().__init__(master, name="dumpmyrideui")
        self.pack(fill=BOTH, expand=Y)
        self.master.title(self.get_title())
        self.master.minsize(640, 480)
        self.columnconfigure(0, weight=1, minsize=400)
        self.rowconfigure(0, weight=1, minsize=300)
        self.create_widgets()
        # Finally, update UI
        self.update_extract_location()
        self.update_ui()
        self.update_tree()

    '''
	UI generation
	'''

    def create_widgets(self):
        self.main = ttk.Frame(self)
        self.main.pack(side=TOP, fill=BOTH, expand=Y)
        self.main.columnconfigure(0, weight=1, minsize=400)
        self.main.grid(row=0, column=0, sticky=NSEW)
        self.create_menubar(self.main)
        self.create_toolbars(self.main)
        self.create_content(self.main)
        self.create_statusbar(self.main)

    def create_menubar(self, parent):
        self.menubar = Menu(parent)

        self.menu_file = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_file, label='File')
        self.menu_file.add_command(label='Open root ...',
                                   command=self.fileOpenRoot)
        self.menu_file.add_command(label='Close root',
                                   command=self.fileCloseRoot)
        self.menu_file.add_separator()
        self.menu_file.add_command(label='Extract selected',
                                   command=self.fileExtractSelected)
        self.menu_file.add_command(label='Extract all',
                                   command=self.fileExtractAll)
        self.menu_file.add_separator()
        self.menu_file.add_command(label='Options', command=self.fileOptions)
        self.menu_file.add_separator()
        self.menu_file.add_command(label='Exit', command=self.fileExit)

        self.menu_help = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_help, label='Help')
        self.menu_help.add_command(label='About ...', command=self.helpAbout)

        self.master['menu'] = self.menubar

    def create_toolbars(self, parent):
        #self.main.rowconfigure(0, weight=0, minsize=0)
        return

    def create_statusbar(self, parent):
        self.statusbar = ttk.Frame(parent)
        self.statusbar["borderwidth"] = 2
        self.statusbar["relief"] = "sunken"
        self.statusbar["padding"] = 1
        parent.rowconfigure(999, weight=0, minsize=15)
        self.statusbar.rowconfigure(0, weight=1, minsize=15)
        self.statusbar.columnconfigure(0, weight=1, minsize=180)
        self.statusbar.columnconfigure(1, weight=0, minsize=400)
        self.statusbar.columnconfigure(999, weight=0, minsize=15)
        self.statusbar.grid(row=999, column=0, sticky=(N, S, E, W))

        self.statustext = ttk.Label(self.statusbar, text="Ready ...")
        self.statustext.grid(column=0, row=0, sticky=NSEW)

        self.progressbar = None

        ttk.Sizegrip(self.statusbar).grid(column=999, row=0, sticky=(S, E))

    def create_content(self, parent):
        self.panes = ttk.Panedwindow(parent, orient=HORIZONTAL)
        self.panes.pack(side=TOP, fill=BOTH, expand=Y)
        parent.rowconfigure(1, weight=1, minsize=300)
        self.panes.grid(row=1, column=0, sticky=NSEW)

        self.tree = ContentTree(self.panes, popup=self.tree_popup, \
              selchange=self.tree_selchange, \
              expanding=self.tree_expanding)
        self.nodes = Nodes(self.tree)

        self.content = ttk.Notebook(self.panes)
        self.details = ScrollableText(self.content, "", True)
        self.details_tab = 0
        self.content.add(self.details, text="Details")
        self.hexdump = ScrollableText(self.content, "", True)
        self.hexdump_tab = 1
        self.content.add(self.hexdump, text="Hex dump")

        self.panes.add(self.tree)
        self.panes.add(self.content)

    '''
	Updates UI
	'''

    def update_ui(self):
        self.master.title(self.get_title())
        #TODO: Be more precise on menu item states
        #      e.g. archives not yet extracted will need this option to be avail
        cab_avail = "normal" if _options.cabinet else "disabled"
        self.menu_file.entryconfigure("Extract selected", state=cab_avail)
        self.menu_file.entryconfigure("Extract all", state=cab_avail)
        self.menu_file.entryconfigure("Close root", state=cab_avail)
        #self.update_tree() # only called when _options.cabinet has changed!
        # more to come, e.g. populating tree, ...
        #...
        self.set_statusbar()
        Tk.update_idletasks(self)

    def update_tree(self):
        self.tree.clear()
        if not _options.cabinet or not os.path.exists(_options.cabinet):
            return
        if not zipfile.is_zipfile(_options.cabinet):
            print("Given file isn't a valid ZIP")
            return
        # more tests to follow, e.g. '.cab' needs explicit handling

        print("\nBuilding tree ...")
        last_selection = _options.last_selection
        self.app_busy()
        self.show_progress_bar(animate=True)
        node = self.nodes.add(None,
                              _options.cabinet,
                              "Root",
                              "Main installation file",
                              self.extract_to,
                              details=None,
                              hexdump=None,
                              lazy=False,
                              callback=None)
        self.set_statusbar()
        self.hide_progress_bar()
        self.app_ready()
        if last_selection:
            if not last_selection in self.nodes:
                #TODO: Build tree until last_selection reached
                a = ""
            else:
                self.tree.focus(last_selection, force=True)
        else:
            self.tree.focus(node.label, force=True)
            _options.last_selection = node.label
        '''
		vals = { "label":"Root", "info":"Main installation file", "exists":None, \
				"processor":ZipProcessor(_options.cabinet), "extract_to":self.extract_to }
		last_selection = _options.last_selection
		iid = self.tree.add("", vals["label"], vals["info"], vals["exists"], open=True)
		self.values = { iid:vals }
		self.tree_populate(iid, open=True, init_progress=True)
		print("... done building")
		if last_selection:
			if not last_selection in self.values:
				#TODO: Build tree until last_selection reached
				a=""
			else:
				self.tree.focus(last_selection, force=True)
		else:
			self.tree.focus(vals["label"], force=True)
			_options.last_selection = vals["label"]
		#self.hexdump.show_disabled()
		#self.details.show_disabled()
		'''

    '''
	Tree handling
	'''

    values = {}  # => Nodes
    tree_popup_menu = None

    def tree_popup(self, event, iid):
        if not iid:
            return
        node = self.nodes[iid]
        print("\nTree requested popup menu @ {}/{}:".\
         format(event.x_root,event.y_root),"\n-",iid,"->",node)
        if not self.tree_popup_menu:
            self.tree_popup_menu = Menu(self)
            self.tree_popup_menu.add_command(label='Extract selected',
                                             command=self.fileExtractSelected)
            self.tree_popup_menu.add_command(label='Extract all',
                                             command=self.fileExtractAll)
        #TODO: Be more precise on menu item states
        #      e.g. archives not yet extracted will need this option to be avail
        avail = True
        #avail = (not vals["exists"]) and (vals["processor"] is ZipProcessor or vals["processor"] is CabProcessor)
        #avail = (not vals["exists"]) or (vals["processor"] and vals["processor"].can_save)
        avail = "normal" if avail else "disabled"
        self.tree_popup_menu.entryconfigure("Extract selected", state=avail)
        self.tree_popup_menu.post(event.x_root, event.y_root)

    def tree_selchange(self, event, iid):
        if not iid:
            return
        _options.last_selection = iid
        node = self.nodes[iid]
        print("\nTree selection changed:\n-", iid, "->", node)
        self.set_statusbar("Working on '{}' ...".format(node.label))
        self.show_progress_bar(animate=True)
        self.hexdump.set(node.get_hexdump()).show_disabled()
        self.details.set(node.get_details()).show_disabled()
        '''
		if node.exists == False:
			msg = "No data to display, file needs to be extracted first"
			self.hexdump.set(msg).show_disabled()
			self.details.set(msg).show_disabled()
		elif node.label == "Root":
			self.hexdump.set("").show_disabled()
			self.details.set("This is your main installation file").show_disabled()
		else:
			def callback():
				self.update_progress_bar()
			processor = node.processor
			if processor:
				print("- Processor:",processor)
				if processor.has_hexdump:
					self.hexdump.set(processor.get_hexdump(callback)).show_enabled()
					self.content.select(self.hexdump_tab)
				else:
					self.hexdump.set("No hex dump avail for this type of file").show_disabled()
				if processor.has_details:
					self.details.set(processor.get_details(callback)).show_enabled()
					self.content.select(self.details_tab)
				else:
					self.details.set("No details avail for this type of file").show_disabled()
			else:
				self.hexdump.set("").show_disabled()
				self.details.set("").show_disabled()
		'''
        self.set_statusbar(None)
        self.hide_progress_bar()
        Tk.update(self)

    def tree_expanding(self, event, iid):
        if not iid:
            return
        node = self.nodes[iid]
        print("\nTree expanding:\n-", iid, "->", node)
        self.nodes.expand(iid)
        '''
		childs = self.tree.childs(iid)
		print("  -",childs)
		if len(childs) == 1 and childs[0].endswith("/dummy"):
			self.tree.delete(childs)
			self.tree_populate(iid, True, True, 1)
		'''

    def tree_populate(self,
                      iid,
                      open=False,
                      init_progress=False,
                      max_levels=None):
        if not iid:
            return

        vals = self.values[iid]
        self.set_statusbar("Working on '{}' ...".format(vals["label"]))
        if init_progress:
            self.app_busy()
            self.show_progress_bar(animate=True)

        try:
            processor = vals["processor"]
            if not processor:
                return

            # Get childs ...
            def callback():
                self.update_progress_bar()
                #Tk.update_idletasks(self)

            content = processor.get_childs(callback) or {}
            if not len(content):
                return

            # ... and fill tree
            print(content, "\n")
            if max_levels:
                max_levels += iid.count("/")

            def recurs_fill(curr, parent, vals, open):
                print(parent, ">>", self.prettify_values(vals))

                file = os.path.join(vals["extract_to"], vals["label"])
                depth = parent.count("/") + 1

                #if max_levels and depth > max_levels:
                #	if os.path.isdir(file):
                #		dummy = self.tree.add(parent, "dummy", "dummy", None)
                #	return

                if not "processor" in vals:
                    filename, ext = os.path.splitext(vals["label"])
                    is_archive = ext.lower() in (".zip", ".cab")

                    vals["processor"] = ProcessorFactory.create(file)
                    if is_archive:
                        vals["info"] = "(Archive)"
                        vals["extract_to"] = os.path.join(
                            vals["extract_to"], filename)
                    else:
                        vals["info"] = "(File)" if os.path.isfile(file) \
                          else "(Folder)" if os.path.isdir(file) \
                          else "?"
                        vals["extract_to"] = file
                    vals["exists"] = os.path.exists(file)  #vals["extract_to"])

                    new_parent = self.tree.add(parent, vals["label"],
                                               vals["info"], vals["exists"],
                                               depth < 2)
                    self.values[new_parent] = vals

                    if is_archive and vals["exists"]:
                        # Process archive contents
                        #self.tree_populate(new_parent, False)
                        # Delayed until knot gets expanded, so we do add a
                        # fake which gets replaced when expanded
                        dummy = self.tree.add(new_parent, "dummy", "dummy",
                                              None)

                    parent = new_parent

                # Non-path childs first
                for file in sorted(
                    [key for key in curr.keys() if len(curr[key]) == 0]):
                    print("- File:", file)
                    new_vals = {
                        "label": file,
                        "extract_to": vals["extract_to"]
                    }
                    recurs_fill(curr[file], parent, new_vals, depth < 2)
                # Paths second
                for path in sorted(
                    [key for key in curr.keys() if len(curr[key]) > 0]):
                    print("- Path:", path)
                    new_vals = {
                        "label": path,
                        "extract_to": vals["extract_to"]
                    }
                    recurs_fill(curr[path], parent, new_vals, depth < 2)

            recurs_fill(content["\\"], iid, vals, open)
            #'''
        finally:
            if init_progress:
                self.set_statusbar()
                self.hide_progress_bar()
                self.app_ready()
        '''
		try:
			def callback():
				self.update_progress_bar()
				#Tk.update_idletasks(self)
			processor = vals["processor"]
			if not processor:
				return
			# Process processor contents
			content = processor.get_childs(callback) or {}
			if not len(content):
				return
			# ... and fill tree
			def check_existance(path, file):
				if not os.path.exists(path):
					return (False,None)
				info = None
				location = None
				name,ext = os.path.splitext(file)
				ext = ext.lower()
				if ext == ".zip" or ext == ".cab":
					info = "(Archive)"
					location = name
				else:
					name += ext
				return (os.path.exists(os.path.join(path,name)),info,location)
			def recurs_fill(curr, extract_path, parent, filename, info, exists, open, skip_this=False):
				callback()
				#print("-",filename,"@",extract_path)
				print("-",self.shorten_path(extract_path))
				self.set_statusbar(extract_path)
				if not skip_this:
					iid = parent + "/" + filename
					#if not iid in self.values:
					processor = ProcessorFactory.create(extract_path)
					#if info == "zip" or info == "cab":
					#	extract_path = extract_path[:-(len(info)+1)]
					#	info = "(Archive)"
					iid = self.tree.add(parent, filename, info, exists, open)
					self.values[iid] = { "label":filename, "info":info, "exists":exists, "processor":processor, \
										"path":os.path.join(self.values[parent]["path"],filename), "extract_to":extract_path }
					parent = iid
				for key in sorted(curr.keys()):
					if len(curr[key]) > 0: continue # Non-branches first
					curr_path = os.path.join(extract_path,key)
					exists,info,location = check_existance(extract_path,key)
					if not info: info = "(File)"
					iid = recurs_fill(curr[key], curr_path, parent, key, info, exists, open)
				for key in sorted(curr.keys()):
					if len(curr[key]) == 0: continue # Branches second
					curr_path = os.path.join(extract_path,key)
					exists,info,location = check_existance(extract_path,key)
					iid = recurs_fill(curr[key], curr_path, parent, key, info, exists, open)

			if not open and iid in self.values:
				self.tree.widget.item(iid, open=False)
			recurs_fill(content["\\"], vals["extract_to"], iid, vals["label"], vals["info"], vals["exists"], open, True)
		finally:
			self.set_statusbar()
			self.hide_progress_bar()
		'''

    '''
	Menu handlers
	'''

    def fileOpenRoot(self):
        new_file = filedialog.askopenfilename(
            title="Select SyncMyRide root file",
            filetypes=[("Containers", ".zip .cab")],
            defaultextension=".zip")
        if len(new_file) > 0:
            _options.last_selection = None
            _options.current_marker = None
            _options.cabinet = new_file
            self.update_extract_location()
            self.update_ui()
            self.update_tree()

    def fileCloseRoot(self):
        _options.last_selection = None
        _options.current_marker = None
        _options.cabinet = None
        self.extract_to = None
        self.update_ui()
        self.update_tree()

    def fileExtractSelected(self):
        raise Exception(__name__ + " needs new implementation")
        '''
		values = self.values[self.tree.current]
		print("\nThis will extract selected item only: {}\n{}".\
			format(self.tree.current,self.prettify_values(values)))
		processor = values["processor"]
		if processor and processor.can_save:
			processor.save(values["extract_to"], callback=self.extract_callback)
			#self.update_ui()
			self.tree_populate(self.tree.current)
		'''

    def fileExtractAll(self):
        raise Exception(__name__ + " needs new implementation")
        '''
		print("\nThis will extract all contents from {}".\
			format(os.path.basename(_options.cabinet)))
		values = self.values[os.path.basename(_options.cabinet)]
		processor = values["processor"]
		if processor and processor.can_save:
			#processor.save(vals["extract_to"], callback=self.extract_callback)
			#TODO: call childs
			self.update_ui()
		'''

    def fileOptions(self):
        dlg = OptionsDialog(self.master, _options)
        if dlg.changed:
            #TODO: Save changes
            self.update_ui()

    def fileExit(self):
        self.master.destroy()

    def helpAbout(self):
        AboutDialog(self.master)

    '''
	Progress bar handling
	'''

    def show_progress_bar(self, max_=100, animate=False):
        self.hide_progress_bar()
        self.progressbar = ttk.Progressbar(
            self.statusbar,
            orient=HORIZONTAL,
            length=200,
            mode=("indeterminate" if animate else "determinate"),
            maximum=max_)
        self.progressbar.grid(column=1, row=0, sticky=NSEW)
        if animate:
            self.progressbar.start(100)
        Tk.update_idletasks(self)

    def hide_progress_bar(self):
        if self.progressbar:
            self.progressbar.destroy()
        self.progressbar = None
        Tk.update_idletasks(self)

    def update_progress_bar(self, pos=None):
        if self.progressbar:
            if pos:
                self.progressbar.step(pos)
            else:
                self.progressbar.step()
        Tk.update_idletasks(self)

    '''
	Status bar handling
	'''

    def set_statusbar(self, text=None):
        self.statustext["text"] = text or "Ready ..."
        Tk.update_idletasks(self)

    '''
	Mouse cursor handling
	'''

    def app_busy(self):
        self._mouse("wait")

    def app_ready(self):
        self._mouse("")

    def _mouse(self, cursor):
        root.config(cursor=cursor)
        Tk.update(root)

    '''
	Helpers
	'''

    def get_title(self):
        s = "DumpMyRide"
        if _options.cabinet:
            s += " - " + os.path.basename(_options.cabinet)
        return s

    def update_extract_location(self):
        if not _options.cabinet:
            self.extract_to = None
            return
        subdir = _options.extract_location
        if "%filename%" in subdir:
            subdir = subdir.replace(
                "%filename%",
                os.path.splitext(os.path.basename(_options.cabinet))[0])
        self.extract_to = os.path.join(os.path.dirname(_options.cabinet),
                                       subdir)
        print("Will use following extract location:\n    " + self.extract_to)

    def extract_callback(self, type, info=None):
        if type == "archive_start":  # info: No. of files to be extracted
            self.set_statusbar("Starting extraction ...")
            self.show_progress_bar(max_=info + 1)
            Tk.update_idletasks(self)
            return
        if type == "archive_end":  # info: Success-flag
            self.set_statusbar("Done extracting")
            self.hide_progress_bar()
            Tk.update_idletasks(self)
            return
        if type == "file_start":  # info: File being extracted (relative path)
            self.set_statusbar("Extracting {} ...".format(info))
            self.update_progress_bar()
            Tk.update_idletasks(self)
            return
        if type == "file_end":  # info: File extracted (relative path)
            '''
			=> MUST be dealt with in another place as we're lacking info on 'parent'
			while info.endswith("/"): info = info[:-1]
			while info.endswith("\\"): info = info[:-1]
			iid = os.path.basename(_options.cabinet) + "/" + info
			if iid in self.values:
				file = os.path.join(self.extract_to,info)
				self.tree.update_image(iid, os.path.exists(file))
			if not self.values[iid]["processor"]:
				self.values[iid]["processor"] = ProcessorFactory.create(file)
				#print("  => ", self.values[iid]["processor"])
				if self.values[iid]["processor"] and self.values[iid]["processor"].can_save:
					#TODO: Build subtree
					todo = ""
			'''
            Tk.update_idletasks(self)
Beispiel #12
0
    def playGameWithComputer(self):
        count = 1
        while self.moveCount < 31:
            print("The human's moves have been",
                  self.player1Moves)  #For testing
            print("Computer moves", self.computerMoves)
            self.getGameRectangle(self.player1Moves, self.computerMoves)
            value = 0
            if self.currentPlayer is self.Player2:
                value = 2
                print("It is the computer's turn:")
                TokenMoveValue = self.computerPlaceOrMove()
                testing = Nodes(self, self.theBoard, self.Player1,
                                self.Player2)  #NOTE: USED FOR TESTING
                #testing.generateChildren(1) # NOTE: USED FOR TESTING
                if (TokenMoveValue == "N" or TokenMoveValue == "n" or
                    (count < 3)) and (self.currentPlayer.getTokens() > 0):
                    if (not (count < 3)
                        ) and self.currentPlayer.getTokens() > 0:
                        print("The computer has chosen to place a new token")
                    self.computerPlaceToken()
                    print(self.computerMoves)  # NOTE: USED FOR TESTING
                    print("The computer has ", self.currentPlayer.getTokens(),
                          " tokens remaining.")
                elif TokenMoveValue == 'M' or TokenMoveValue == "m" or self.currentPlayer.getTokens(
                ) <= 0:
                    if self.currentPlayer.getTokens() > 0:
                        print("The computer has chosen to move a token")
                    elif self.currentPlayer.getTokens() <= 0:
                        print(
                            "The computer has used up all their tokens and can only move tokens now. "
                            "There are ", self.moveCount,
                            "moves left in the game.")
                    if self.moveCount < 31:  # number of moves must be 30
                        self.move(value)
                    else:
                        print("Game reached its number of moves ... ")
            elif self.currentPlayer is self.Player1:
                value = 1
                print("It is Player 1 (P1)'s turn, ",
                      self.currentPlayer.getName(), ":")
                if (
                        self.currentPlayer.getTokens() > 0
                ):  # If player has tokens, they can either place token or move tokens
                    print("You have", self.currentPlayer.getTokens(),
                          "tokens remaining.")
                    self.chooseTokenMove(value, count)
                elif self.currentPlayer.getTokens(
                ) < 0:  # Once the player has used all their tokens, they can only move tokens around
                    print(
                        "You have used up all your tokens. Now, you can only move tokens. There are ",
                        self.moveCount, "moves left in the game.")
                    self.move(value)

            count = count + 1
            if self.isWinner(int(self.lastPieceXCoordinate),
                             int(self.lastPieceYCoordinate),
                             self.currentPlayer):
                self.winner = self.currentPlayer
                break

            if self.wasLastRoundAMove and 0 < self.lastMoveXCoordinate < 11 and self.isWinner(
                (self.lastMoveXCoordinate + 1), self.lastMoveYCoordinate,
                    self.getOpponent(self.currentPlayer)):
                self.winner = self.getOpponent(self.currentPlayer)
                break

            self.printGame()
            self.switchPlayers()

        if self.moveCount <= 0:  # number of moves must be 30
            print("Game reached its number of moves ... ")

        self.printGame()
        if (self.winner != "null"):
            print("The winner is", self.winner.getName())
        else:
            print("The game resulted in a tie")
import sys

from Nodes import Nodes as Nodes


def get_kth_element(k, node):
    if k == 0:
        return node.data
    else:
        return get_kth_element(k - 1, node.next())


if __name__ == "__main__":
    if len(sys.argv) <= 2:
        print "Not enough arguments to get_kth element"
    else:
        k = int(sys.argv[1])  # get kth element from end of list
        head = Nodes(sys.argv[2])
        node = head
        for i in range(3, len(sys.argv)):
            next = Nodes(sys.argv[i])
            node.set_next(next)
            node = next
        print "the kth element is " + str(
            get_kth_element(len(sys.argv) - 2 - k, head))
Beispiel #14
0
 def add_to_head(self, data):
     n = Nodes.Nodes(data);
     self._add_to_head(n)
Beispiel #15
0
 def append(self, data):
     n = Nodes.Nodes(data)
     self._append(n)