问:
Print out Python console output to Qtextedit
I have the output like this, when I press the button:

['VERSION', 'ROMMON', 'HOSTNAME', 'UPTIME', 'RUNNING_IMAGE',
'HARDWARE', 'SERIAL', 'CONFIG_REGISTER']

['12.2(55)SE7', 'Bootstrap', 'Revo-Solusindo-01', '1 hour, 27
minutes', 'c2960s-universalk9-mz.122-55.SE7.bin',
['WS-C2960S-24PD-L'], ['FOC1644Z129'], '0xF'] Write 1 records

['FAN', 'TEMPERATURE', 'TEMPERATURE_VALUE', 'TEMPERATURE_STATE',
'YELLOW_THRESHOLD', 'RED_THRESHOLD', 'POWER', 'RPS']

['OK', 'OK', '33', 'GREEN', '54', '64', '', ''] Write 1 records

['TOTAL', 'FFREE']

['57931776', '29178368']

['524288', '523212'] Write 2 records

['MEMTYPE', 'HEAD', 'TOTAL', 'USED', 'FREE', 'LOW', 'LARGE']

['Processor', '2BA9598', '73910760', '26908308', '47002452',
'45367928', '30211716']

['      I/O', '6200000', '14680064', '12406764', '2273300', '2273300',
'2273024']

['Driver te', '1A00000', '1048576', '44', '1048532', '1048532',
'1048532'] Write 3 records

['CPU_5_SEC', 'CPU_1_MIN', 'CPU_5_MIN']

['10', '10', '9'] Write 1 records

How can I print the output of the background process to Qtextedit?

My code:

```<code>import sys
from PyQt4 import QtGui, QtCore
import jtextfsm as textfsm

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

    def home(self):
        btn = QtGui.QPushButton("Generate", self)
        btn.clicked.connect(self.TextFSM)
        btn.resize(100, 50)
        btn.move(50, 50)

        process  = QtGui.QTextEdit(self)
        process.moveCursor(QtGui.QTextCursor.Start)
        process.ensureCursorVisible()
        process.setLineWrapColumnOrWidth(500)
        process.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)
        process.setFixedWidth(400)
        process.setFixedHeight(150)
        process.move(50,100)

        self.show()

    def TextFSM(self):

        nameFile = 'Switch'

        try:
            input_file = open(nameFile + '.txt', encoding='utf-8')  # show version
            raw_text_data = input_file.read()
            input_file.close()

            input_file2 = open(nameFile + '.txt', encoding='utf-8')  # show env
            raw_text_data2 = input_file2.read()
            input_file2.close()

            input_file3 = open(nameFile + '.txt', encoding='utf-8')  # show flash
            raw_text_data3 = input_file3.read()
            input_file3.close()

            input_file4 = open(nameFile + '.txt', encoding='utf-8')  # show memory statistic
            raw_text_data4 = input_file4.read()
            input_file4.close()

            input_file5 = open(nameFile + '.txt', encoding='utf-8')  # show process cpu
            raw_text_data5 = input_file5.read()
            input_file5.close()

            template = open("show-version.textfsm")  # show version
            re_table = textfsm.TextFSM(template)
            fsm_results = re_table.ParseText(raw_text_data)

            template2 = open("show-env.textfsm")  # show env
            re_table2 = textfsm.TextFSM(template2)
            fsm_results2 = re_table2.ParseText(raw_text_data2)

            template3 = open("show-flash.textfsm")  # show flash
            re_table3 = textfsm.TextFSM(template3)
            fsm_results3 = re_table3.ParseText(raw_text_data3)

            template4 = open("show-memory-statistic.textfsm")  # show memory statistic
            re_table4 = textfsm.TextFSM(template4)
            fsm_results4 = re_table4.ParseText(raw_text_data4)

            template5 = open("show-process-cpu.textfsm")  # show process cpu
            re_table5 = textfsm.TextFSM(template5)
            fsm_results5 = re_table5.ParseText(raw_text_data5)

            outfile_name = open(nameFile + "-show-version.csv", "w+")  # show version
            outfile = outfile_name

            outfile_name2 = open(nameFile + "-show-env.csv", "w+")  # show env
            outfile2 = outfile_name2

            outfile_name3 = open(nameFile + "-show-flash.csv", "w+")  # show flash
            outfile3 = outfile_name3

            outfile_name4 = open(nameFile + "-show-memory-statistic.csv", "w+")  # show memory statistic
            outfile4 = outfile_name4

            outfile_name5 = open(nameFile + "-show-process-cpu.csv", "w+")  # show process cpu
            outfile5 = outfile_name5

            print(re_table.header)  # show version
            for s in re_table.header:
                outfile.write("%s;" % s)
            outfile.write("\n")

            counter = 0
            for row in fsm_results:  # show version
                print(row)
                for s in row:
                    outfile.write("%s;" % s)
                outfile.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table2.header)  # show env
            for s in re_table2.header:
                outfile2.write("%s;" % s)
            outfile2.write("\n")

            counter = 0
            for row in fsm_results2:  # show env
                print(row)
                for s in row:
                    outfile2.write("%s;" % s)
                outfile2.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table3.header)  # show flash
            for s in re_table3.header:
                outfile3.write("%s;" % s)
            outfile3.write("\n")

            counter = 0
            for row in fsm_results3:  # show flash
                print(row)
                for s in row:
                    outfile3.write("%s;" % s)
                outfile3.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table4.header)  # show memory statistics
            for s in re_table4.header:
                outfile4.write("%s;" % s)
            outfile4.write("\n")

            counter = 0
            for row in fsm_results4:  # show memory statistics
                print(row)
                for s in row:
                    outfile4.write("%s;" % s)
                outfile4.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table5.header)  # show process cpu
            for s in re_table5.header:
                outfile5.write("%s;" % s)
            outfile5.write("\n")

            counter = 0
            for row in fsm_results5:  # show process cpu
                print(row)
                for s in row:
                    outfile5.write("%s;" % s)
                outfile5.write("\n")
                counter += 1
            print("Write %d records" % counter)
        except IOError:
            print("Error: There Have File does not appear to exist.")
            QtGui.QMessageBox.question(self, 'Warning', "ERROR:Please check you're '.txt' file and TextFSM File.")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()
</code>```

答:
The output consoles produced by Python are written to the program output streams sys.stdout (normal output) and sys.stderr (error output, such as exception tracebacks). In this case we will use stdout

```<code>class Stream(QtCore.QObject):
    newText = QtCore.pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

        sys.stdout = Stream(newText=self.onUpdateText)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__
</code>```

Complete code:

```<code>import sys
from PyQt4 import QtGui, QtCore
import jtextfsm as textfsm

class Stream(QtCore.QObject):
    newText = QtCore.pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

        sys.stdout = Stream(newText=self.onUpdateText)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__

    def home(self):

        w = QtGui.QWidget()
        self.setCentralWidget(w)
        lay = QtGui.QVBoxLayout(w)
        btn = QtGui.QPushButton("Generate")
        btn.clicked.connect(self.TextFSM)

        self.process  = QtGui.QTextEdit()
        self.process.moveCursor(QtGui.QTextCursor.Start)
        self.process.ensureCursorVisible()
        self.process.setLineWrapColumnOrWidth(500)
        self.process.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)

        lay.addWidget(btn)
        lay.addWidget(self.process)

        self.show()

    def TextFSM(self):

        nameFile = 'Switch'

        try:
            input_file = open(nameFile + '.txt', encoding='utf-8')  # show version
            raw_text_data = input_file.read()
            input_file.close()

            input_file2 = open(nameFile + '.txt', encoding='utf-8')  # show env
            raw_text_data2 = input_file2.read()
            input_file2.close()

            input_file3 = open(nameFile + '.txt', encoding='utf-8')  # show flash
            raw_text_data3 = input_file3.read()
            input_file3.close()

            input_file4 = open(nameFile + '.txt', encoding='utf-8')  # show memory statistic
            raw_text_data4 = input_file4.read()
            input_file4.close()

            input_file5 = open(nameFile + '.txt', encoding='utf-8')  # show process cpu
            raw_text_data5 = input_file5.read()
            input_file5.close()

            template = open("show-version.textfsm")  # show version
            re_table = textfsm.TextFSM(template)
            fsm_results = re_table.ParseText(raw_text_data)

            template2 = open("show-env.textfsm")  # show env
            re_table2 = textfsm.TextFSM(template2)
            fsm_results2 = re_table2.ParseText(raw_text_data2)

            template3 = open("show-flash.textfsm")  # show flash
            re_table3 = textfsm.TextFSM(template3)
            fsm_results3 = re_table3.ParseText(raw_text_data3)

            template4 = open("show-memory-statistic.textfsm")  # show memory statistic
            re_table4 = textfsm.TextFSM(template4)
            fsm_results4 = re_table4.ParseText(raw_text_data4)

            template5 = open("show-process-cpu.textfsm")  # show process cpu
            re_table5 = textfsm.TextFSM(template5)
            fsm_results5 = re_table5.ParseText(raw_text_data5)

            outfile_name = open(nameFile + "-show-version.csv", "w+")  # show version
            outfile = outfile_name

            outfile_name2 = open(nameFile + "-show-env.csv", "w+")  # show env
            outfile2 = outfile_name2

            outfile_name3 = open(nameFile + "-show-flash.csv", "w+")  # show flash
            outfile3 = outfile_name3

            outfile_name4 = open(nameFile + "-show-memory-statistic.csv", "w+")  # show memory statistic
            outfile4 = outfile_name4

            outfile_name5 = open(nameFile + "-show-process-cpu.csv", "w+")  # show process cpu
            outfile5 = outfile_name5

            print(re_table.header)  # show version
            for s in re_table.header:
                outfile.write("%s;" % s)
            outfile.write("\n")

            counter = 0
            for row in fsm_results:  # show version
                print(row)
                for s in row:
                    outfile.write("%s;" % s)
                outfile.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table2.header)  # show env
            for s in re_table2.header:
                outfile2.write("%s;" % s)
            outfile2.write("\n")

            counter = 0
            for row in fsm_results2:  # show env
                print(row)
                for s in row:
                    outfile2.write("%s;" % s)
                outfile2.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table3.header)  # show flash
            for s in re_table3.header:
                outfile3.write("%s;" % s)
            outfile3.write("\n")

            counter = 0
            for row in fsm_results3:  # show flash
                print(row)
                for s in row:
                    outfile3.write("%s;" % s)
                outfile3.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table4.header)  # show memory statistics
            for s in re_table4.header:
                outfile4.write("%s;" % s)
            outfile4.write("\n")

            counter = 0
            for row in fsm_results4:  # show memory statistics
                print(row)
                for s in row:
                    outfile4.write("%s;" % s)
                outfile4.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table5.header)  # show process cpu
            for s in re_table5.header:
                outfile5.write("%s;" % s)
            outfile5.write("\n")

            counter = 0
            for row in fsm_results5:  # show process cpu
                print(row)
                for s in row:
                    outfile5.write("%s;" % s)
                outfile5.write("\n")
                counter += 1
            print("Write %d records" % counter)
        except IOError:
            print("Error: There Have File does not appear to exist.")
            QtGui.QMessageBox.question(self, 'Warning', "ERROR:Please check you're '.txt' file and TextFSM File.")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()
</code>```

Screenshot:

Body:
I have the output like this, when I press the button:

['VERSION', 'ROMMON', 'HOSTNAME', 'UPTIME', 'RUNNING_IMAGE',
'HARDWARE', 'SERIAL', 'CONFIG_REGISTER']

['12.2(55)SE7', 'Bootstrap', 'Revo-Solusindo-01', '1 hour, 27
minutes', 'c2960s-universalk9-mz.122-55.SE7.bin',
['WS-C2960S-24PD-L'], ['FOC1644Z129'], '0xF'] Write 1 records

['FAN', 'TEMPERATURE', 'TEMPERATURE_VALUE', 'TEMPERATURE_STATE',
'YELLOW_THRESHOLD', 'RED_THRESHOLD', 'POWER', 'RPS']

['OK', 'OK', '33', 'GREEN', '54', '64', '', ''] Write 1 records

['TOTAL', 'FFREE']

['57931776', '29178368']

['524288', '523212'] Write 2 records

['MEMTYPE', 'HEAD', 'TOTAL', 'USED', 'FREE', 'LOW', 'LARGE']

['Processor', '2BA9598', '73910760', '26908308', '47002452',
'45367928', '30211716']

['      I/O', '6200000', '14680064', '12406764', '2273300', '2273300',
'2273024']

['Driver te', '1A00000', '1048576', '44', '1048532', '1048532',
'1048532'] Write 3 records

['CPU_5_SEC', 'CPU_1_MIN', 'CPU_5_MIN']

['10', '10', '9'] Write 1 records

How can I print the output of the background process to Qtextedit?

My code:

import sys
from PyQt4 import QtGui, QtCore
import jtextfsm as textfsm

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

    def home(self):
        btn = QtGui.QPushButton("Generate", self)
        btn.clicked.connect(self.TextFSM)
        btn.resize(100, 50)
        btn.move(50, 50)

        process  = QtGui.QTextEdit(self)
        process.moveCursor(QtGui.QTextCursor.Start)
        process.ensureCursorVisible()
        process.setLineWrapColumnOrWidth(500)
        process.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)
        process.setFixedWidth(400)
        process.setFixedHeight(150)
        process.move(50,100)

        self.show()

    def TextFSM(self):

        nameFile = 'Switch'

        try:
            input_file = open(nameFile + '.txt', encoding='utf-8')  # show version
            raw_text_data = input_file.read()
            input_file.close()

            input_file2 = open(nameFile + '.txt', encoding='utf-8')  # show env
            raw_text_data2 = input_file2.read()
            input_file2.close()

            input_file3 = open(nameFile + '.txt', encoding='utf-8')  # show flash
            raw_text_data3 = input_file3.read()
            input_file3.close()

            input_file4 = open(nameFile + '.txt', encoding='utf-8')  # show memory statistic
            raw_text_data4 = input_file4.read()
            input_file4.close()

            input_file5 = open(nameFile + '.txt', encoding='utf-8')  # show process cpu
            raw_text_data5 = input_file5.read()
            input_file5.close()

            template = open("show-version.textfsm")  # show version
            re_table = textfsm.TextFSM(template)
            fsm_results = re_table.ParseText(raw_text_data)

            template2 = open("show-env.textfsm")  # show env
            re_table2 = textfsm.TextFSM(template2)
            fsm_results2 = re_table2.ParseText(raw_text_data2)

            template3 = open("show-flash.textfsm")  # show flash
            re_table3 = textfsm.TextFSM(template3)
            fsm_results3 = re_table3.ParseText(raw_text_data3)

            template4 = open("show-memory-statistic.textfsm")  # show memory statistic
            re_table4 = textfsm.TextFSM(template4)
            fsm_results4 = re_table4.ParseText(raw_text_data4)

            template5 = open("show-process-cpu.textfsm")  # show process cpu
            re_table5 = textfsm.TextFSM(template5)
            fsm_results5 = re_table5.ParseText(raw_text_data5)

            outfile_name = open(nameFile + "-show-version.csv", "w+")  # show version
            outfile = outfile_name

            outfile_name2 = open(nameFile + "-show-env.csv", "w+")  # show env
            outfile2 = outfile_name2

            outfile_name3 = open(nameFile + "-show-flash.csv", "w+")  # show flash
            outfile3 = outfile_name3

            outfile_name4 = open(nameFile + "-show-memory-statistic.csv", "w+")  # show memory statistic
            outfile4 = outfile_name4

            outfile_name5 = open(nameFile + "-show-process-cpu.csv", "w+")  # show process cpu
            outfile5 = outfile_name5

            print(re_table.header)  # show version
            for s in re_table.header:
                outfile.write("%s;" % s)
            outfile.write("\n")

            counter = 0
            for row in fsm_results:  # show version
                print(row)
                for s in row:
                    outfile.write("%s;" % s)
                outfile.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table2.header)  # show env
            for s in re_table2.header:
                outfile2.write("%s;" % s)
            outfile2.write("\n")

            counter = 0
            for row in fsm_results2:  # show env
                print(row)
                for s in row:
                    outfile2.write("%s;" % s)
                outfile2.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table3.header)  # show flash
            for s in re_table3.header:
                outfile3.write("%s;" % s)
            outfile3.write("\n")

            counter = 0
            for row in fsm_results3:  # show flash
                print(row)
                for s in row:
                    outfile3.write("%s;" % s)
                outfile3.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table4.header)  # show memory statistics
            for s in re_table4.header:
                outfile4.write("%s;" % s)
            outfile4.write("\n")

            counter = 0
            for row in fsm_results4:  # show memory statistics
                print(row)
                for s in row:
                    outfile4.write("%s;" % s)
                outfile4.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table5.header)  # show process cpu
            for s in re_table5.header:
                outfile5.write("%s;" % s)
            outfile5.write("\n")

            counter = 0
            for row in fsm_results5:  # show process cpu
                print(row)
                for s in row:
                    outfile5.write("%s;" % s)
                outfile5.write("\n")
                counter += 1
            print("Write %d records" % counter)
        except IOError:
            print("Error: There Have File does not appear to exist.")
            QtGui.QMessageBox.question(self, 'Warning', "ERROR:Please check you're '.txt' file and TextFSM File.")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

Body:
The output consoles produced by Python are written to the program output streams sys.stdout (normal output) and sys.stderr (error output, such as exception tracebacks). In this case we will use stdout

class Stream(QtCore.QObject):
    newText = QtCore.pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

        sys.stdout = Stream(newText=self.onUpdateText)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__

Complete code:

import sys
from PyQt4 import QtGui, QtCore
import jtextfsm as textfsm

class Stream(QtCore.QObject):
    newText = QtCore.pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

        sys.stdout = Stream(newText=self.onUpdateText)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__

    def home(self):

        w = QtGui.QWidget()
        self.setCentralWidget(w)
        lay = QtGui.QVBoxLayout(w)
        btn = QtGui.QPushButton("Generate")
        btn.clicked.connect(self.TextFSM)

        self.process  = QtGui.QTextEdit()
        self.process.moveCursor(QtGui.QTextCursor.Start)
        self.process.ensureCursorVisible()
        self.process.setLineWrapColumnOrWidth(500)
        self.process.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)

        lay.addWidget(btn)
        lay.addWidget(self.process)

        self.show()

    def TextFSM(self):

        nameFile = 'Switch'

        try:
            input_file = open(nameFile + '.txt', encoding='utf-8')  # show version
            raw_text_data = input_file.read()
            input_file.close()

            input_file2 = open(nameFile + '.txt', encoding='utf-8')  # show env
            raw_text_data2 = input_file2.read()
            input_file2.close()

            input_file3 = open(nameFile + '.txt', encoding='utf-8')  # show flash
            raw_text_data3 = input_file3.read()
            input_file3.close()

            input_file4 = open(nameFile + '.txt', encoding='utf-8')  # show memory statistic
            raw_text_data4 = input_file4.read()
            input_file4.close()

            input_file5 = open(nameFile + '.txt', encoding='utf-8')  # show process cpu
            raw_text_data5 = input_file5.read()
            input_file5.close()

            template = open("show-version.textfsm")  # show version
            re_table = textfsm.TextFSM(template)
            fsm_results = re_table.ParseText(raw_text_data)

            template2 = open("show-env.textfsm")  # show env
            re_table2 = textfsm.TextFSM(template2)
            fsm_results2 = re_table2.ParseText(raw_text_data2)

            template3 = open("show-flash.textfsm")  # show flash
            re_table3 = textfsm.TextFSM(template3)
            fsm_results3 = re_table3.ParseText(raw_text_data3)

            template4 = open("show-memory-statistic.textfsm")  # show memory statistic
            re_table4 = textfsm.TextFSM(template4)
            fsm_results4 = re_table4.ParseText(raw_text_data4)

            template5 = open("show-process-cpu.textfsm")  # show process cpu
            re_table5 = textfsm.TextFSM(template5)
            fsm_results5 = re_table5.ParseText(raw_text_data5)

            outfile_name = open(nameFile + "-show-version.csv", "w+")  # show version
            outfile = outfile_name

            outfile_name2 = open(nameFile + "-show-env.csv", "w+")  # show env
            outfile2 = outfile_name2

            outfile_name3 = open(nameFile + "-show-flash.csv", "w+")  # show flash
            outfile3 = outfile_name3

            outfile_name4 = open(nameFile + "-show-memory-statistic.csv", "w+")  # show memory statistic
            outfile4 = outfile_name4

            outfile_name5 = open(nameFile + "-show-process-cpu.csv", "w+")  # show process cpu
            outfile5 = outfile_name5

            print(re_table.header)  # show version
            for s in re_table.header:
                outfile.write("%s;" % s)
            outfile.write("\n")

            counter = 0
            for row in fsm_results:  # show version
                print(row)
                for s in row:
                    outfile.write("%s;" % s)
                outfile.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table2.header)  # show env
            for s in re_table2.header:
                outfile2.write("%s;" % s)
            outfile2.write("\n")

            counter = 0
            for row in fsm_results2:  # show env
                print(row)
                for s in row:
                    outfile2.write("%s;" % s)
                outfile2.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table3.header)  # show flash
            for s in re_table3.header:
                outfile3.write("%s;" % s)
            outfile3.write("\n")

            counter = 0
            for row in fsm_results3:  # show flash
                print(row)
                for s in row:
                    outfile3.write("%s;" % s)
                outfile3.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table4.header)  # show memory statistics
            for s in re_table4.header:
                outfile4.write("%s;" % s)
            outfile4.write("\n")

            counter = 0
            for row in fsm_results4:  # show memory statistics
                print(row)
                for s in row:
                    outfile4.write("%s;" % s)
                outfile4.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table5.header)  # show process cpu
            for s in re_table5.header:
                outfile5.write("%s;" % s)
            outfile5.write("\n")

            counter = 0
            for row in fsm_results5:  # show process cpu
                print(row)
                for s in row:
                    outfile5.write("%s;" % s)
                outfile5.write("\n")
                counter += 1
            print("Write %d records" % counter)
        except IOError:
            print("Error: There Have File does not appear to exist.")
            QtGui.QMessageBox.question(self, 'Warning', "ERROR:Please check you're '.txt' file and TextFSM File.")

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

Screenshot:


来源: stackexchange

问:
Can't access Eureka form object from outside viewDidLoad
I'm trying to create a Eureka form for editing / creating a task object. Now, I segue to the view and pass on a Task object as class variable, but for some reason it is not accessible from viewDidLoad where I'm creating the form. This means I can't assign values to the form. When I create a didSet method for the Task class variable, it gets called eventually, but then the form object is an empty object, as when I look form.values() there is nothing. But in viewDidLoad it works. Any suggestions what am I missing?

```<code>var task: Task? { didSet { print("didSet values:", form.values(), "didSet task name", task?.name) } }

override func viewDidLoad() {
    super.viewDidLoad()

    form +++ Section()
        <<< TextRow("name"){
            $0.title = "Name"
        }

    print("viewDidLoad values:", form.values(), "viewDidLoad task name", task?.name)
}
</code>```

and output

```<code>viewDidLoad values: ["name": nil, "deadline": Optional(2017-06-08 19:02:39 +0000)] viewDidLoad task name nil
didSet values: [:] didSet task name Optional("ascasc")
</code>```

答: Well, after debugging I found that there were two different instances of the Eureka form view. So after digging I found that I did two segues doing the same thing. One segue from storyboard tableView cell to the form, and other from code by didSelectRowAt and performSegue. Interesting that I didn't find this when I debugged the prepare(for segue:) from the controller which called the form view, it should have printed the output twice, but I saw only one, so I was always thinking I was creating only one segue.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a Eureka form for editing / creating a task object. Now, I segue to the view and pass on a Task object as class variable, but for some reason it is not accessible from viewDidLoad where I'm creating the form. This means I can't assign values to the form. When I create a didSet method for the Task class variable, it gets called eventually, but then the form object is an empty object, as when I look form.values() there is nothing. But in viewDidLoad it works. Any suggestions what am I missing?

var task: Task? { didSet { print("didSet values:", form.values(), "didSet task name", task?.name) } }

override func viewDidLoad() {
    super.viewDidLoad()

    form +++ Section()
        <<< TextRow("name"){
            $0.title = "Name"
        }

    print("viewDidLoad values:", form.values(), "viewDidLoad task name", task?.name)
}

and output

viewDidLoad values: ["name": nil, "deadline": Optional(2017-06-08 19:02:39 +0000)] viewDidLoad task name nil
didSet values: [:] didSet task name Optional("ascasc")


问:
Getting data from IList inside child ViewModel
I am trying to iterate over a collection of child objects from my parent controller.

```<code> public class ListBlogsPageModel : IPageViewModel<ListBlogsPage>
 {
     public IList<BlogPage> BlogPages { get; set; }
 }
</code>```

BlogPages contain an index of BlogPage. This BlogPage model contains an IList of ProfilePage I want to iterate over in my parent controller.

```<code>public class BlogPageModel : IPageViewModel<BlogPage>
{
    public IList<ProfilePage> Profiles { get; set; }
}
</code>```

Now my question is how do I access this child Profiles model in the parent ListBlogsPage? I have tried getting Profiles the same way I am already getting BlogPage children (see below) but I seems to receive no values.

```<code>public ActionResult Index(ListBlogsPage currentPage)
{
    var model = new ListBlogsPageModel(currentPage);
    var blogPages = _contentLoader.GetChildren<BlogPage>(currentPage.ContentLink).ToList();
    var authorPages = _contentLoader.GetChildren<ProfilePage>(currentPage.ContentLink).ToList();
    var filteredPages = _contentFilterService.FilterForDisplay(blogPages, false, true).ToList();
    var filteredAuthors = _contentFilterService.FilterForDisplay(authorPages, false, true).ToList();
    model.BlogPages = filteredPages;
    model.AuthorPages = filteredAuthors;
    return View(model);
}
</code>```

答:
```<code>foreach (page in model.BlogPages)
{
    page.Profiles = something;
}
</code>```

I could be wrong, but it seems like you asked this.

Body:
I am trying to iterate over a collection of child objects from my parent controller.

 public class ListBlogsPageModel : IPageViewModel<ListBlogsPage>
 {
     public IList<BlogPage> BlogPages { get; set; }
 }

BlogPages contain an index of BlogPage. This BlogPage model contains an IList of ProfilePage I want to iterate over in my parent controller.

public class BlogPageModel : IPageViewModel<BlogPage>
{
    public IList<ProfilePage> Profiles { get; set; }
}

Now my question is how do I access this child Profiles model in the parent ListBlogsPage? I have tried getting Profiles the same way I am already getting BlogPage children (see below) but I seems to receive no values.

public ActionResult Index(ListBlogsPage currentPage)
{
    var model = new ListBlogsPageModel(currentPage);
    var blogPages = _contentLoader.GetChildren<BlogPage>(currentPage.ContentLink).ToList();
    var authorPages = _contentLoader.GetChildren<ProfilePage>(currentPage.ContentLink).ToList();
    var filteredPages = _contentFilterService.FilterForDisplay(blogPages, false, true).ToList();
    var filteredAuthors = _contentFilterService.FilterForDisplay(authorPages, false, true).ToList();
    model.BlogPages = filteredPages;
    model.AuthorPages = filteredAuthors;
    return View(model);
}

Body:
foreach (page in model.BlogPages)
{
    page.Profiles = something;
}

I could be wrong, but it seems like you asked this.


问:
HTML Table : Overflow-x scroll if no of columns are more
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="horizontal_scroll_div">
    <div class="scroll_table_div b">
      <div class="table_section">
      <div class="row m-l-none m-r-none " >
          <div class="col-sm-12 col-md-12 set_padding_0">
                <div class="table-responsive m-b-none no_border">
                <table class="table b-t b-b no-footer">
                  <thead class="bg-white">
                  <tr>
                    <th>column 1</th>
                    <th>column 2</th>
                    <th>column 3</th>
                    <th>column 4</th>
                    <th>column 5</th>
                    <th>column 6</th>
                    <th>column 7</th>
                    <th>column 8</th>
                    <th>column 9</th>
                    <th>column 10</th>
                    <th>column 11</th>
                    <th>column 12</th>

                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td>value 1</td>
                    <td>value 2</td>
                    <td>value 3</td>
                    <td>value 4</td>
                    <td>value 5</td>
                    <td>value 6</td>
                    <td>value 7</td>
                    <td>value 8</td>
                    <td>value 9</td>
                    <td>value 10</td>
                    <td>value 11</td>
                    <td>value 12</td>
                  </tr>
                  </tbody>
                  </table>
               </div>
          </div>
       </div>
  </div>
  </div>
  </div></code>```

Any help would be great.
Thank You.

答:
Try this </p>

```<code>overflow-x: auto !important;
</code>```

<p>inside div class </p>

```<code>.horizontal_scroll_div .scroll_table_div
</code>```

Body:
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                    column 1
                    column 2
                    column 3
                    column 4
                    column 5
                    column 6
                    column 7
                    column 8
                    column 9
                    column 10
                    column 11
                    column 12

                    value 1
                    value 2
                    value 3
                    value 4
                    value 5
                    value 6
                    value 7
                    value 8
                    value 9
                    value 10
                    value 11
                    value 12

Any help would be great.
Thank You.

Body:
Try this

overflow-x: auto !important;

inside div class

.horizontal_scroll_div .scroll_table_div


问:
Using vue-cli, components throw "Uncaught ReferenceError: Vue is not defined"
I installed vue-cli and made some components, and everything was working great until I had to update some object values with keys

```<code>obj = {
    key1: value1,
    key2: value2,
    key3: value3
};
</code>```

The data is updating, but the view isn't updating and when I dig into Vue documentation it says

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

The solution would be to use Vue.set() but when try that (inside my component) I get the following result:

```<code>Vue.set(example1.items, indexOfItem, newValue);
</code>```

Uncaught ReferenceError: Vue is not defined

答:
You forget the most important thing to introduce vue. The simplest, we can directly in the html file in the script tag to introduce vue, such as:

```<code><script src="https://cdn.bootcss.com/vue/2.3.3/vue.min.js" type="text/javascript" charset="utf-8"></script>
</code>```

In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.

vue-cli

If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!

Vue Demo

ContentLicense: CC BY-SA 4.0

Body:
I installed vue-cli and made some components, and everything was working great until I had to update some object values with keys

obj = {
    key1: value1,
    key2: value2,
    key3: value3
};

The data is updating, but the view isn't updating and when I dig into Vue documentation it says

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

The solution would be to use Vue.set() but when try that (inside my component) I get the following result:

Vue.set(example1.items, indexOfItem, newValue);

Uncaught ReferenceError: Vue is not defined

Body:
You forget the most important thing to introduce vue. The simplest, we can directly in the html file in the script tag to introduce vue, such as:

<script src="https://cdn.bootcss.com/vue/2.3.3/vue.min.js" type="text/javascript" charset="utf-8"></script>

In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.

vue-cli

If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!

Vue Demo


问:
Session variable in MVC with jQuery Ajax post
I am using ASP.Net MVC 5 to build a web application and using jQuery along with it. I have kind of a single page application where I use the index action set a session variable and display the view. Further I using jQuery to invoke Get and Post Ajax request to actions on the same controllers. The problem is in accessing the Sesssion variable. I am setting the session variable in the index action and trying to access the same variable in the post action invoked by jquery. Please suggest if there is something that I am missing.

My Controller class is something like below:

```<code>public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
        var obj = new SomeObject();
        Session["UserName"] = Request.QueryString["UserName"];

        return View(obj);
    }

    //Invoked by jQuery Ajax method..
    [HttpPost]
    [Route("home/GetResponse/")]
    public async Task<JsonResult> GetResponse(string message)
    {
        var userName = Convert.ToString(Session["UserName"]);// Getting Null
        //Perform some stuff and return json
    }
}
</code>```

答:
Session variable is constant in single page that means it will not change if page is not loaded or refreshed.
So in Success of Ajax submit you have to place the value of the session manually.
if @session["client_name"]

then

```<code>       success: function(data)
       {
           $("#demoid").html(data);  // here data is the value for the session
       }
</code>```

Body:
I am using ASP.Net MVC 5 to build a web application and using jQuery along with it. I have kind of a single page application where I use the index action set a session variable and display the view. Further I using jQuery to invoke Get and Post Ajax request to actions on the same controllers. The problem is in accessing the Sesssion variable. I am setting the session variable in the index action and trying to access the same variable in the post action invoked by jquery. Please suggest if there is something that I am missing.

My Controller class is something like below:

public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
        var obj = new SomeObject();
        Session["UserName"] = Request.QueryString["UserName"];

        return View(obj);
    }

    //Invoked by jQuery Ajax method..
    [HttpPost]
    [Route("home/GetResponse/")]
    public async Task<JsonResult> GetResponse(string message)
    {
        var userName = Convert.ToString(Session["UserName"]);// Getting Null
        //Perform some stuff and return json
    }
}

Body:
Session variable is constant in single page that means it will not change if page is not loaded or refreshed.
So in Success of Ajax submit you have to place the value of the session manually.
if <span id="demoid">@session["client_name"]</span>

then

       success: function(data)
       {
           $("#demoid").html(data);  // here data is the value for the session
       }


问:
Uncaught TypeError: $(...).datepicker is not a function(anonymous function)
I found few answers on stack overflow but still cant resolve my problem.
I am running on Django but I dont think it is relevant for this error.

I try to make work my date picker java script but I am getting the error

1:27 Uncaught TypeError: $(...).datepicker is not a function(anonymous function) @ 1:27fire @ jquery-1.9.1.js:1037self.fireWith @ jquery-1.9.1.js:1148jQuery.extend.ready @ jquery-1.9.1.js:433completed @ jquery-1.9.1.js:103
jquery-2.1.0.min.js:4 XHR finished loading: POST "https://localhost:26143/skypectoc/v1/pnr/parse".l.cors.a.crossDomain.send @ jquery-2.1.0.min.js:4o.extend.ajax @ jquery-2.1.0.min.js:4PNR.findNumbers @ pnr.js:43parseContent @ contentscript.js:385processMutatedElements @ contentscript.js:322

This is all my scripts :

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

```

any feedback will be very appreciated

答:
This error is occur,because the function is not defined.
In my case i have called the datepicker function without including the datepicker js file that time I got this error. </p>

Body:
I found few answers on stack overflow but still cant resolve my problem.
I am running on Django but I dont think it is relevant for this error.

I try to make work my date picker java script but I am getting the error

1:27 Uncaught TypeError: $(...).datepicker is not a function(anonymous function) @ 1:27fire @ jquery-1.9.1.js:1037self.fireWith @ jquery-1.9.1.js:1148jQuery.extend.ready @ jquery-1.9.1.js:433completed @ jquery-1.9.1.js:103
jquery-2.1.0.min.js:4 XHR finished loading: POST "https://localhost:26143/skypectoc/v1/pnr/parse".l.cors.a.crossDomain.send @ jquery-2.1.0.min.js:4o.extend.ajax @ jquery-2.1.0.min.js:4PNR.findNumbers @ pnr.js:43parseContent @ contentscript.js:385processMutatedElements @ contentscript.js:322

This is all my scripts :

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

any feedback will be very appreciated


问:
sidebar menu triangle pointer appears after click
I've created a simple sidebar nav menu here, as you can see - when clicking on the links - the rectangle/triangle remains....
Wonder how to fix it.... and why is it happening.

Here is how i got the pointer.

```<code>ul.faq_questions li.active:after, ul.faq_questions li:hover:after {
content: "";
position: absolute;
width: 10px;
height: 10px;
background:#5d3c95;
-webkit-transform: rotate(-45deg);
right: -5px;
top: 40%;
}
</code>```

答:
add this following code

css

```<code>ul.faq_questions li.active
{
  background-color: #5d3c95;
  color:#fff;
}

ul.faq_questions li.active:after, ul.faq_questions li:hover:after {
    content: "";
    position: absolute;
    width: 10px;
    height: 10px;
    background:#5d3c95;
    -webkit-transform: rotate(-45deg);
    right: -5px;
  top: 40%;
}
</code>```

hope this works..

or

remove

```<code>ul.faq_questions li.active:after
</code>```

from present code

Body:
I've created a simple sidebar nav menu here, as you can see - when clicking on the links - the rectangle/triangle remains....
Wonder how to fix it.... and why is it happening.

Here is how i got the pointer.

ul.faq_questions li.active:after, ul.faq_questions li:hover:after {
content: "";
position: absolute;
width: 10px;
height: 10px;
background:#5d3c95;
-webkit-transform: rotate(-45deg);
right: -5px;
top: 40%;
}

Body:
add this following code

css

ul.faq_questions li.active
{
  background-color: #5d3c95;
  color:#fff;
}

ul.faq_questions li.active:after, ul.faq_questions li:hover:after {
    content: "";
    position: absolute;
    width: 10px;
    height: 10px;
    background:#5d3c95;
    -webkit-transform: rotate(-45deg);
    right: -5px;
  top: 40%;
}

hope this works..

or

remove

ul.faq_questions li.active:after

from present code


问:
uwp adaptiveGridView throws exception on OneRowMode
I am having following exception on my adaptivegridview of uwp community toolkit

"System.ArgumentException: Value does not fall within the expected range.
   \r\n   at Windows.UI.Xaml.FrameworkElement.SetBinding(DependencyProperty dp, BindingBase binding)\r\n   at Microsoft.Toolkit.Uwp.UI.Controls.AdaptiveGridView.DetermineOneRowMode()\r\n   at Microsoft.Toolkit.Uwp.UI.Controls.AdaptiveGridView.OnLoaded(Object sender, RoutedEventArgs e)"

XAML

```<code><controls:AdaptiveGridView Name="AllVideosGridView"
                                           OneRowModeEnabled="True"
                                           MaxHeight="260"
                                           ScrollViewer.HorizontalScrollMode="Enabled"
                                           ScrollViewer.HorizontalScrollBarVisibility="Auto"
                                           ItemClick="AllVideosGridView_ItemClick"
                                           Style="{StaticResource MainGridView}"
    <...data template and other stuff...>
</controls.........>
</code>```

the error occurs due to property OneRowModeEnabled to True, and if I remove that property it works fine and after app runs and then I set this property to true, while app is running then it doesn't show any exception and gridview goes to one row mode as it should.

Also the code behind doesn't matter, because I tried to commend the code behind which initializes the itemsource, but this exception still occurs.

答:
The problem here is that you didn't set ItemHeight property in AdaptiveGridView.

Form the source code of AdaptiveGridView, you can find the following code (L155-L186):

```<code>private void OnLoaded(object sender, RoutedEventArgs e)
{
    _isLoaded = true;
    DetermineOneRowMode();
}

private void DetermineOneRowMode()
{
    if (_isLoaded)
    {
        var itemsWrapGridPanel = ItemsPanelRoot as ItemsWrapGrid;

        if (OneRowModeEnabled)
        {
            var b = new Binding()
            {
                Source = this,
                Path = new PropertyPath("ItemHeight")
            };

            if (itemsWrapGridPanel != null)
            {
                _savedOrientation = itemsWrapGridPanel.Orientation;
                itemsWrapGridPanel.Orientation = Orientation.Vertical;
            }

            SetBinding(MaxHeightProperty, b);
            ...
</code>```

When OneRowModeEnabled set to True, it will bind MaxHeightProperty to ItemHeight property. However, as you didn't set a value to ItemHeight property, its value will be NaN. That's why you got Value does not fall within the expected range. error.

To solve this problem, you can set ItemHeight property like the following:

```<code> <controls:AdaptiveGridView Name="AllVideosGridView"
                                   OneRowModeEnabled="True"
                                   DesiredWidth="260"
                                   ItemHeight="200"
                                   SelectionMode="None"
                                   StretchContentForSingleRow="False"
                                   IsItemClickEnabled="True"
                                   ItemsSource="{x:Bind ViewModel.Videos, Mode=OneWay}">
    ...
</controls:AdaptiveGridView>
</code>```

Body:
I am having following exception on my adaptivegridview of uwp community toolkit

"System.ArgumentException: Value does not fall within the expected range.
   \r\n   at Windows.UI.Xaml.FrameworkElement.SetBinding(DependencyProperty dp, BindingBase binding)\r\n   at Microsoft.Toolkit.Uwp.UI.Controls.AdaptiveGridView.DetermineOneRowMode()\r\n   at Microsoft.Toolkit.Uwp.UI.Controls.AdaptiveGridView.OnLoaded(Object sender, RoutedEventArgs e)"

XAML

<controls:AdaptiveGridView Name="AllVideosGridView"
                                           OneRowModeEnabled="True"
                                           MaxHeight="260"
                                           ScrollViewer.HorizontalScrollMode="Enabled"
                                           ScrollViewer.HorizontalScrollBarVisibility="Auto"
                                           ItemClick="AllVideosGridView_ItemClick"
                                           Style="{StaticResource MainGridView}"
    <...data template and other stuff...>
</controls.........>

the error occurs due to property OneRowModeEnabled to True, and if I remove that property it works fine and after app runs and then I set this property to true, while app is running then it doesn't show any exception and gridview goes to one row mode as it should.

Also the code behind doesn't matter, because I tried to commend the code behind which initializes the itemsource, but this exception still occurs.

Body:
The problem here is that you didn't set ItemHeight property in AdaptiveGridView.

Form the source code of AdaptiveGridView, you can find the following code (L155-L186):

private void OnLoaded(object sender, RoutedEventArgs e)
{
    _isLoaded = true;
    DetermineOneRowMode();
}

private void DetermineOneRowMode()
{
    if (_isLoaded)
    {
        var itemsWrapGridPanel = ItemsPanelRoot as ItemsWrapGrid;

        if (OneRowModeEnabled)
        {
            var b = new Binding()
            {
                Source = this,
                Path = new PropertyPath("ItemHeight")
            };

            if (itemsWrapGridPanel != null)
            {
                _savedOrientation = itemsWrapGridPanel.Orientation;
                itemsWrapGridPanel.Orientation = Orientation.Vertical;
            }

            SetBinding(MaxHeightProperty, b);
            ...

When OneRowModeEnabled set to True, it will bind MaxHeightProperty to ItemHeight property. However, as you didn't set a value to ItemHeight property, its value will be NaN. That's why you got Value does not fall within the expected range. error.

To solve this problem, you can set ItemHeight property like the following:

 <controls:AdaptiveGridView Name="AllVideosGridView"
                                   OneRowModeEnabled="True"
                                   DesiredWidth="260"
                                   ItemHeight="200"
                                   SelectionMode="None"
                                   StretchContentForSingleRow="False"
                                   IsItemClickEnabled="True"
                                   ItemsSource="{x:Bind ViewModel.Videos, Mode=OneWay}">
    ...
</controls:AdaptiveGridView>


问:
Visual Studio 2015 + Webpack generated bundles + Publish == missing files
When using Visual Studio 2015 & Webpack, Webpack generates a bundle like "[name].[chunkhash].js"

so this generated bundle will not be included in the solution, then when we publish the project this new bundle will not be published, because it is not included in the solution.

What is the best way to handle newly generated files outside of visual studio?

Am i forced to manually include this new file?

答:
To publish folder which are not "included" in the VS-Solution do:

. right click the solution -> unload project

. right click -> edit csproj file

. add following code

```<code><Content Include="FolderToInclude\**">
<Visible>false</Visible>
</Content>
</code>```

. save file, close it, right click solution -> reload project

now whenever you publish you code the folder will be published too, but remember that the folder will not be visible in your solution
ps. "false" is on purpose to hide it in the solution, so that the folder will be not altered by an user.

Body:
To publish folder which are not "included" in the VS-Solution do:

. right click the solution -> unload project

. right click -> edit csproj file

. add following code

<Content Include="FolderToInclude\**">
<Visible>false</Visible>
</Content>

. save file, close it, right click solution -> reload project

now whenever you publish you code the folder will be published too, but remember that the folder will not be visible in your solution
ps. "false" is on purpose to hide it in the solution, so that the folder will be not altered by an user.


问:
How do I position and size JLabels in Java?
I want to be able to position my two JLabels but when I change the values in the position lines it does nothing. Also when I run it only the second label is displayed.

My code:

```<code>import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class cubeTimerClass {

    public static void main(String[] args) {
        window(); //Runs the window method
    }

    public static void window() {
        //Create a window
                JFrame window = new JFrame(); //Create the window object
                window.setSize(900, 600); //Set the size of the window
                window.setTitle("Cube Timer"); //Set the title of the window
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the program to quit when user closes the window
                window.setVisible(true); //Make the window visible

                //Create a label
                JLabel label1 = new JLabel(""); //Create the label1 object
                label1.setText("Message 1"); //Set the text for label1
                label1.setAlignmentX(0);
                label1.setAlignmentY(0);
                window.add(label1); //Place the label on the window

                //Create a label
                JLabel label2 = new JLabel(""); //Create the label2 object
                label2.setText("Message 2"); //Set the text for label2
                label2.setAlignmentX(0);
                label2.setAlignmentY(50);
                window.add(label2); //Place the label on the window
    }
}
</code>```

答:
Check with this -</p>

```<code>JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = (JPanel) frame.getContentPane();
    panel.setLayout(null);

    JLabel label = new JLabel("Java");
    panel.add(label);
    Dimension size = label.getPreferredSize();
    label.setBounds(90, 100, size.width, size.height);

    frame.setSize(300, 200);
    frame.setVisible(true);
</code>```

Body:
I want to be able to position my two JLabels but when I change the values in the position lines it does nothing. Also when I run it only the second label is displayed.

My code:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class cubeTimerClass {

    public static void main(String[] args) {
        window(); //Runs the window method
    }

    public static void window() {
        //Create a window
                JFrame window = new JFrame(); //Create the window object
                window.setSize(900, 600); //Set the size of the window
                window.setTitle("Cube Timer"); //Set the title of the window
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the program to quit when user closes the window
                window.setVisible(true); //Make the window visible

                //Create a label
                JLabel label1 = new JLabel(""); //Create the label1 object
                label1.setText("Message 1"); //Set the text for label1
                label1.setAlignmentX(0);
                label1.setAlignmentY(0);
                window.add(label1); //Place the label on the window

                //Create a label
                JLabel label2 = new JLabel(""); //Create the label2 object
                label2.setText("Message 2"); //Set the text for label2
                label2.setAlignmentX(0);
                label2.setAlignmentY(50);
                window.add(label2); //Place the label on the window
    }
}

Body:
Check with this -

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = (JPanel) frame.getContentPane();
    panel.setLayout(null);

    JLabel label = new JLabel("Java");
    panel.add(label);
    Dimension size = label.getPreferredSize();
    label.setBounds(90, 100, size.width, size.height);

    frame.setSize(300, 200);
    frame.setVisible(true);


问:
TabHost.TabSpec layout that looks like the built-in layout
I have some icons of varying height, and the default tabspec layout on my HTC Legend places the icon at the top.

I wanted to center it by defining my own layout for the tabspec, but after many experiments with style & background, I still can't make it look like the built-in layout.

So I need the built-in Padding & background for my tabspec layout, anyone knows what they're called?

答:
Too much fiddling about - solved it by creating a fixed-height and variable width icon for the tab:

```<code>    private Drawable getTabIcon(byte chainID, Resources res) {
    BitmapDrawable chainIcon = (BitmapDrawable) res.getDrawable(ChainDisplay.getIconID(chainID));

    int tabIconHeight;
    switch(res.getDisplayMetrics().densityDpi) {
        case DisplayMetrics.DENSITY_LOW:
            tabIconHeight = 24;
            break;
        case DisplayMetrics.DENSITY_MEDIUM:
            tabIconHeight = 32;
            break;
        case DisplayMetrics.DENSITY_HIGH:
            tabIconHeight = 48;
            break;
        default:
            tabIconHeight = 48;
            break;
    }

    Bitmap tabIconBitmap = Bitmap.createBitmap(chainIcon.getIntrinsicWidth(), tabIconHeight, Bitmap.Config.ARGB_8888);
    new Canvas(tabIconBitmap).drawBitmap(chainIcon.getBitmap(), 0, (tabIconHeight - chainIcon.getIntrinsicHeight())/2, null);
    return new BitmapDrawable(tabIconBitmap);
}
</code>```

Did some experimenting with scaling and Paint.ANTI_ALIAS_FLAG, but it was ugly, so image cropping was selected.

ContentLicense: CC BY-SA 2.5

Body:
Too much fiddling about - solved it by creating a fixed-height and variable width icon for the tab:

    private Drawable getTabIcon(byte chainID, Resources res) {
    BitmapDrawable chainIcon = (BitmapDrawable) res.getDrawable(ChainDisplay.getIconID(chainID));

    int tabIconHeight;
    switch(res.getDisplayMetrics().densityDpi) {
        case DisplayMetrics.DENSITY_LOW:
            tabIconHeight = 24;
            break;
        case DisplayMetrics.DENSITY_MEDIUM:
            tabIconHeight = 32;
            break;
        case DisplayMetrics.DENSITY_HIGH:
            tabIconHeight = 48;
            break;
        default:
            tabIconHeight = 48;
            break;
    }

    Bitmap tabIconBitmap = Bitmap.createBitmap(chainIcon.getIntrinsicWidth(), tabIconHeight, Bitmap.Config.ARGB_8888);
    new Canvas(tabIconBitmap).drawBitmap(chainIcon.getBitmap(), 0, (tabIconHeight - chainIcon.getIntrinsicHeight())/2, null);
    return new BitmapDrawable(tabIconBitmap);
}

Did some experimenting with scaling and Paint.ANTI_ALIAS_FLAG, but it was ugly, so image cropping was selected.


问:
RobotFramework: Executing a unix command locally
I know that the below examples can be used on a remote machine. But how would i do same locally

```<code>Execute Command   rm -rf ${processed_path}
Execute Command   rm -rf ${failed_path}
Execute Command   rm -rf ${files_to_process_path}
Execute Command   mkdir ${processed_path}
Execute Command   mkdir ${failed_path}
</code>```

Especially for getting back return codes etc?

答:
Use the OperatingSystem library. For example the Run And Return RC keyword.

See the documentation here.

Body:
I know that the below examples can be used on a remote machine. But how would i do same locally

Execute Command   rm -rf ${processed_path}
Execute Command   rm -rf ${failed_path}
Execute Command   rm -rf ${files_to_process_path}
Execute Command   mkdir ${processed_path}
Execute Command   mkdir ${failed_path}

Especially for getting back return codes etc?


问:
Display XML in jsp file using Spring MVC
I need to display an XML file in jsp. The code should go to a particular location and read xml and then show it in a jsp.

I have done the file reading part but when I try to show that in jsp I am getting error. I tried different ways, like escaping char, setting content type, but every time I get a different error.

One of them is -

XML Parsing Error: no element found Location:

http://localhost:8080/viewXmlFile

Line Number 8, Column 12:

Is there any way I can show the XML file in jsp? I am using Spring MVC.

```<code>@RequestMapping(value = "/viewXmlFile", method = RequestMethod.GET)
public ModelAndView viewXmlFile(HttpServletRequest request, HttpServletResponse response) {
    String path = //sec15/folder/myXmlFile.xml;

    StringBuffer data = new StringBuffer();
    try(BufferedReader reader = Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8);) {
        List<String> collect = reader.lines().collect(Collectors.toList());

        for (String line : collect) {
            data.append(line + CommonConstants.FILE_NEXT_LINE);
        }
    } catch (Exception e) {
    }

    ModelAndView model = new ModelAndView("viewXmlFile");
    model.addObject("xmlData", data.toString());
    return model;
}
</code>```

This is the JSP file-

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
```
    <c:out value="${xmlData}" />
```
</body>
</html>
</code>```

This is the XML, I am trying to show-

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns14:Appearance xmlns:ns2="http://www.example.com/ObjectMetadata/9.0" xmlns:ns3="http://www.example.com/TransactionMetadata/9.0" xmlns:ns14="http://www.example.com/Appearance/2.56">
    <ns3:TransactionMetadata>
        <SourceSystem>Alpha</SourceSystem>
        <TransactionType>Appearance</TransactionType>
        <UniqueTransactionId>8d797d156487</UniqueTransactionId>
        <TransactionDateTime>2017-05-23T03:04:48.025+02:00</TransactionDateTime>
    </ns3:TransactionMetadata>
    <Appearance>
        <ns2:ObjectMetadata>
            <ActionType>Update</ActionType>
            <BusinessObjectName>Appearance</BusinessObjectName>
        </ns2:ObjectMetadata>
        <AppearanceUID>A500003410</AppearanceUID>
        <AppearanceNumber>001</AppearanceNumber>
        <AppearanceName>1495501</AppearanceName>
        <CreationDate>2017-05-23T03:04:37+02:00</CreationDate>
        <ModifiedDate>2017-05-23T03:04:38+02:00</ModifiedDate>
    </Appearance>
</ns14:Appearance>
</code>```

答:
After changing the jsp file I am able to view the XML on jsp.

This is the code I have in jsp now-

```<code><%@page contentType="text/xml" pageEncoding="UTF-8"%>${xmlData}
</code>```

Body:
I need to display an XML file in jsp. The code should go to a particular location and read xml and then show it in a jsp.

I have done the file reading part but when I try to show that in jsp I am getting error. I tried different ways, like escaping char, setting content type, but every time I get a different error.

One of them is -

XML Parsing Error: no element found Location:

http://localhost:8080/viewXmlFile

Line Number 8, Column 12:

Is there any way I can show the XML file in jsp? I am using Spring MVC.

@RequestMapping(value = "/viewXmlFile", method = RequestMethod.GET)
public ModelAndView viewXmlFile(HttpServletRequest request, HttpServletResponse response) {
    String path = //sec15/folder/myXmlFile.xml;

    StringBuffer data = new StringBuffer();
    try(BufferedReader reader = Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8);) {
        List<String> collect = reader.lines().collect(Collectors.toList());

        for (String line : collect) {
            data.append(line + CommonConstants.FILE_NEXT_LINE);
        }
    } catch (Exception e) {
    }

    ModelAndView model = new ModelAndView("viewXmlFile");
    model.addObject("xmlData", data.toString());
    return model;
}

This is the JSP file-

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <c:out value="${xmlData}" />

This is the XML, I am trying to show-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns14:Appearance xmlns:ns2="http://www.example.com/ObjectMetadata/9.0" xmlns:ns3="http://www.example.com/TransactionMetadata/9.0" xmlns:ns14="http://www.example.com/Appearance/2.56">
    <ns3:TransactionMetadata>
        <SourceSystem>Alpha</SourceSystem>
        <TransactionType>Appearance</TransactionType>
        <UniqueTransactionId>8d797d156487</UniqueTransactionId>
        <TransactionDateTime>2017-05-23T03:04:48.025+02:00</TransactionDateTime>
    </ns3:TransactionMetadata>
    <Appearance>
        <ns2:ObjectMetadata>
            <ActionType>Update</ActionType>
            <BusinessObjectName>Appearance</BusinessObjectName>
        </ns2:ObjectMetadata>
        <AppearanceUID>A500003410</AppearanceUID>
        <AppearanceNumber>001</AppearanceNumber>
        <AppearanceName>1495501</AppearanceName>
        <CreationDate>2017-05-23T03:04:37+02:00</CreationDate>
        <ModifiedDate>2017-05-23T03:04:38+02:00</ModifiedDate>
    </Appearance>
</ns14:Appearance>

Body:
After changing the jsp file I am able to view the XML on jsp.

This is the code I have in jsp now-

<%@page contentType="text/xml" pageEncoding="UTF-8"%>${xmlData}


问:
#include <QtWidgets> not working in Qt 5.5 with ros kinetic ubuntu 16.06
I have a ros-project that builds fine under ros-indigo on ubuntu 14.04
now I switched to ros-kinetic and to ubuntu 16.04 and I got the following error when building my code:

Errors     << rviz_satellite:make
  /home/kohaf3/opel_ws/logs/rviz_satellite/build.make.028.log        In
  file included from
  /home/kohaf3/opel_ws/build/rviz_satellite/src/moc_aerialmap_display.cpp:9:0:
  /home/kohaf3/opel_ws/build/rviz_satellite/src/../../../src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]: *
  [CMakeFiles/rviz_satellite.dir/src/moc_aerialmap_display.cpp.o] Error
  1 make[2]:  Waiting for unfinished jobs.... In file included from
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.cpp:45:0:
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]:
  [CMakeFiles/rviz_satellite.dir/src/aerialmap_display.cpp.o] Error 1
  make[1]: * [CMakeFiles/rviz_satellite.dir/all] Error 2 make: ***
  [all] Error 2

My CMakeLists file is as follows:

```<code>cmake_minimum_required(VERSION 2.8.3)
project(rviz_satellite)

set(DISTRO $ENV{ROS_DISTRO})
message("Distribution: " ${DISTRO})

set(DEFAULT_BUILD_QT5 OFF)
if(${DISTRO} STREQUAL "kinetic")
    set(DEFAULT_BUILD_QT5 ON)
endif()

option(UseQt5 "Build w/ QT version 5" ${DEFAULT_BUILD_QT5})

if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()

find_package(OpenCV REQUIRED)
find_package(PkgConfig REQUIRED)

pkg_check_modules(OGRE_OV OGRE OGRE-Overlay)

# Old versions of OGRE (pre 1.9) included OGRE-Overlay in the main package
# (i.e. there was no OGRE-Overlay component).  So if the above
# pkg_check_modules() failed, try looking for just OGRE.
if(NOT OGRE_OV_FOUND)
  pkg_check_modules(OGRE_OV REQUIRED OGRE)
endif()

find_package(catkin REQUIRED COMPONENTS
  nav_msgs
  roscpp
  rviz
  sensor_msgs
  geodesy
  rtkrcv_ros_tool# wichtig für include:#include <rtkrcv_ros_tool/GPS_rtklib.h>
)

#generate_messages(
 # DEPENDENCIES
 # std_msgs
#)

catkin_package(CATKIN_DEPENDS nav_msgs sensor_msgs )#message_runtime)

set(${PROJECT_NAME}_SOURCES
  src/aerialmap_display.cpp
  src/tileloader.cpp
  src/rviz_plot_markers.cpp
)

set(${PROJECT_NAME}_HEADERS
  src/aerialmap_display.h
  src/tileloader.h
)

# invoke MOC and UI/ include Qt headers/ link Qt libraries
if (UseQt5)
    qt5_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(
        ${Qt5Core_INCLUDE_DIRS}
        ${Qt5Gui_INCLUDE_DIRS}
        ${Qt5Network_INCLUDE_DIRS}
        ${Qt5Concurrent_INCLUDE_DIRS}
                "/usr/include/qt5"
        )
    link_libraries(
        ${Qt5Core_LIBRARIES}
        ${Qt5Gui_LIBRARIES}
        ${Qt5Network_LIBRARIES}
        ${Qt5Concurrent_LIBRARIES}
        )
else()
    qt4_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(${Qt4_INCLUDE_DIR})
    link_libraries(
        ${QT_LIBRARIES}
        )
endif()

# Other includes
include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
  ${OpenCV_INCLUDE_DIR}
  ${OGRE_OV_INCLUDE_DIRS}
  ${catkin_INCLUDE_DIRS}
  src
)

# Other libraries
link_libraries(
  ${QT_LIBRARIES}
  ${OpenCV_LIBRARIES}
  ${catkin_LIBRARIES}
)

add_definitions("-Wall -Wunused -std=c++11")

set(PROJECT_SOURCE_FILES
  ${${PROJECT_NAME}_SOURCES}
  ${${PROJECT_NAME}_MOCSrcs}
)

add_library(${PROJECT_NAME}
  ${PROJECT_SOURCE_FILES}
)

install(TARGETS ${PROJECT_NAME}
    RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)

install(FILES plugin_description.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})

# von Markus:
add_executable(rviz_node
    src/rviz_plot_markers.cpp)
add_dependencies(rviz_node ${catkin_EXPORTED_TARGETS})
target_link_libraries(rviz_node
  ${catkin_LIBRARIES}
)
</code>```

qmake --version

```<code>QMake version 3.0
Using Qt version 5.5.1 in /usr/lib/x86_64-linux-gnu
</code>```

pkg-config --modversion QtCore

```<code>4.8.7
</code>```

qtdiag

```<code>Library info:   PrefixPath: /usr   DocumentationPath: /usr/share/qt5/doc
HeadersPath: /usr/include/x86_64-linux-gnu/qt5   LibrariesPath: /usr/lib
/x86_64-linux-gnu   LibraryExecutablesPath: /usr/lib/x86_64-linux-gnu/qt5
/libexec   BinariesPath: /usr/lib/x86_64-linux-gnu/qt5/bin   PluginsPath:
/usr/lib/x86_64-linux-gnu/qt5/plugins   ImportsPath: /usr/lib/x86_64-
linux-gnu/qt5/imports   Qml2ImportsPath: /usr/lib/x86_64-linux-gnu/qt5/qml
ArchDataPath: /usr/lib/x86_64-linux-gnu/qt5   DataPath: /usr/share/qt5
TranslationsPath: /usr/share/qt5/translations   ExamplesPath: /usr/lib
/x86_64-linux-gnu/qt5/examples   TestsPath: /usr/tests
SettingsPath: /etc/xdg
</code>```

I also installed Qt creator ros plugin see here (https://github.com/ros-industrial/ros_qtc_plugin/wiki/1.-How-to-Install-(Users) )

答:
I think you must also include the Widgets/QtWidgets module from Qt within your CMake:</p>

```<code>if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent Widgets REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork QtWidgets REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()
</code>```

Body:
I have a ros-project that builds fine under ros-indigo on ubuntu 14.04
now I switched to ros-kinetic and to ubuntu 16.04 and I got the following error when building my code:

Errors     << rviz_satellite:make
  /home/kohaf3/opel_ws/logs/rviz_satellite/build.make.028.log        In
  file included from
  /home/kohaf3/opel_ws/build/rviz_satellite/src/moc_aerialmap_display.cpp:9:0:
  /home/kohaf3/opel_ws/build/rviz_satellite/src/../../../src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]: *
  [CMakeFiles/rviz_satellite.dir/src/moc_aerialmap_display.cpp.o] Error
  1 make[2]:  Waiting for unfinished jobs.... In file included from
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.cpp:45:0:
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]:
  [CMakeFiles/rviz_satellite.dir/src/aerialmap_display.cpp.o] Error 1
  make[1]: * [CMakeFiles/rviz_satellite.dir/all] Error 2 make: ***
  [all] Error 2

My CMakeLists file is as follows:

cmake_minimum_required(VERSION 2.8.3)
project(rviz_satellite)

set(DISTRO $ENV{ROS_DISTRO})
message("Distribution: " ${DISTRO})

set(DEFAULT_BUILD_QT5 OFF)
if(${DISTRO} STREQUAL "kinetic")
    set(DEFAULT_BUILD_QT5 ON)
endif()

option(UseQt5 "Build w/ QT version 5" ${DEFAULT_BUILD_QT5})

if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()

find_package(OpenCV REQUIRED)
find_package(PkgConfig REQUIRED)

pkg_check_modules(OGRE_OV OGRE OGRE-Overlay)

# Old versions of OGRE (pre 1.9) included OGRE-Overlay in the main package
# (i.e. there was no OGRE-Overlay component).  So if the above
# pkg_check_modules() failed, try looking for just OGRE.
if(NOT OGRE_OV_FOUND)
  pkg_check_modules(OGRE_OV REQUIRED OGRE)
endif()

find_package(catkin REQUIRED COMPONENTS
  nav_msgs
  roscpp
  rviz
  sensor_msgs
  geodesy
  rtkrcv_ros_tool# wichtig für include:#include <rtkrcv_ros_tool/GPS_rtklib.h>
)

#generate_messages(
 # DEPENDENCIES
 # std_msgs
#)

catkin_package(CATKIN_DEPENDS nav_msgs sensor_msgs )#message_runtime)

set(${PROJECT_NAME}_SOURCES
  src/aerialmap_display.cpp
  src/tileloader.cpp
  src/rviz_plot_markers.cpp
)

set(${PROJECT_NAME}_HEADERS
  src/aerialmap_display.h
  src/tileloader.h
)

# invoke MOC and UI/ include Qt headers/ link Qt libraries
if (UseQt5)
    qt5_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(
        ${Qt5Core_INCLUDE_DIRS}
        ${Qt5Gui_INCLUDE_DIRS}
        ${Qt5Network_INCLUDE_DIRS}
        ${Qt5Concurrent_INCLUDE_DIRS}
                "/usr/include/qt5"
        )
    link_libraries(
        ${Qt5Core_LIBRARIES}
        ${Qt5Gui_LIBRARIES}
        ${Qt5Network_LIBRARIES}
        ${Qt5Concurrent_LIBRARIES}
        )
else()
    qt4_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(${Qt4_INCLUDE_DIR})
    link_libraries(
        ${QT_LIBRARIES}
        )
endif()

# Other includes
include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
  ${OpenCV_INCLUDE_DIR}
  ${OGRE_OV_INCLUDE_DIRS}
  ${catkin_INCLUDE_DIRS}
  src
)

# Other libraries
link_libraries(
  ${QT_LIBRARIES}
  ${OpenCV_LIBRARIES}
  ${catkin_LIBRARIES}
)

add_definitions("-Wall -Wunused -std=c++11")

set(PROJECT_SOURCE_FILES
  ${${PROJECT_NAME}_SOURCES}
  ${${PROJECT_NAME}_MOCSrcs}
)

add_library(${PROJECT_NAME}
  ${PROJECT_SOURCE_FILES}
)

install(TARGETS ${PROJECT_NAME}
    RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)

install(FILES plugin_description.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})

# von Markus:
add_executable(rviz_node
    src/rviz_plot_markers.cpp)
add_dependencies(rviz_node ${catkin_EXPORTED_TARGETS})
target_link_libraries(rviz_node
  ${catkin_LIBRARIES}
)

qmake --version

QMake version 3.0
Using Qt version 5.5.1 in /usr/lib/x86_64-linux-gnu

pkg-config --modversion QtCore

4.8.7

qtdiag

Library info:   PrefixPath: /usr   DocumentationPath: /usr/share/qt5/doc
HeadersPath: /usr/include/x86_64-linux-gnu/qt5   LibrariesPath: /usr/lib
/x86_64-linux-gnu   LibraryExecutablesPath: /usr/lib/x86_64-linux-gnu/qt5
/libexec   BinariesPath: /usr/lib/x86_64-linux-gnu/qt5/bin   PluginsPath:
/usr/lib/x86_64-linux-gnu/qt5/plugins   ImportsPath: /usr/lib/x86_64-
linux-gnu/qt5/imports   Qml2ImportsPath: /usr/lib/x86_64-linux-gnu/qt5/qml
ArchDataPath: /usr/lib/x86_64-linux-gnu/qt5   DataPath: /usr/share/qt5
TranslationsPath: /usr/share/qt5/translations   ExamplesPath: /usr/lib
/x86_64-linux-gnu/qt5/examples   TestsPath: /usr/tests
SettingsPath: /etc/xdg

I also installed Qt creator ros plugin see here (https://github.com/ros-industrial/ros_qtc_plugin/wiki/1.-How-to-Install-(Users) )

Body:
I think you must also include the Widgets/QtWidgets module from Qt within your CMake:

if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent Widgets REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork QtWidgets REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()


问:
I can't migrate the database of my Rails app on Heroku with sqlite
I'm following this tutorial on creating Ruby on Rail apps, and I've hit a roadblock. I am trying to migrate its database to Heroku, only to be told this:

```<code>c:\Sites\railsbridge\test_app>heroku run rails db:migrate
Running rails db:migrate on floating-ocean-40882... up, run.5709 (Free)
rails aborted!
Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not
loaded. Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the
minimum required by ActiveRecord).
</code>```

I already have sqlite3 listed in my Gemfile, what am I doing wrong?

答: Heroku doesn't support SQLite it only support PostgresSQL here is full documentation for deployment on Heroku

Body:
I'm following this tutorial on creating Ruby on Rail apps, and I've hit a roadblock. I am trying to migrate its database to Heroku, only to be told this:

c:\Sites\railsbridge\test_app>heroku run rails db:migrate
Running rails db:migrate on floating-ocean-40882... up, run.5709 (Free)
rails aborted!
Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not
loaded. Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the
minimum required by ActiveRecord).

I already have sqlite3 listed in my Gemfile, what am I doing wrong?


问:
how to fetch contact image and phone Number in my app using Objective C
I am getting the contact name from my phone.
Check my code:

```<code>- (void) fetchContacts
{
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];

        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:TRUE completion:nil];
        return;
    }

    CNContactStore *store = [[CNContactStore alloc] init];    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        // make sure the user granted us access

        if (!granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // user didn't grant access;
                // so, again, tell user here why app needs permissions in order  to do it's job;
                // this is dispatched to the main queue because this request could be running on background thread
            });
            return;
        }

        // build array of contacts

        NSMutableArray *contacts = [NSMutableArray array];

        NSError *fetchError;
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

        BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
            [contacts addObject:contact];
        }];

        if (!success) {
            NSLog(@"error = %@", fetchError);
        }

        // you can now do something with the list of contacts, for example, to show the names

        CNContactFormatter *formatter = [[CNContactFormatter alloc] init];

        for (CNContact *contact in contacts) {
            if (!_contacts) {
                _contacts = [[NSMutableArray alloc] init];
            }

            NSString *string = [formatter stringFromContact:contact];
            NSLog(@"contact = %@", string);
            [_contacts addObject:string];
        }
        [_contactatableview reloadData];

    }];
}
</code>```

for this code, I am getting the response

```<code>2015-12-28 15:18:13.867 finalprototype[2138:66648] contact = John Appleseed
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Kate Bell
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Anna Haro
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Daniel Higgins Jr.
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = David Taylor
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Hank M. Zakroff
</code>```

my requirement is I need to display the image and phone number of a particular contact in my app contacts page.

So is this possible in iOS 9?

give me suggestions

Thank you.

答:
```<code>+ (UIImage *)getImageForContactIdentifier:(NSString *)contactIdentifer
{
     NSError *error;
     NSArray *keysToFetch = @[CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey];

     CNContact *contact = [[NWContactManager sharedManger].contactStore unifiedContactWithIdentifier:contactIdentifer keysToFetch:keysToFetch error:&error];

     UIImage *image;
     if (contact.imageDataAvailable) {
          image = [UIImage imageWithData:contact.thumbnailImageData];
     }
        return image;
    }

//For iOS8 or below, Use Following code

+ (UIImage *)getImageForContactIdentifier:(NSNumber *)contactIdentifer
{
    CFErrorRef error = NULL;
    ABRecordID recId = (ABRecordID)[contactIdentifer intValue];
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABRecordRef contactPerson = ABAddressBookGetPersonWithRecordID(addressBook, recId);

    UIImage *image;
    CFDataRef imageData = ABPersonCopyImageData(contactPerson);
    if (imageData) {
        image = [UIImage imageWithData:(__bridge NSData *)imageData];
    }
    return image;
}
</code>```

Body:
I am getting the contact name from my phone.
Check my code:

- (void) fetchContacts
{
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];

        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:TRUE completion:nil];
        return;
    }

    CNContactStore *store = [[CNContactStore alloc] init];    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        // make sure the user granted us access

        if (!granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // user didn't grant access;
                // so, again, tell user here why app needs permissions in order  to do it's job;
                // this is dispatched to the main queue because this request could be running on background thread
            });
            return;
        }

        // build array of contacts

        NSMutableArray *contacts = [NSMutableArray array];

        NSError *fetchError;
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

        BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
            [contacts addObject:contact];
        }];

        if (!success) {
            NSLog(@"error = %@", fetchError);
        }

        // you can now do something with the list of contacts, for example, to show the names

        CNContactFormatter *formatter = [[CNContactFormatter alloc] init];

        for (CNContact *contact in contacts) {
            if (!_contacts) {
                _contacts = [[NSMutableArray alloc] init];
            }

            NSString *string = [formatter stringFromContact:contact];
            NSLog(@"contact = %@", string);
            [_contacts addObject:string];
        }
        [_contactatableview reloadData];

    }];
}

for this code, I am getting the response

2015-12-28 15:18:13.867 finalprototype[2138:66648] contact = John Appleseed
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Kate Bell
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Anna Haro
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Daniel Higgins Jr.
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = David Taylor
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Hank M. Zakroff

my requirement is I need to display the image and phone number of a particular contact in my app contacts page.

So is this possible in iOS 9?

give me suggestions

Thank you.


问:
pyLucene Installation
I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene.

Here's what I have done so far, installed these packages -

```<code>sudo apt-get install ant
sudo apt-get install sun-java6-jdk
sudo update-java-alternatives -s java-1.5.0-sun
sudo apt-get install gcc
sudo apt-get install g++
sudo apt-get install gcj
sudo apt-get install python-dev
</code>```

After that got the source code of pyLucene from http://www.apache.org/dyn/closer.cgi/lucene/pylucene/. I got version pylucene-3.0.1-1.

Untared it. Since JCC needs to be built first; went to JCC dir & then typed python setup.py install. got an error about some setuptools patch. it told me to do this -
sudo patch -d /usr/lib/python2.6/dist-packages -Nup0 < /home/code/python/lucene/pylucene-3.0.1-1/jcc/jcc/patches/patch.43.0.6c11

and I did. but I got this on the terminal -

```<code>patching file setuptools/extension.py
patching file setuptools/command/build_ext.py
Hunk #1 FAILED at 85.
Hunk #2 succeeded at 177 (offset 7 lines).
Hunk #3 succeeded at 259 (offset 7 lines).
1 out of 3 hunks FAILED -- saving rejects to file setuptools/command/build_ext.py.rej
</code>```

Now my build fails - i.e. when I do sudo python setup.py build I get -

```<code>...
error: command 'gcc' failed with exit status 1
</code>```

答:
I think the problem may be that the patch is for setuptools 0.6-11 and you have an earlier version of setuptools (prob 0.6-10) installed from your distro's packages.

I have had a similar problem that was resolved by removing the version of setuptools installed by the distro and installing your own downloaded from http://pypi.python.org/pypi/setuptools

I have had no problems yet, but there is a very small chance that this will interfere with some other programs on your system.

OwnerDisplayName: Inception

Title: pyLucene Installation

Body:
I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene.

Here's what I have done so far, installed these packages -

sudo apt-get install ant
sudo apt-get install sun-java6-jdk
sudo update-java-alternatives -s java-1.5.0-sun
sudo apt-get install gcc
sudo apt-get install g++
sudo apt-get install gcj
sudo apt-get install python-dev

After that got the source code of pyLucene from http://www.apache.org/dyn/closer.cgi/lucene/pylucene/. I got version pylucene-3.0.1-1.

Untared it. Since JCC needs to be built first; went to JCC dir & then typed python setup.py install. got an error about some setuptools patch. it told me to do this -
sudo patch -d /usr/lib/python2.6/dist-packages -Nup0 < /home/code/python/lucene/pylucene-3.0.1-1/jcc/jcc/patches/patch.43.0.6c11

and I did. but I got this on the terminal -

patching file setuptools/extension.py
patching file setuptools/command/build_ext.py
Hunk #1 FAILED at 85.
Hunk #2 succeeded at 177 (offset 7 lines).
Hunk #3 succeeded at 259 (offset 7 lines).
1 out of 3 hunks FAILED -- saving rejects to file setuptools/command/build_ext.py.rej

Now my build fails - i.e. when I do sudo python setup.py build I get -

...
error: command 'gcc' failed with exit status 1


问:
How do I parse the fields in a comma separated list and convert them to Integer
I have the following:

```<code>char *strings = "1998,9,20,"
</code>```

Here I want to store each number into an integer varaible and print as :

1998

9

20

I tried using strtok and then atoi but this did not help me as my variable is a character pointer and not an array.

答:
with <regex> library:

and regex_token_iterator as splitter:

```<code>unsigned int some_int[ 5 ]{};

const char* string = "1998,9,20,";

const char* begin_s = string;
const char* end___s = string + std::string( string ).size();

std::regex regex( "," );

std::regex_token_iterator< const char* > first( begin_s, end___s, regex, -1 ), last;

unsigned int index = 0;

while( first != last ){
    some_int[ index++ ] = std::stoi( *first++ );
}

for( unsigned int item : some_int ){
    std::cout << item << '\n';
}
</code>```

the output:

```<code>1998
9
20
0
0
</code>```

Body:
I have the following:

char *strings = "1998,9,20,"

Here I want to store each number into an integer varaible and print as :

1998

9

20

I tried using strtok and then atoi but this did not help me as my variable is a character pointer and not an array.

Body:
with <regex> library:

and regex_token_iterator as splitter:

unsigned int some_int[ 5 ]{};

const char* string = "1998,9,20,";

const char* begin_s = string;
const char* end___s = string + std::string( string ).size();

std::regex regex( "," );

std::regex_token_iterator< const char* > first( begin_s, end___s, regex, -1 ), last;

unsigned int index = 0;

while( first != last ){
    some_int[ index++ ] = std::stoi( *first++ );
}

for( unsigned int item : some_int ){
    std::cout << item << '\n';
}

the output:

1998
9
20
0
0


问:
Is there a way to simplify OpenCl kernels usage ?
To use OpenCL kernel the following is needed:

Put the kernel code in a string

call clCreateProgramWithSource

call clBuildProgram

call clCreateKernel

call clSetKernelArg (x number of arguments)

call clEnqueueNDRangeKernel

This need to be done for each kernel. Is there a way to do this repeating less code for each kernel?

答: I suggest you look into SYCL. The building steps are performed offline, saving execution time by skipping the clCreateProgramWithSource. The argument setting is done automatically by the runtime, extracting the information from the user lambda</p>


问:
Polarion Web services API - How to create a project?
Looking at the list of available polarion webservices wsdl api functions,  I don't see one for creating a polarion project.  I have had no luck in finding out how I can create a polarion project via scripting to the polarion soap (wsdl) API.   </p>

答:
It is not possible.

I was looking through the (in my opinion) three relevant classes when it comes to using the API and I could not find a createProject method.

The three relevant classes are:

http://almdemo.polarion.com/polarion/sdk/doc/javadoc/com/polarion/alm/ws/client/projects/ProjectWebService.html

http://almdemo.polarion.com/polarion/sdk/doc/javadoc/com/polarion/alm/ws/client/session/SessionWebService.html

http://almdemo.polarion.com/polarion/sdk/doc/javadoc/com/polarion/alm/ws/client/tracker/TrackerWebService.html

There is a createProject method however in the following interface
but importing that did also not work. It is not part of ws/client so I think the method is only ment to be implemented in Polarion Wikipages with Velocity Code.
http://almdemo.polarion.com/polarion/sdk/doc/javadoc/com/polarion/alm/projects/IProjectLifecycleManager.html


问:
WordPress front page display issues
I've developed my theme locally and I have the Reading Settings > Front page displays > Front page displays > Your latest posts.

This would then mean the template file would be home.php and this all works fine on my local machine. Though when I push this to my live site and have the same settings the front-page.php file is being displayed even though I deleted it and cleared my cache.

You can view the site here: www.eatsleepkayak.com

The home page should be displaying a blog feed not the current quotes landing page.

Im not sure why this is happening and how to resolve it.

答:
After move live Permalink re-save.
Note: .htaccess should be writable.

or create template file and assign to any other page. Use this page as front page.

Title: WordPress front page display issues


问:
Find out if Delphi ClassType inherits from other ClassType?
In Delphi, given the following:

```<code>TFruit = class;
TFruitClass = class of TFruit;

TApple = class(TFruit);

TRedApple = class(TApple);
</code>```

If I have a TFruitClass variable, how can I find out if it inherits from TApple? E.g. say I have

```<code>var
  FruitClass: TFruitClass;
...
FruitClass := TRedApple;
</code>```

How can I verify that FruitClass does indeed inherit from TApple in this case? Using FruitClass is TApple only works for class instances.

答:
Use InheritsFrom:

```<code>if TApple.InheritsFrom(TFruit) then
  ...
</code>```

You can also use

```<code>var
  Fr: TFruitClass;
  X: TObject;
begin
  if X.InheritsFrom(TFruit) then
    Fr := TFruitClass(X.ClassType);
end;
</code>```

Body:
In Delphi, given the following:

TFruit = class;
TFruitClass = class of TFruit;

TApple = class(TFruit);

TRedApple = class(TApple);

If I have a TFruitClass variable, how can I find out if it inherits from TApple? E.g. say I have

var
  FruitClass: TFruitClass;
...
FruitClass := TRedApple;

How can I verify that FruitClass does indeed inherit from TApple in this case? Using FruitClass is TApple only works for class instances.

Body:
Use InheritsFrom:

if TApple.InheritsFrom(TFruit) then
  ...

You can also use

var
  Fr: TFruitClass;
  X: TObject;
begin
  if X.InheritsFrom(TFruit) then
    Fr := TFruitClass(X.ClassType);
end;