show data key-value in ListCtrl for tree item
556087
def show_data(self, item):
        
        child, cookie = self.mainview_tree.GetFirstChild(item)
        child_list = []
        while child.IsOk():
            child_list.append(child)
            child, cookie = self.mainview_tree.GetNextChild(item, cookie)

        lc = self.nodeview_lc
        lc.DeleteAllItems()
        for i, child in enumerate(child_list):
            text = self.mainview_tree.GetItemText(child)
            try:
                k, v = [s.strip() for s in text.split(':')]
            except ValueError:
                k, v = text, '...'
            idx = lc.InsertItem(MAXNROW, v)
            lc.SetItem(idx, 1, k)
408950
def emitDataChanged(self, treeItem):  # TODO: move to BaseTreeItem?
        
        indexLeft, indexRight = self.indexTupleFromItem(treeItem)
        checkItem = self.getItem(indexLeft)
        assert checkItem is treeItem, "{} != {}".format(checkItem, treeItem) # TODO: remove
        self.dataChanged.emit(indexLeft, indexRight)
1319113
def _populate_list(self, value):
        
        # Nothing to do if the value is rubbish.
        if value is None:
            return

        # Stop any recursion - no more returns from here to end of fn please!
        if self._in_update:
            return
        self._in_update = True

        # We need to update the tree view.
        self._root = os.path.abspath(value if os.path.isdir(value) else os.path.dirname(value))

        # The absolute expansion of "/" or "\" is the root of the disk, so is a cross-platform
        # way of spotting when to insert ".." or not.
        tree_view = []
        if len(self._root) > len(os.path.abspath(os.sep)):
            tree_view.append((["|-+ .."], os.path.abspath(os.path.join(self._root, ".."))))

        tree_dirs = []
        tree_files = []
        try:
            files = os.listdir(self._root)
        except OSError:
            # Can fail on Windows due to access permissions
            files = []
        for my_file in files:
            full_path = os.path.join(self._root, my_file)
            try:
                details = os.lstat(full_path)
            except OSError:
                # Can happen on Windows due to access permissions
                details = namedtuple("stat_type", "st_size st_mtime")
                details.st_size = 0
                details.st_mtime = 0
            name = "|-- {}".format(my_file)
            tree = tree_files
            if os.path.isdir(full_path):
                tree = tree_dirs
                if os.path.islink(full_path):
                    # Show links separately for directories
                    real_path = os.path.realpath(full_path)
                    name = "|-+ {} -> {}".format(my_file, real_path)
                else:
                    name = "|-+ {}".format(my_file)
            elif self._file_filter and not self._file_filter.match(my_file):
                # Skip files that don't match the filter (if present)
                continue
            elif os.path.islink(full_path):
                # Check if link target exists and if it does, show statistics of the
                # linked file, otherwise just display the link
                try:
                    real_path = os.path.realpath(full_path)
                except OSError:
                    # Can fail on Linux prof file system.
                    real_path = None
                if real_path and os.path.exists(real_path):
                    details = os.stat(real_path)
                    name = "|-- {} -> {}".format(my_file, real_path)
                else:
                    # Both broken directory and file links fall to this case.
                    # Actually using the files will cause a FileNotFound exception
                    name = "|-- {} -> {}".format(my_file, real_path)

            # Normalize names for MacOS and then add to the list.
            tree.append(([unicodedata.normalize("NFC", name),
                          readable_mem(details.st_size),
                          readable_timestamp(details.st_mtime)], full_path))

        tree_view.extend(sorted(tree_dirs))
        tree_view.extend(sorted(tree_files))

        self.options = tree_view
        self._titles[0] = self._root

        # We're out of the function - unset recursion flag.
        self._in_update = False
537208
def list_view_on_selected(self, widget, selected_item_key):
        
        self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())
1298343
def fill_tree(self, tree, input_dict):
        

        def add_element(item, key, value):
            child_name = QtGui.QStandardItem(key)
            child_name.setDragEnabled(False)
            child_name.setSelectable(False)
            child_name.setEditable(False)

            if isinstance(value, dict):
                for ket_child, value_child in value.items():
                    add_element(child_name, ket_child, value_child)
                child_value = QtGui.QStandardItem('')
            else:
                child_value = QtGui.QStandardItem(str(value))
                child_value.setData(value)

            child_value.setDragEnabled(False)
            child_value.setSelectable(False)
            child_value.setEditable(False)
            item.appendRow([child_name, child_value])

        for index, (loaded_item, loaded_item_settings) in enumerate(input_dict.items()):
            # print(index, loaded_item, loaded_item_settings)
            item = QtGui.QStandardItem(loaded_item)

            for key, value in loaded_item_settings['settings'].items():
                add_element(item, key, value)

            value = QtGui.QStandardItem('')
            tree.model().appendRow([item, value])

            if tree == self.tree_loaded:
                item.setEditable(False)
            tree.setFirstColumnSpanned(index, self.tree_infile.rootIndex(), True)
576299
def _render_item(self, depth, key, value = None, **settings):
        
        strptrn  = self.INDENT * depth

        lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
        s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
        lchar = self.fmt_text(lchar, **s)

        strptrn = "{}"
        if value is not None:
            strptrn += ": {}"
        s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING])
        strptrn = self.fmt_text(strptrn.format(key, value), **s)

        return '{} {} {}'.format(self.INDENT * depth, lchar, strptrn)
190507
def get_value_map(self):
        
        value_map = {}
        tree_clone = self.tree_mapping_widget.invisibleRootItem().clone()
        for tree_branch in tree_clone.takeChildren():
            value_list = []
            for tree_leaf in tree_branch.takeChildren():
                value_list += [tree_leaf.data(0, Qt.UserRole)]
            if value_list:
                value_map[tree_branch.data(0, Qt.UserRole)] = value_list
        return value_map
229508
def populate_tree(self, parentItem, children_list):
        """"""
        for child_key in children_list:
            self.item_depth += 1
            (filename, line_number, function_name, file_and_line, node_type
             ) = self.function_info(child_key)

            ((total_calls, total_calls_dif), (loc_time, loc_time_dif), (cum_time,
             cum_time_dif)) = self.format_output(child_key)

            child_item = TreeWidgetItem(parentItem)
            self.item_list.append(child_item)
            self.set_item_data(child_item, filename, line_number)

            # FIXME: indexes to data should be defined by a dictionary on init
            child_item.setToolTip(0, _('Function or module name'))
            child_item.setData(0, Qt.DisplayRole, function_name)
            child_item.setIcon(0, self.icon_list[node_type])

            child_item.setToolTip(1, _('Time in function '\
                                       '(including sub-functions)'))
            child_item.setData(1, Qt.DisplayRole, cum_time)
            child_item.setTextAlignment(1, Qt.AlignRight)
            
            child_item.setData(2, Qt.DisplayRole, cum_time_dif[0])
            child_item.setForeground(2, QColor(cum_time_dif[1]))
            child_item.setTextAlignment(2, Qt.AlignLeft)

            child_item.setToolTip(3, _('Local time in function '\
                                      '(not in sub-functions)'))

            child_item.setData(3, Qt.DisplayRole, loc_time)
            child_item.setTextAlignment(3, Qt.AlignRight)
            
            child_item.setData(4, Qt.DisplayRole, loc_time_dif[0])
            child_item.setForeground(4, QColor(loc_time_dif[1]))
            child_item.setTextAlignment(4, Qt.AlignLeft)

            child_item.setToolTip(5, _('Total number of calls '\
                                       '(including recursion)'))

            child_item.setData(5, Qt.DisplayRole, total_calls)
            child_item.setTextAlignment(5, Qt.AlignRight)
            
            child_item.setData(6, Qt.DisplayRole, total_calls_dif[0])
            child_item.setForeground(6, QColor(total_calls_dif[1]))
            child_item.setTextAlignment(6, Qt.AlignLeft)

            child_item.setToolTip(7, _('File:line '\
                                       'where function is defined'))
            child_item.setData(7, Qt.DisplayRole, file_and_line)
            #child_item.setExpanded(True)
            if self.is_recursive(child_item):
                child_item.setData(7, Qt.DisplayRole, '(%s)' % _('recursion'))
                child_item.setDisabled(True)
            else:
                callees = self.find_callees(child_key)
                if self.item_depth < 3:
                    self.populate_tree(child_item, callees)
                elif callees:
                    child_item.setChildIndicatorPolicy(child_item.ShowIndicator)
                    self.items_to_be_shown[id(child_item)] = callees
            self.item_depth -= 1
1186194
def showGridColumns( self ):
        
        delegate = self.itemDelegate()
        if ( isinstance(delegate, XTreeWidgetDelegate) ):
            return delegate.showGridColumns()
        return False
167505
def show_tree_cache(self, label, current_node=None):
        '''
        
        '''
        import os
        import tempfile
        import subprocess

        assert DEBUG, "Please use dr tree visualization functions in debug mode"

        cache_path = os.path.abspath('profiles')
        def string_for(self, my_name):

            color_mapping = {'new' : 'grey', 'pending':'red', 'cached':'yellow', 'done': 'green'}
            if hasattr(self, 'label'):
                my_name = self.label
            my_name = '%s (%s)' % (my_name, str(self.__class__.__name__))
            result = []
            if not hasattr(self, 'dterms'):
                return result
            for dterm in self.dterms:
                if hasattr(self, dterm):
                    dtval = getattr(self, dterm)
                    if hasattr(dtval, 'dterms') or hasattr(dtval, 'terms'):
                        child_label = getattr(dtval, 'label') if hasattr(dtval, 'label') else dterm
                        child_label = '%s (%s)' % (child_label, str(dtval.__class__.__name__))
                        src = 'aaa%d' % (id(self))
                        dst = 'aaa%d' % (id(dtval))

                        s = ''
                        color = color_mapping[dtval._status] if hasattr(dtval, '_status') else 'grey'
                        if dtval == current_node:
                            color = 'blue'
                        if isinstance(dtval, Concatenate) and len(dtval.dr_cached) > 0:
                            s = 'dr_cached\n'
                            for k, v in dtval.dr_cached.items():
                                if v is not None:
                                    issparse = sp.issparse(v)
                                    size = v.size 
                                    if issparse:
                                        size = v.shape[0] * v.shape[1]
                                        nonzero = len(v.data)
                                    else:
                                        nonzero = np.count_nonzero(v)  
                                    s += '\nsparse: %s\nsize: %d\nnonzero: %d\n' % (issparse, size, nonzero)
                            # if dtval.called_dr_wrt:
                            # #   dtval.called_dr_wrt = False
                            #     color = 'brown3'
                            # else:
                            #     color = 'azure1'
                        elif len(dtval._cache['drs']) > 0:
                            s = '_cache\n'
                            
                            for k, v in dtval._cache['drs'].items():
                                if v is not None:
                                    issparse = sp.issparse(v)
                                    size = v.size
                                    if issparse:
                                        size = v.shape[0] * v.shape[1]
                                        nonzero = len(v.data)
                                    else:
                                        nonzero = np.count_nonzero(v)     

                                    s += '\nsparse: %s\nsize: %d\nnonzero: %d\n' % (issparse, size, nonzero)
                                    if hasattr(dtval, '_cache_info'):
                                        s += '\ncache hit:%s\n' % dtval._cache_info[k]
                            # if hasattr(dtval,'called_dr_wrt') and dtval.called_dr_wrt:
                            # #   dtval.called_dr_wrt = False
                            #     color = 'brown3'
                            # else:
                            #     color = 'azure1'
                        result += ['%s -> %s;' % (src, dst)]
                        # Do not overwrite src
                        #result += ['%s [label="%s"];' % (src, my_name)]
                        result += ['%s [label="%s\n%s\n", color=%s, style=filled];' %
                                   (dst, child_label, s, color)]
                        result += string_for(getattr(self, dterm), dterm)
            return result
            

        dot_file_contents = 'digraph G {\n%s\n}' % '\n'.join(list(set(string_for(self, 'root'))))
        dot_file_name = os.path.join(cache_path, label)
        png_file_name = os.path.join(cache_path, label+'.png')
        with open(dot_file_name, 'w') as dot_file:
            with open(png_file_name, 'w') as png_file:
                dot_file.write(dot_file_contents)
                dot_file.flush()

                png_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
                subprocess.call(['dot', '-Tpng', '-o', png_file.name, dot_file.name])

        import webbrowser
        webbrowser.open('file://' + png_file.name)
        
        self.loop_children_do(self.reset_flag)
715351
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
		var i,
			key,
			l,
			node,
			foundOne = false,
			expandOpts = tree.options.persist.expandOpts,
			deferredList = [],
			missingKeyList = [];

		keyList = keyList || [];
		dfd = dfd || $.Deferred();

		for (i = 0, l = keyList.length; i < l; i++) {
			key = keyList[i];
			node = tree.getNodeByKey(key);
			if (node) {
				if (mode && node.isUndefined()) {
					foundOne = true;
					tree.debug(
						"_loadLazyNodes: " + node + " is lazy: loading..."
					);
					if (mode === "expand") {
						deferredList.push(node.setExpanded(true, expandOpts));
					} else {
						deferredList.push(node.load());
					}
				} else {
					tree.debug("_loadLazyNodes: " + node + " already loaded.");
					node.setExpanded(true, expandOpts);
				}
			} else {
				missingKeyList.push(key);
				tree.debug("_loadLazyNodes: " + node + " was not yet found.");
			}
		}

		$.when.apply($, deferredList).always(function() {
			// All lazy-expands have finished
			if (foundOne && missingKeyList.length > 0) {
				// If we read new nodes from server, try to resolve yet-missing keys
				_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
			} else {
				if (missingKeyList.length) {
					tree.warn(
						"_loadLazyNodes: could not load those keys: ",
						missingKeyList
					);
					for (i = 0, l = missingKeyList.length; i < l; i++) {
						key = keyList[i];
						local._appendKey(EXPANDED, keyList[i], false);
					}
				}
				dfd.resolve();
			}
		});
		return dfd;
	}
394363
def __focus(self, item):
        """"""
        cols = self.__get_display_columns()
        for col in cols:
            self.__event_info =(col,item)
            self.event_generate('<<TreeviewInplaceEdit>>')
            if col in self._inplace_widgets:
                w = self._inplace_widgets[col]
                w.bind('<Key-Tab>',
                    lambda e: w.tk_focusNext().focus_set())
                w.bind('<Shift-Key-Tab>',
                    lambda e: w.tk_focusPrev().focus_set())
690081
def showGridRows( self ):
        
        delegate = self.itemDelegate()
        if ( isinstance(delegate, XTreeWidgetDelegate) ):
            return delegate.showGridRows()
        return None
31427
def iter_insert_items(tree):
    
    if tree.list_values:
        keys = tree.attrs
        for values in tree.list_values:
            if len(keys) != len(values):
                raise SyntaxError(
                    "Values '%s' do not match attributes " "'%s'" % (values, keys)
                )
            yield dict(zip(keys, map(resolve, values)))
    elif tree.map_values:
        for item in tree.map_values:
            data = {}
            for (key, val) in item:
                data[key] = resolve(val)
            yield data
    else:
        raise SyntaxError("No insert data found")
1309540
static  function toTree($list,$parent_field = 'parent_id',$id_field='id',$children_field='children') {
        $map = self::groupBy($list);
        $data=[];
        foreach ($list as $item) {
            $item->text=$item->name;
            if(is_object($item)){
                if(!$item->$parent_field){
                    $item->$children_field=$map[$item->$id_field];
                    $data[]=$item;
                }
            }
        }
        return $data;
    }
1212769
def OnRightClickListctrl(self, event):
        
        i = event.GetIndex()
        fit,spec = self.fit_list[i][0],self.fit_list[i][1]
        if fit in self.parent.bad_fits:
            if not self.parent.mark_fit_good(fit,spec=spec): return
            if i == self.current_fit_index:
                self.logger.SetItemBackgroundColour(i,"LIGHT BLUE")
            else:
                self.logger.SetItemBackgroundColour(i,"WHITE")
        else:
            if not self.parent.mark_fit_bad(fit): return
            if i == self.current_fit_index:
                self.logger.SetItemBackgroundColour(i,"red")
            else:
                self.logger.SetItemBackgroundColour(i,"red")
        self.parent.calculate_high_levels_data()
        self.parent.plot_high_levels_data()
        self.logger_focus(i)
1373878
private void setListEnabled(CmsList<? extends I_CmsListItem> list, boolean enabled, String disabledReason) {

        for (Widget child : list) {
            CmsTreeItem treeItem = (CmsTreeItem)child;
            if (enabled) {
                treeItem.getCheckBox().enable();
            } else {
                treeItem.getCheckBox().disable(disabledReason);
            }
            setListEnabled(treeItem.getChildren(), enabled, disabledReason);
        }
    }