Пример #1
0
 def update_node_data(self,
                      child_node: QTreeWidgetItem,
                      item: Union[JenkinsJob, JenkinsFolder]):
     icon = "job.png" if isinstance(item, JenkinsJob) else "folder.png"
     child_node.setText(0, item.name)
     child_node.setIcon(0, get_icon(icon))
     child_node.setCheckState(0, as_qt_selection(item.selected))
Пример #2
0
 def add_dir(self, dir_path, parent):
     sorted_list = sorted(self.list_dir(dir_path),
                          key=lambda x:
                          (x[0] not in self.dirs, x[0].lower()))
     for path, mtime in sorted_list:
         basename = os.path.basename(path)
         if len(basename) == 0:
             continue
         item = QTreeWidgetItem()
         item.setText(0, basename)
         self.index[item] = path
         parent.setFlags(parent.flags() | Qt.ItemIsTristate
                         | Qt.ItemIsUserCheckable)
         item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
         item.setCheckState(
             0, Qt.Checked
             if parent.checkState(0) == Qt.Checked else Qt.Unchecked)
         parent.addChild(item)
         item.setText(
             1, time.strftime("%b %d %Y %I:%M:%S %p",
                              time.localtime(mtime)))
         if path in self.dirs and len(self.list_dir(path)) != 0:
             sub_item = QTreeWidgetItem()
             self.hidden[item] = sub_item
             item.addChild(sub_item)
             item.setIcon(0, QIcon(get_resource_path("images/folder.png")))
Пример #3
0
 def _create(self):
     struct = self.dm.getStructure(self.isInverse)
     for ws in struct:
         gparent = QTreeWidgetItem(self)
         gparent.setText(0, ws)
         for key in struct[ws]:
             parent = QTreeWidgetItem(gparent)
             parent.setText(0, key)
             parent.setFlags(parent.flags() | Qt.ItemIsTristate
                             | Qt.ItemIsUserCheckable)
             if (self.inputList is not None and key == self.inputList[1]
                     and ws == self.inputList[0]):
                 channelsChecked = True
                 gparent.setExpanded(True)
                 self.curChecked = parent
                 parent.setSelected(True)
             else:
                 channelsChecked = False
             for k in struct[ws][key]:
                 child = QTreeWidgetItem(parent)
                 child.setFlags(child.flags())
                 child.setText(0, k)
                 if channelsChecked:
                     child.setCheckState(0, Qt.Checked)
                 else:
                     child.setCheckState(0, Qt.Unchecked)
Пример #4
0
def create_node(item: Any) -> QTreeWidgetItem:
    child_node = QTreeWidgetItem()
    child_node.setFlags(child_node.flags() | Qt.ItemIsUserCheckable)
    child_node.setCheckState(0, Qt.CheckState.Checked)
    child_node.setData(1, 0, item)

    return child_node
Пример #5
0
 def onAddOptionGroup(self):
     text, ok = QInputDialog.getText(self.backtest, "请输入期权组名称", "名称",
                                     QLineEdit.Normal)
     current_item = self.backtest_tree.currentItem()
     # parent_item = current_item.parent()
     current_item_text = current_item.text(0)
     # parent_item_text = parent_item.text(0)
     if ok and text:
         node = QTreeWidgetItem(current_item)
         node.setText(0, text)
         node.setCheckState(0, Qt.Unchecked)
         node.setWhatsThis(0, "option_group")
         node.setIcon(0, QtGui.QIcon("../icon/group.png"))
         self.backtest_tree.expandItem(self.backtest_tree.currentItem())
         group_dict = {
             "name": text,
             "enable": 1,
             "contracts": [],
             "signal": {
                 "type": "list",
                 "value": 0,
                 "list": []
             },
             "ratio": {
                 "type": "float",
                 "value": 0,
             },
         }
         for underlying in self.config["options"]["underlyings"]:
             if underlying.get("name") == current_item_text:
                 underlying["groups"].append(group_dict)
Пример #6
0
 def add_root_path(self, path):
     root = QTreeWidgetItem()
     root.setText(0, path)
     root.setCheckState(0, Qt.Unchecked)
     root.setIcon(0, QIcon(get_resource_path("images/folder.png")))
     self.index[root] = path
     self.expanded.add(path)
     self.snapshot_tree_widget.addTopLevelItem(root)
     self.add_dir(path, root)
Пример #7
0
    def onAddOptionUnderlying(self):

        text, ok = QInputDialog.getText(self.backtest, "请输入期权标的名称", "名称",
                                        QLineEdit.Normal)
        if ok and text:
            node = QTreeWidgetItem(self.backtest_tree.currentItem())
            node.setText(0, text)
            node.setCheckState(0, Qt.Unchecked)
            node.setWhatsThis(0, "option_underlying")
            self.backtest_tree.expandItem(self.backtest_tree.currentItem())
            ids = [
                i.btId for i in self.mdi_area.subWindowList()
                if hasattr(i, "btType")
                and i.btType in ["option_underlying", "excel", "csv"]
            ]
            group_dict = {
                "name": text,
                "enable": 0,
                "ratio": {
                    "type": "int",
                    "value": 0,
                },
                "id": {
                    "type":
                    "list",
                    "value":
                    0,
                    "list":
                    ids,
                    "data":
                    getattr(
                        self.parent.getSubWindowByAttribute("btId", ids[0]),
                        "btData")
                },
                "signal": {
                    "type": "list",
                    "value": 0,
                    "list": []
                },
                "option_side": {
                    "type": "list",
                    "value": 0,
                    "list": [u"买入"]
                },
                "volume": {
                    "type": "int",
                    "value": 0,
                },
                "groups": [],
                "contracts": [],
            }
            self.config["options"]["underlyings"].append(group_dict)
Пример #8
0
 def createCourseTreeItem(self, name: str, courseId: str, chapterId: str,
                          hasChild: bool):
     item = QTreeWidgetItem()
     item.setText(0, str(name))
     item.setText(1, str(courseId))
     item.setText(2, str(chapterId))
     if hasChild is True:
         item.setFlags(item.flags() | Qt.ItemIsTristate
                       | Qt.ItemIsUserCheckable)
     else:
         item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
         item.setCheckState(0, Qt.Unchecked)
     return item
Пример #9
0
    def _createFilterTree(self, spatial_filters):
        av = self.model.activeView
        tally = self.model.statepoint.tallies[av.selectedTally]
        filters = tally.filters

        # create a tree for the filters
        self.treeLayout = QVBoxLayout()
        self.filterTree = QTreeWidget()
        self.treeLayout.addWidget(self.filterTree)
        self.treeExpander = Expander("Filters:", layout=self.treeLayout)
        self.treeExpander.expand()  # start with filters expanded

        header = QTreeWidgetItem(["Filters"])
        self.filterTree.setHeaderItem(header)
        self.filterTree.setItemHidden(header, True)
        self.filterTree.setColumnCount(1)

        self.filter_map = {}
        self.bin_map = {}

        for tally_filter in filters:
            filter_label = str(type(tally_filter)).split(".")[-1][:-2]
            filter_item = QTreeWidgetItem(self.filterTree, (filter_label,))
            self.filter_map[tally_filter] = filter_item

            # make checkable
            if not spatial_filters:
                filter_item.setFlags(QtCore.Qt.ItemIsUserCheckable)
                filter_item.setToolTip(0, "Only tallies with spatial filters are viewable.")
            else:
                filter_item.setFlags(filter_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
            filter_item.setCheckState(0, QtCore.Qt.Unchecked)

            if isinstance(tally_filter, MeshFilter):
                filter_item.setCheckState(0, QtCore.Qt.Checked)
                filter_item.setFlags(QtCore.Qt.ItemIsUserCheckable)
                filter_item.setToolTip(0, "All Mesh bins are selected automatically")
                continue

            def _bin_sort_val(bin):
                if isinstance(bin, Iterable) and all([isinstance(val, float) for val in bin]):
                    return np.sum(bin)
                else:
                    return bin

            for bin in sorted(tally_filter.bins, key=_bin_sort_val):
                item = QTreeWidgetItem(filter_item, [str(bin),])
                if not spatial_filters:
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable)
                    item.setToolTip(0, "Only tallies with spatial filters are viewable.")
                else:
                    item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
                item.setCheckState(0, QtCore.Qt.Unchecked)

                bin = bin if not isinstance(bin, Iterable) else tuple(bin)
                self.bin_map[tally_filter, bin] = item

            # start with all filters selected if spatial filters are present
            if spatial_filters:
                filter_item.setCheckState(0, QtCore.Qt.Checked)
Пример #10
0
 def init_trees(self):
     ''' Draw hierarchical tree of fields in NWB file '''
     self.tree_primary.clear()
     self.tree_secondary.clear()
     for var1 in self.primary_names:  # primary variables list
         parent = QTreeWidgetItem(self.tree_primary,
                                  [var1, str(self.df[var1].dtype)])
         parent.setFlags(parent.flags() | QtCore.Qt.ItemIsTristate
                         | QtCore.Qt.ItemIsUserCheckable)
         parent.setCheckState(0, QtCore.Qt.Checked)
     for var2 in self.secondary_names:  # secondary variables list
         parent = QTreeWidgetItem(
             self.tree_secondary,
             [var2, str(self.secondary_vars[var2].dtype)])
         parent.setFlags(parent.flags() | QtCore.Qt.ItemIsTristate
                         | QtCore.Qt.ItemIsUserCheckable)
         parent.setCheckState(0, QtCore.Qt.Checked)
Пример #11
0
    def add_dict_to_tree(self, filesList):
        self.gui.file_tree.clear()

        for group in filesList:
            parent = QTreeWidgetItem(self.gui.file_tree)

            parent.setFlags(parent.flags() | Qt.ItemIsTristate
                            | Qt.ItemIsUserCheckable)

            source_item = None
            for item_object, simVal in group.items():

                if simVal == "Source":
                    parent.setText(0, "{}".format(item_object.fn))
                    parent.setText(3, "{}".format(item_object.src_fqpath))
                    source_item = item_object

            assert source_item is not None
            for item_object, simVal in group.items():

                if simVal == "Source":
                    continue

                branch = QTreeWidgetItem(parent)
                branch.setFlags(branch.flags() | Qt.ItemIsUserCheckable)

                branch.setText(CLEANED_NAME_COLUMN, item_object.cn)
                branch.setText(FILE_NAME_COLUMN, item_object.fn)
                branch.setText(SOURCE_FQPATH_COLUMN,
                               "%s" % (item_object.src_fqpath, ))
                branch.setText(DEST_FQPATH_COLUMN,
                               "%s" % (item_object.dest_fqpath, ))
                if isinstance(simVal, (int, float)):
                    branch.setText(SIMILARITY_COLUMN, "%0.5f" % (simVal, ))
                else:
                    branch.setText(SIMILARITY_COLUMN, "%s" % (simVal, ))
                branch.setCheckState(0, Qt.Unchecked)
                branch.item_data = item_object

        self.gui.file_tree.setColumnWidth(CLEANED_NAME_COLUMN, 400)
        self.gui.file_tree.setColumnWidth(FILE_NAME_COLUMN, 400)
        self.gui.file_tree.setColumnWidth(SOURCE_FQPATH_COLUMN, 100)
        self.gui.file_tree.setColumnWidth(DEST_FQPATH_COLUMN, 100)
        self.gui.file_tree.setColumnWidth(SIMILARITY_COLUMN, 100)
Пример #12
0
    def addItem(self, group, row, colList):
        rootIter = QTreeWidgetItemIterator(self,
                                           QTreeWidgetItemIterator.HasChildren)
        gparent = None
        while (rootIter.value()):
            item = rootIter.value()
            if item.text(0) == group and rootIter.value().parent() is None:
                gparent = item
                break
            rootIter += 1

        parent = QTreeWidgetItem(gparent)
        parent.setText(0, row)
        parent.setFlags(parent.flags() | Qt.ItemIsTristate
                        | Qt.ItemIsUserCheckable)
        for k in colList:
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags())
            child.setText(0, k)
            child.setCheckState(0, Qt.Unchecked)
Пример #13
0
    def get_plc_tags(self):
        self.tags.clear()
        self.ui.treeWidget
        with LogixDriver(self.ui.comboBox_ip.currentText()) as plc:
            self.tags = plc.get_tag_list()
        for i in self.tags:
            parent = QTreeWidgetItem(self.ui.treeWidget)
            parent.setText(0, "{}".format(i['tag_name']))
            if type(i['data_type']) == str:
                parent.setText(1, i['data_type'])
            parent.setFlags(parent.flags() | Qt.ItemIsUserCheckable)
            parent.setCheckState(0, Qt.Unchecked)
            #for x in range(5):
            #    child = QTreeWidgetItem(parent)
            #    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            #    child.setText(0, "Child {}".format(x))
            #    child.setCheckState(0, Qt.Unchecked)

        self.ui.treeWidget.sortByColumn(0)
        self.ui.treeWidget.resizeColumnToContents(0)
Пример #14
0
 def onAddOptionContract(self):
     text, ok = QInputDialog.getText(self.backtest, "请输入期权合约名称", "名称",
                                     QLineEdit.Normal)
     current_item = self.backtest_tree.currentItem()
     current_item_whats_this = current_item.whatsThis(0)
     current_item_text = current_item.text(0)
     parent_item = current_item.parent()
     parent_whats_this = parent_item.whatsThis(0)
     parent_item_text = parent_item.text(0)
     if ok and text:
         node = QTreeWidgetItem(current_item)
         node.setText(0, text)
         node.setCheckState(0, Qt.Unchecked)
         node.setWhatsThis(0, "option_contract")
         node.setIcon(0, QtGui.QIcon("../icon/contract.png"))
         self.backtest_tree.expandItem(self.backtest_tree.currentItem())
         filter_dict = {
             "name": text,
             "enable": 1,
             "open_status": False,
             "ids": [],
             "option_type": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_TYPE,
             },
             "option_side": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_SIDE,
             },
             "close_method": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_CLOSE_METHOD,
             },
             "change_feq": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_CHANGE_FEQ,
             },
             "change_condition": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_CHANGE_CONDITION,
             },
             "month_interval": {
                 "type":
                 "list",
                 "value":
                 0,
                 "list": [
                     setting.OPTION_INTERVAL[i]
                     for i in range(len(setting.OPTION_INTERVAL)) if i != 2
                 ],
             },
             "strike_interval": {
                 "type": "list",
                 "value": 0,
                 "list": setting.OPTION_STRIKE_INTERVAL,
             },
             "smart_selection": {
                 "type": "list",
                 "value": 1,
                 "list": setting.OPTION_SMART_SELECTION,
             },
             "type": "option",
             "volume": {
                 "type": "int",
                 "value": 0
             },
             "deposit_coefficient": {
                 "type": "int",
                 "value": 1,
             },
             "delta": {
                 "type": "int",
                 "value": 0,
             },
             "gamma": {
                 "type": "int",
                 "value": 0,
             },
             "theta": {
                 "type": "int",
                 "value": 0,
             },
             "vega": {
                 "type": "int",
                 "value": 0,
             },
             "rho": {
                 "type": "int",
                 "value": 0,
             },
             "ivix": {
                 "type": "float",
                 "value": 0
             }
         }
         for underlying in self.config["options"]["underlyings"]:
             underlying_name = underlying.get("name")
             if current_item_whats_this == "option_group":
                 if underlying_name == parent_item_text:
                     groups = underlying.get("groups")
                     for group in groups:
                         if group.get("name") == current_item_text:
                             group["contracts"].append(filter_dict)
             elif current_item_whats_this == "option_underlying":
                 if underlying_name == current_item_text:
                     underlying.get("contracts").append(filter_dict)
Пример #15
0
    def _init_widgets(self):
        layout = QGridLayout()
        row = 0

        validation_failures = set()

        # name

        name_label = QLabel(self)
        name_label.setText("Name")

        name_box = QLineEdit(self)
        name_box.setText(NameGenerator.random_name())

        def handle_name(txt):
            nonlocal validation_failures
            key = {'name'}
            if txt and not any(s.gui_data.name == txt
                               for s in self.instance.states):
                validation_failures -= key
            else:
                validation_failures |= key
            validation_update()

        name_box.textEdited.connect(handle_name)

        layout.addWidget(name_label, row, 0)
        layout.addWidget(name_box, row, 1)
        row += 1

        # address

        address_label = QLabel(self)
        address_label.setText("Address")

        address_box = QLineEdit(self)
        address_box.setText(
            hex(self.instance.project.entry
                ) if self._addr is None else hex(self._addr))

        def handle_address(_):
            nonlocal validation_failures
            key = {'addr'}
            if parse_address() is not None:
                validation_failures -= key
            else:
                validation_failures |= key
            validation_update()

        def parse_address():
            txt = address_box.text()
            try:
                return self.instance.project.kb.labels.lookup(txt)
            except KeyError:
                pass

            try:
                return int(txt, 16)
            except ValueError:
                return None

        address_box.textEdited.connect(handle_address)
        layout.addWidget(address_label, row, 0)
        layout.addWidget(address_box, row, 1)
        row += 1

        # template

        template_label = QLabel(self)
        template_label.setText("Template")

        template_combo = QComboBox()
        template_combo.addItem("Blank State", 'blank')
        template_combo.addItem("Call state", 'call')
        template_combo.addItem("Entry state", 'entry')
        template_combo.addItem("Full-init state", 'full')

        def handle_template(_):
            base_allowed = template_combo.currentData() in ('blank', 'call')
            base_state_combo.setHidden(not base_allowed)
            base_state_label.setHidden(not base_allowed)

        template_combo.currentIndexChanged.connect(handle_template)

        layout.addWidget(template_label, row, 0)
        layout.addWidget(template_combo, row, 1)
        row += 1

        # base state

        base_state_label = QLabel(self)
        base_state_label.setText('Base state')

        base_state_combo = QStateComboBox(self.instance, self)
        self._base_state_combo = base_state_combo

        layout.addWidget(base_state_label, row, 0)
        layout.addWidget(base_state_combo, row, 1)
        row += 1

        # mode

        mode_label = QLabel(self)
        mode_label.setText("Mode")

        mode_combo = QComboBox(self)
        mode_combo.addItem("Symbolic", "symbolic")
        mode_combo.addItem("Static", "static")
        mode_combo.addItem("Fast-path", "fastpath")
        mode_combo.addItem("Tracing", "tracing")
        self._mode_combo = mode_combo

        def mode_changed():
            self._options.clear()
            self._options.update(
                angr.sim_options.modes[mode_combo.currentData()])
            for child in children_items:
                child.setCheckState(
                    0, Qt.Checked
                    if child.text(0) in self._options else Qt.Unchecked)

        mode_combo.currentIndexChanged.connect(mode_changed)
        self._options.clear()
        self._options.update(angr.sim_options.modes[mode_combo.currentData()])

        layout.addWidget(mode_label, row, 0)
        layout.addWidget(mode_combo, row, 1)
        row += 1

        # options tree

        options_label = QLabel(self)
        options_label.setText("Options")

        options_tree = QTreeWidget(self)
        options_tree.setHeaderHidden(True)
        children_items = []
        for name, members in angr.sim_options.__dict__.items():
            if type(members) is not set:
                continue
            if name == 'resilience_options':
                continue
            parent = QTreeWidgetItem(options_tree)
            parent.setText(0, name)
            parent.setFlags(parent.flags() | Qt.ItemIsTristate
                            | Qt.ItemIsUserCheckable)
            for option in members:
                child = QTreeWidgetItem(parent)
                child.setText(0, option)
                child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                child.setCheckState(
                    0, Qt.Checked if option in self._options else Qt.Unchecked)
                children_items.append(child)
        parent = QTreeWidgetItem(options_tree)
        parent.setText(0, "All options")
        parent.setFlags(parent.flags() | Qt.ItemIsTristate
                        | Qt.ItemIsUserCheckable)
        for option in {
                x
                for x in angr.sim_options.__dict__.values()
                if type(x) is str and is_option(x)
        }:
            child = QTreeWidgetItem(parent)
            child.setText(0, option)
            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            child.setCheckState(
                0, Qt.Checked if option in self._options else Qt.Unchecked)
            children_items.append(child)

        def maintain_model(item: QTreeWidgetItem, _):
            option = item.text(0)
            if not is_option(option):
                return

            checked = item.checkState(0)
            if (option in self._options) == checked:
                return

            if checked:
                self._options.add(option)
            else:
                self._options.remove(option)

            for child in children_items:
                if child is not item and child.text(0) == option:
                    child.setCheckState(0, checked)

        options_tree.itemChanged.connect(maintain_model)

        layout.addWidget(options_label, row, 0)
        layout.addWidget(options_tree, row, 1)
        row += 1

        # options filter

        options_filter_label = QLabel(self)
        options_filter_label.setText("")

        options_filter_box = QLineEdit(self)
        options_filter_box.setPlaceholderText("Filter")

        def do_filter(text):
            for child in children_items:
                child.setHidden(text.upper() not in child.text(0))

        options_filter_box.textEdited.connect(do_filter)

        layout.addWidget(options_filter_label, row, 0)
        layout.addWidget(options_filter_box, row, 1)
        row += 1

        # buttons

        ok_button = QPushButton(self)
        ok_button.setText('OK')

        def do_ok():
            name = name_box.text()
            template = template_combo.currentData()
            addr = parse_address()
            base_state = base_state_combo.state
            mode = mode_combo.currentData()
            if template in ('blank', 'call') and base_state is not None:
                if template == 'blank':
                    self.state = self.instance.project.factory.blank_state(
                        addr=addr,
                        base_state=base_state,
                        options=self._options)
                else:
                    self.state = self.instance.project.factory.call_state(
                        addr, base_state=base_state, options=self._options)
                self.state.gui_data.base_name = base_state.gui_data.name
            else:
                if template == 'blank':
                    self.state = self.instance.project.factory.blank_state(
                        addr=addr, mode=mode, options=self._options)
                elif template == 'call':
                    self.state = self.instance.project.factory.call_state(
                        addr, mode=mode, options=self._options)
                elif template == 'entry':
                    self.state = self.instance.project.factory.entry_state(
                        mode=mode, options=self._options)
                else:
                    self.state = self.instance.project.factory.full_init_state(
                        mode=mode, options=self._options)
                self.state.gui_data.base_name = name
                self.state.gui_data.is_base = True

            self.state.gui_data.name = name
            self.state.gui_data.is_original = True

            if self._create_simgr:
                self.instance.workspace.create_simulation_manager(
                    self.state, name)

            self.close()

        ok_button.clicked.connect(do_ok)

        def validation_update():
            ok_button.setDisabled(bool(validation_failures))

        cancel_button = QPushButton(self)
        cancel_button.setText('Cancel')

        def do_cancel():
            self.close()

        cancel_button.clicked.connect(do_cancel)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)

        self.main_layout.addLayout(layout)
        self.main_layout.addLayout(buttons_layout)
 def __change_item_check_state_by_item_pressed(cls, item: QTreeWidgetItem,
                                               col):
     if item.checkState(col) == Qt.Checked:
         item.setCheckState(col, Qt.Unchecked)
     else:
         item.setCheckState(col, Qt.Checked)
Пример #17
0
    def _updateAll(self, newGroup=None):
        try:
            self.chSelector.itemChanged.disconnect(self.itemChanged)
            self.sSelector.itemChanged.disconnect(self.itemChanged)
        except:
            pass
        if newGroup == '':
            return
        
        chStruct = self.chartData[newGroup]
        sStruct = self.chartData[newGroup].getColStructure()
        
        self.chSelector.clear()
        for ws in chStruct:
            gparent = QTreeWidgetItem(self.chSelector)
            gparent.setText(0, ws)
            gparent.setBackgroundColor(0, Qt.white)
            gparent.setFlags(Qt.ItemIsEnabled)
            for key in chStruct[ws]:
                parent = QTreeWidgetItem(gparent)
                parent.setText(0, key)
                if chStruct[ws][key][0] == True:
                    dataNames = chStruct[ws][key][3]
                    sColor = QColor(chStruct[ws][key][4])
                    sColor.setAlpha(100)
                    parent.setBackgroundColor(0, sColor)
                else:
                    dataNames = ','.join(chStruct[ws][key][2])
                    sColor = QColor(chStruct[ws][key][3])
                    sColor.setAlpha(100)
                    parent.setBackgroundColor(0, sColor)
                    
                parent.setText(1, dataNames)
                if chStruct[ws][key][1] == True:
                    parent.setCheckState(0, Qt.Checked)
                else:
                    parent.setCheckState(0, Qt.Unchecked)
                parent.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
        
        self.sSelector.clear()
        self.gSelector.clear()
        for ws in sStruct:
            firstChannel = sStruct[ws][0]
            isOneSignal = self.chartData[newGroup][firstChannel][ws][0]
            if isOneSignal:
                gparent = QTreeWidgetItem(self.sSelector)
                gparent.setText(0, ws)
                gparent.setFlags(Qt.ItemIsEnabled | Qt.ItemIsDragEnabled
                                 | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable)
                if True:
##                if chStruct['CH1'][ws][5] == True:
                    gparent.setCheckState(0, Qt.Checked) 
                else:
                    gparent.setCheckState(0, Qt.Unchecked)
                    
                for key in sStruct[ws]:
                    parent = QTreeWidgetItem(gparent)
                    parent.setText(0, key)
                    if chStruct[key][ws][2] == True:
                        parent.setCheckState(0, Qt.Checked)
                    else:
                        parent.setCheckState(0, Qt.Unchecked)
                    parent.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                    sColor = QColor(chStruct[key][ws][4])
                    sColor.setAlpha(100)
                    sGradient = QLinearGradient(0, 0, 100, 10)
                    sGradient.setColorAt(0, sColor)
                    sGradient.setColorAt(1, Qt.white)
                    sBrush = QBrush(sGradient)
                    sBrush.setStyle(Qt.LinearGradientPattern)
                    sBrush.setColor(sColor)
                    gparent.setBackground(0, sBrush)
                    
            else:
                gparent = QTreeWidgetItem(self.gSelector)
                gparent.setText(0, ws)
                gparent.setFlags(Qt.ItemIsEnabled | Qt.ItemIsDropEnabled
                                 | Qt.ItemIsUserCheckable)
                if chStruct['CH1'][ws][5] == True:
                    gparent.setCheckState(0, Qt.Checked)
                else:
                    gparent.setCheckState(0, Qt.Unchecked)
                
                signalNames = chStruct[key][ws][2]
                sColor = QColor(chStruct[key][ws][3])
                sColor.setAlpha(100)
                gparent.setBackgroundColor(0, sColor)
                for signal in signalNames:
                    parent = QTreeWidgetItem(gparent)
                    parent.setText(0, signal)
                    parent.setFlags(Qt.ItemIsEnabled)

                    for key in sStruct[signal]:
                        sColor = QColor(chStruct[key][signal][4])
                        sColor.setAlpha(100)
                        parent.setBackgroundColor(0, sColor)
                        break                   
            
        self.chSelector.itemChanged.connect(self.itemChanged)
        self.sSelector.itemChanged.connect(self.itemChanged)
        self.curSelect = None
Пример #18
0
    def loadBacktestTree(self):
        options = self.config.get("options", {})
        underlyings = options.get("underlyings", [])

        for i in range(1):
            item = self.backtest_tree.topLevelItem(i)
            item.setExpanded(True)
            for j in range(item.childCount()):
                child_item = item.child(j)
                child_item.setExpanded(True)
                whatsthis = child_item.whatsThis(0)
                if whatsthis == "option":
                    for underlying in underlyings:
                        current_item = child_item
                        node = QTreeWidgetItem(current_item)
                        node.setText(0, underlying["name"])
                        node.setCheckState(0, Qt.Unchecked)
                        node.setWhatsThis(0, "option_underlying")
                        node.setExpanded(True)

                        data = underlying.get("id",
                                              {}).get("data", pd.DataFrame())
                        if not data.empty:
                            id_dict = underlying.get("id", {})
                            name = id_dict["list"][id_dict["value"]]
                            childSubWindow = {
                                "title": "%s的当日合约",
                                "type": "option_contract_table",
                                "table_name": "%date%",
                                "where": "",
                                "select": id,
                                "hidden_columns": [],
                                "index_column": [],
                                "childSubWindow": {},
                            }
                            hidden_columns = [
                                'total_turnover', 'limit_up', 'limit_down',
                                'settlement', 'prev_settlement',
                                'discount_rate', 'acc_net_value',
                                'unit_net_value', 'date', 'open_interest',
                                'iopv', 'num_trades'
                            ]

                            GridView(self.parent,
                                     name,
                                     data,
                                     id=name,
                                     hidden_columns=hidden_columns,
                                     index_column='date',
                                     childSubWindow=childSubWindow,
                                     type="option_underlying")
                        current_item = node

                        groups = underlying.get("groups", [])
                        for group in groups:
                            node = QTreeWidgetItem(current_item)
                            node.setText(0, group["name"])
                            node.setCheckState(0, Qt.Unchecked)
                            node.setIcon(0, QtGui.QIcon("../icon/group.png"))
                            node.setWhatsThis(0, "option_group")
                            node.setExpanded(True)
                            current_item = node
                            contracts = group.get("contracts")
                            for contract in contracts:
                                node = QTreeWidgetItem(current_item)
                                node.setText(0, contract["name"])
                                node.setCheckState(0, Qt.Unchecked)
                                node.setWhatsThis(0, "option_contract")
                                node.setExpanded(True)
                                current_item = node
Пример #19
0
    def _add_msg_object(self, parent, path, name, obj, obj_type):
        label = name

        if hasattr(obj, '__slots__'):
            subobjs = [(slot, getattr(obj, slot)) for slot in obj.__slots__]
        elif type(obj) in [list, tuple]:
            len_obj = len(obj)
            if len_obj == 0:
                subobjs = []
            else:
                w = int(math.ceil(math.log10(len_obj)))
                subobjs = [('[%*d]' % (w, i), subobj) for (i, subobj) in enumerate(obj)]
        else:
            subobjs = []

        plotitem=False
        if type(obj) in [int, long, float]:
            plotitem=True
            if type(obj) == float:
                obj_repr = '%.6f' % obj
            else:
                obj_repr = str(obj)

            if obj_repr[0] == '-':
                label += ': %s' % obj_repr
            else:
                label += ':  %s' % obj_repr

        elif type(obj) in [str, bool, int, long, float, complex, rospy.Time]:
            # Ignore any binary data
            obj_repr = codecs.utf_8_decode(str(obj), 'ignore')[0]

            # Truncate long representations
            if len(obj_repr) >= 50:
                obj_repr = obj_repr[:50] + '...'

            label += ': ' + obj_repr
        item = QTreeWidgetItem([label])
        if name == '':
            pass
        elif path.find('.') == -1 and path.find('[') == -1:
            self.addTopLevelItem(item)
        else:
            parent.addChild(item)
        if plotitem == True:
            if path.replace(' ', '') in self._checked_states:
                item.setCheckState (0, Qt.Checked)
            else:
                item.setCheckState (0, Qt.Unchecked)
        item.setData(0, Qt.UserRole, (path, obj_type))


        for subobj_name, subobj in subobjs:
            if subobj is None:
                continue

            if path == '':
                subpath = subobj_name  # root field
            elif subobj_name.startswith('['):
                subpath = '%s%s' % (path, subobj_name)  # list, dict, or tuple
            else:
                subpath = '%s.%s' % (path, subobj_name)  # attribute (prefix with '.')

            if hasattr(subobj, '_type'):
                subobj_type = subobj._type
            else:
                subobj_type = type(subobj).__name__

            self._add_msg_object(item, subpath, subobj_name, subobj, subobj_type)
Пример #20
0
    def _init_widgets(self):
        layout = QGridLayout()
        row = 0

        validation_failures = set()

        # name

        name_label = QLabel(self)
        name_label.setText("Name")

        name_box = QLineEdit(self)
        name_box.setText(NameGenerator.random_name())

        def handle_name(txt):
            nonlocal validation_failures
            key = {'name'}
            if txt and not any(s.gui_data.name == txt
                               for s in self.instance.states):
                validation_failures -= key
            else:
                validation_failures |= key
            validation_update()

        name_box.textEdited.connect(handle_name)

        layout.addWidget(name_label, row, 0)
        layout.addWidget(name_box, row, 1)
        row += 1

        # address

        address_label = QLabel(self)
        address_label.setText("Address")

        address_box = QLineEdit(self)
        self._address_box = address_box
        address_box.setText(
            hex(self.instance.project.entry
                ) if self._addr is None else hex(self._addr))

        def handle_address(_):
            nonlocal validation_failures
            key = {'addr'}
            if parse_address() is not None:
                validation_failures -= key
            else:
                validation_failures |= key
            validation_update()

        def parse_address():
            txt = address_box.text()
            try:
                return self.instance.project.kb.labels.lookup(txt)
            except KeyError:
                pass

            try:
                return int(txt, 16)
            except ValueError:
                return None

        address_box.textEdited.connect(handle_address)
        layout.addWidget(address_label, row, 0)
        layout.addWidget(address_box, row, 1)
        row += 1

        # template

        template_label = QLabel(self)
        template_label.setText("Template")

        template_combo = QComboBox()
        template_combo.addItem("Blank State", 'blank')
        template_combo.addItem("Call state", 'call')
        template_combo.addItem("Entry state", 'entry')
        template_combo.addItem("Full-init state", 'full')

        def handle_template(_):
            base_allowed = template_combo.currentData() in ('blank', 'call')
            base_state_combo.setHidden(not base_allowed)
            base_state_label.setHidden(not base_allowed)
            args_allowed = template_combo.currentData() in ("entry", )
            args_label.setHidden(not args_allowed)
            args_edit.setHidden(not args_allowed)

        template_combo.currentIndexChanged.connect(handle_template)

        layout.addWidget(template_label, row, 0)
        layout.addWidget(template_combo, row, 1)
        row += 1

        # base state

        base_state_label = QLabel(self)
        base_state_label.setText('Base state')

        base_state_combo = QStateComboBox(self.instance, self)
        self._base_state_combo = base_state_combo

        layout.addWidget(base_state_label, row, 0)
        layout.addWidget(base_state_combo, row, 1)
        row += 1

        # args
        args_label = QLabel(self)
        args_label.setText('Args')

        args_edit = QLineEdit(self)
        self._args_edit = args_edit

        def handle_args():
            self._args = [
                self.instance.project.filename.encode() or b'dummy_filename'
            ]
            for x in args_edit.text().split():
                if len(x) > 2 and x[0] == "`" and x[-1] == "`":
                    tmp = [
                        symbol for symbol in self.instance.symbols
                        if symbol.args[0].split('_')[0] == x[1:-1]
                    ]
                    if len(tmp) == 1:
                        self._args.append(tmp[0])
                else:
                    self._args.append(x.encode())

        args_edit.editingFinished.connect(handle_args)

        layout.addWidget(args_label, row, 0)
        layout.addWidget(args_edit, row, 1)
        row += 1

        # fs_mount
        fs_label = QLabel(self)
        fs_label.setText('Filesystem')
        fs_button = QPushButton(self)
        fs_button.setText("Change")

        layout.addWidget(fs_label, row, 0)
        layout.addWidget(fs_button, row, 1)

        def fs_edit_button():
            fs_dialog = FilesystemMount(fs_config=self._fs_config,
                                        instance=self.instance,
                                        parent=self)
            fs_dialog.exec_()
            self._fs_config = fs_dialog.fs_config
            fs_button.setText("{} Items".format(len(self._fs_config)))

        fs_button.clicked.connect(fs_edit_button)

        row += 1

        # mode

        mode_label = QLabel(self)
        mode_label.setText("Mode")

        mode_combo = QComboBox(self)
        mode_combo.addItem("Symbolic", "symbolic")
        mode_combo.addItem("Static", "static")
        mode_combo.addItem("Fast-path", "fastpath")
        mode_combo.addItem("Tracing", "tracing")
        self._mode_combo = mode_combo

        def mode_changed():
            if mode_combo.currentData() == "tracing":
                TraceState(self.instance, self._base_state_combo,
                           self._address_box)
            self._options.clear()
            self._options.update(
                angr.sim_options.modes[mode_combo.currentData()])
            for child in children_items:
                child.setCheckState(
                    0, Qt.Checked
                    if child.text(0) in self._options else Qt.Unchecked)

        mode_combo.currentIndexChanged.connect(mode_changed)
        self._options.clear()
        self._options.update(angr.sim_options.modes[mode_combo.currentData()])

        layout.addWidget(mode_label, row, 0)
        layout.addWidget(mode_combo, row, 1)
        row += 1

        # options tree

        options_label = QLabel(self)
        options_label.setText("Options")

        options_tree = QTreeWidget(self)
        options_tree.setHeaderHidden(True)
        children_items = []
        for name, members in angr.sim_options.__dict__.items():
            if type(members) is not set:
                continue
            if name == 'resilience_options':
                continue
            parent = QTreeWidgetItem(options_tree)
            parent.setText(0, name)
            parent.setFlags(parent.flags() | Qt.ItemIsTristate
                            | Qt.ItemIsUserCheckable)
            for option in members:
                child = QTreeWidgetItem(parent)
                child.setText(0, option)
                child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                child.setCheckState(
                    0, Qt.Checked if option in self._options else Qt.Unchecked)
                children_items.append(child)
        parent = QTreeWidgetItem(options_tree)
        parent.setText(0, "All options")
        parent.setFlags(parent.flags() | Qt.ItemIsTristate
                        | Qt.ItemIsUserCheckable)
        for option in {
                x
                for x in angr.sim_options.__dict__.values()
                if type(x) is str and is_option(x)
        }:
            child = QTreeWidgetItem(parent)
            child.setText(0, option)
            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            child.setCheckState(
                0, Qt.Checked if option in self._options else Qt.Unchecked)
            children_items.append(child)

        def maintain_model(item: QTreeWidgetItem, _):
            option = item.text(0)
            if not is_option(option):
                return

            checked = item.checkState(0)
            if (option in self._options) == checked:
                return

            if checked:
                self._options.add(option)
            else:
                self._options.remove(option)

            for child in children_items:
                if child is not item and child.text(0) == option:
                    child.setCheckState(0, checked)

        options_tree.itemChanged.connect(maintain_model)

        layout.addWidget(options_label, row, 0)
        layout.addWidget(options_tree, row, 1)
        row += 1

        # options filter

        options_filter_label = QLabel(self)
        options_filter_label.setText("")

        options_filter_box = QLineEdit(self)
        options_filter_box.setPlaceholderText("Filter")

        def do_filter(text):
            for child in children_items:
                child.setHidden(text.upper() not in child.text(0))

        options_filter_box.textEdited.connect(do_filter)

        layout.addWidget(options_filter_label, row, 0)
        layout.addWidget(options_filter_box, row, 1)
        row += 1

        # buttons

        ok_button = QPushButton(self)
        ok_button.setText('OK')

        def do_ok():
            name = name_box.text()
            template = template_combo.currentData()
            addr = parse_address()
            base_state = base_state_combo.state
            mode = mode_combo.currentData()
            if template in ('blank', 'call') and base_state is not None:
                if template == 'blank':
                    self.state = self.instance.project.factory.blank_state(
                        addr=addr,
                        base_state=base_state,
                        options=self._options)
                else:
                    self.state = self.instance.project.factory.call_state(
                        addr, base_state=base_state, options=self._options)
                self.state.gui_data.base_name = base_state.gui_data.name
            else:
                if template == 'blank':
                    self.state = self.instance.project.factory.blank_state(
                        addr=addr, mode=mode, options=self._options)
                elif template == 'call':
                    self.state = self.instance.project.factory.call_state(
                        addr, mode=mode, options=self._options)
                elif template == 'entry':
                    self.state = self.instance.project.factory.entry_state(
                        mode=mode, options=self._options, args=self._args)
                else:
                    self.state = self.instance.project.factory.full_init_state(
                        mode=mode, options=self._options)
                self.state.gui_data.base_name = name
                self.state.gui_data.is_base = True

            self.state.gui_data.name = name
            self.state.gui_data.is_original = True

            # TODO: there should prob be an am_event here
            def attach_addr_annotation(state):
                for i in range(len(state.solver.constraints)):
                    if SrcAddrAnnotation not in [
                            type(a)
                            for a in state.solver.constraints[i].annotations
                    ]:
                        state.solver.constraints[i] = \
                                state.solver.constraints[i].annotate(SrcAddrAnnotation(state.addr))
                return state

            self.state.inspect.b(event_type='constraints',
                                 when=angr.BP_AFTER,
                                 action=attach_addr_annotation)

            # mount fs
            if self._fs_config:
                for path, real in self._fs_config:
                    if os.path.isdir(real):
                        fs = angr.SimHostFilesystem(real)
                        fs.set_state(self.state)
                        self.state.fs.mount(path, fs)

            if self._create_simgr:
                self.instance.workspace.create_simulation_manager(
                    self.state, name)

            self.close()

        ok_button.clicked.connect(do_ok)

        def validation_update():
            ok_button.setDisabled(bool(validation_failures))

        cancel_button = QPushButton(self)
        cancel_button.setText('Cancel')

        def do_cancel():
            self.close()

        cancel_button.clicked.connect(do_cancel)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)

        self.main_layout.addLayout(layout)
        self.main_layout.addLayout(buttons_layout)