Return (first column model index, last column model index) tuple for a configTreeItem
425559
def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem?
        
        if not treeItem:
            return (QtCore.QModelIndex(), QtCore.QModelIndex())

        if not treeItem.parentItem: # TODO: only necessary because of childNumber?
            return (QtCore.QModelIndex(), QtCore.QModelIndex())

        # Is there a bug in Qt in QStandardItemModel::indexFromItem?
        # It passes the parent in createIndex. TODO: investigate

        row =  treeItem.childNumber()
        return (self.createIndex(row, 0, treeItem),
                self.createIndex(row, self.columnCount() - 1, treeItem))
919261
def _retrieve_indices(cols):
        '''
        
        '''
        if isinstance(cols, int):
            return [cols]
        elif isinstance(cols, slice):
            start = cols.start if cols.start else 0
            stop = cols.stop
            step = cols.step if cols.step else 1
            return list(range(start, stop, step))
        elif isinstance(cols, list) and cols:
            if isinstance(cols[0], bool):
                return np.flatnonzero(np.asarray(cols))
            elif isinstance(cols[0], int):
                return cols
        else:
            raise TypeError('No valid column specifier. Only a scalar, list or slice of all'
                            'integers or a boolean mask are allowed.')
728838
def selectedIndexes(self):
        """"""
        model = self.model()
        indexes = []
        for comp in self._selectedComponents:
            index = model.indexByComponent(comp)
            if index is None:
                # must have been removed from model, discard
                self._selectedComponents.remove(comp)
            else:
                indexes.append(index)
        return indexes
350105
def get_model_indexes(model, add_reserver_flag=True):
    
    import uliweb.orm as orm
    from sqlalchemy.engine.reflection import Inspector

    indexes = []
    engine = model.get_engine().engine
    insp = Inspector.from_engine(engine)
    for index in insp.get_indexes(model.tablename):
        d = {}
        d['name'] = index['name']
        d['unique'] = index['unique']
        d['fields'] = index['column_names']
        if add_reserver_flag:
            d['_reserved'] = True
        indexes.append(d)

    return indexes
957564
def indexables(self):
        
        if self._indexables is None:

            self._indexables = []

            # index columns
            self._indexables.extend([
                IndexCol(name=name, axis=axis, pos=i)
                for i, (axis, name) in enumerate(self.attrs.index_cols)
            ])

            # values columns
            dc = set(self.data_columns)
            base_pos = len(self._indexables)

            def f(i, c):
                klass = DataCol
                if c in dc:
                    klass = DataIndexableCol
                return klass.create_for_block(i=i, name=c, pos=base_pos + i,
                                              version=self.version)

            self._indexables.extend(
                [f(i, c) for i, c in enumerate(self.attrs.values_cols)])

        return self._indexables
418848
def create_indexer(indexes: list):
    """"""

    if len(indexes) == 1:
        index = indexes[0]
        return lambda x: (x[index],)
    else:
        return itemgetter(*indexes)
1214286
def flags(self, index):
        """"""
        # This method was implemented in CollectionsModel only, but to enable
        # tuple exploration (even without editing), this method was moved here
        if not index.isValid():
            return Qt.ItemIsEnabled
        return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|
                            Qt.ItemIsEditable)
1078963
def _last_index(x, default_dim):
  """"""
  if x.get_shape().ndims is not None:
    return len(x.get_shape()) - 1
  else:
    return default_dim
1319532
def ColumnItem(name='', key=None, **kwargs):
    ''
    return Column(name,
            expr=key if key is not None else name,
            getter=lambda col,row: getitemdef(row, col.expr),
            setter=lambda col,row,val: setitem(row, col.expr, val),
            **kwargs)
563175
def itertuples(self, index=True, name='Raccoon'):
        
        fields = [self._index_name] if index else list()
        fields.extend(self._columns)
        row_tuple = namedtuple(name, fields)
        for i in range(len(self._index)):
            row = {self._index_name: self._index[i]} if index else dict()
            for c, col in enumerate(self._columns):
                row[col] = self._data[c][i]
            yield row_tuple(**row)
238966
def prior_model_tuples(self):
        
        return list(filter(lambda t: isinstance(t[1], AbstractPriorModel), self.__dict__.items()))
54813
def _extract_multi_indexer_columns(self, header, index_names, col_names,
                                       passed_names=False):
        
        if len(header) < 2:
            return header[0], index_names, col_names, passed_names

        # the names are the tuples of the header that are not the index cols
        # 0 is the name of the index, assuming index_col is a list of column
        # numbers
        ic = self.index_col
        if ic is None:
            ic = []

        if not isinstance(ic, (list, tuple, np.ndarray)):
            ic = [ic]
        sic = set(ic)

        # clean the index_names
        index_names = header.pop(-1)
        index_names, names, index_col = _clean_index_names(index_names,
                                                           self.index_col,
                                                           self.unnamed_cols)

        # extract the columns
        field_count = len(header[0])

        def extract(r):
            return tuple(r[i] for i in range(field_count) if i not in sic)

        columns = lzip(*[extract(r) for r in header])
        names = ic + columns

        # If we find unnamed columns all in a single
        # level, then our header was too long.
        for n in range(len(columns[0])):
            if all(compat.to_str(c[n]) in self.unnamed_cols for c in columns):
                raise ParserError(
                    "Passed header=[{header}] are too many rows for this "
                    "multi_index of columns"
                    .format(header=','.join(str(x) for x in self.header))
                )

        # Clean the column names (if we have an index_col).
        if len(ic):
            col_names = [r[0] if (len(r[0]) and
                                  r[0] not in self.unnamed_cols) else None
                         for r in header]
        else:
            col_names = [None] * len(header)

        passed_names = True

        return names, index_names, col_names, passed_names
736917
def item(self, index: int) -> Optional[Attr]:
        """"""
        if 0 <= index < len(self):
            return self._dict[tuple(self._dict.keys())[index]]
        return None
815798
def _slice(self, slicer):
        
        if isinstance(slicer, tuple):
            col, loc = slicer
            if not com.is_null_slice(col) and col != 0:
                raise IndexError("{0} only contains one item".format(self))
            return self.values[loc]
        return self.values[slicer]
114807
def get_order(self):
        
        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]
341654
def index_tuple(self,tables_dict,index,is_set):
    ""
    if not self.aonly_resolved: raise RuntimeError('resolve_aonly() before querying nix')
    with tables_dict.tempkeys():
      tables_dict.update(self.aonly) # todo: find spec support for aliases overwriting existing tables. (more likely, it's an error)
      index = index.name if isinstance(index,sqparse2.NameX) else index
      if isinstance(index,basestring):
        candidates = [t for t in self.table_order if any(f.name==index for f in tables_dict[t].fields)]
        if len(candidates)!=1: raise ColumnNameError(("ambiguous_column" if candidates else "no_such_column"),index)
        tname, = candidates
        return self.table_order.index(tname), tables_dict[tname].lookup(index).index
      elif isinstance(index,sqparse2.AttrX):
        if index.parent.name not in self.aliases: raise TableNameError('table_notin_x',index.parent,self.aliases)
        tname = self.aliases[index.parent.name]
        tindex = self.table_order.index(tname)
        if isinstance(index.attr,sqparse2.AsterX):
          if is_set: raise ValueError('cant_set_asterisk') # todo: better error class
          else: return (tindex,)
        else: return (tindex,tables_dict[tname].lookup(index.attr).index)
        # todo: stronger typing here. make sure both fields of the AttrX are always strings.
      else: raise TypeError(type(index)) # pragma: no cover
911140
def indexXY(self, index):
        
        # just want the top left of row selected
        row = index.row()
        if row == -1:
            row = self.model().rowCount()
        y = self.rowHeight(0)*row
        return 0, y