def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return 'Min: %r\nMax: %r' % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return '%s  Mode: %s' % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        cols = [to_text_string(c) for c in cols]
        return 'Column names: ' + ', '.join(list(cols))
    if is_binary_string(value):
        try:
            value = to_text_string(value, 'utf8')
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + ' ...'
    return value
Exemple #2
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     value = self.get_value(index)
     if is_binary_string(value):
         try:
             value = to_text_string(value, 'utf8')
         except:
             pass
     if role == Qt.DisplayRole:
         if value is np.ma.masked:
             return ''
         else:
             return to_qvariant(self._format % value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
       and value is not np.ma.masked:
         hue = self.hue0+\
               self.dhue*(self.vmax-self.color_func(value)) \
               /(self.vmax-self.vmin)
         hue = float(np.abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
         return to_qvariant(color)
     elif role == Qt.FontRole:
         return to_qvariant(get_font('arrayeditor'))
     return to_qvariant()
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return 'Min: %r\nMax: %r' % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return '%s  Mode: %s' % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        cols = [to_text_string(c) for c in cols]
        return 'Column names: ' + ', '.join(list(cols))
    if is_binary_string(value):
        try:
            value = to_text_string(value, 'utf8')
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + ' ...'
    return value
Exemple #4
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     value = self.get_value(index)
     if is_binary_string(value):
         try:
             value = to_text_string(value, 'utf8')
         except:
             pass
     if role == Qt.DisplayRole:
         if value is np.ma.masked:
             return ''
         else:
             return to_qvariant(self._format % value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
       and value is not np.ma.masked:
         hue = self.hue0+\
               self.dhue*(self.vmax-self.color_func(value)) \
               /(self.vmax-self.vmin)
         hue = float(np.abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
         return to_qvariant(color)
     elif role == Qt.FontRole:
         return to_qvariant(get_font('arrayeditor'))
     return to_qvariant()
Exemple #5
0
    def __init__(self,
                 text,
                 title='',
                 font=None,
                 parent=None,
                 readonly=False,
                 size=(400, 300)):
        QDialog.__init__(self, parent)

        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.text = None

        # Display text as unicode if it comes as bytes, so users see
        # its right representation
        if is_binary_string(text):
            self.is_binary = True
            text = to_text_string(text, 'utf8')
        else:
            self.is_binary = False

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # Text edit
        self.edit = QTextEdit(parent)
        self.edit.textChanged.connect(self.text_changed)
        self.edit.setReadOnly(readonly)
        self.edit.setPlainText(text)
        if font is None:
            font = get_font('texteditor')
        self.edit.setFont(font)
        self.layout.addWidget(self.edit)

        # Buttons configuration
        buttons = QDialogButtonBox.Ok
        if not readonly:
            buttons = buttons | QDialogButtonBox.Cancel
        bbox = QDialogButtonBox(buttons)
        bbox.accepted.connect(self.accept)
        bbox.rejected.connect(self.reject)
        self.layout.addWidget(bbox)

        # Make the dialog act as a window
        self.setWindowFlags(Qt.Window)

        self.setWindowIcon(ima.icon('edit'))
        self.setWindowTitle(_("Text editor") + \
                            "%s" % (" - "+str(title) if str(title) else ""))
        self.resize(size[0], size[1])
Exemple #6
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    try:
        if isinstance(value, recarray):
            fields = value.names
            display = 'Field names: ' + ', '.join(fields)
        elif minmax and isinstance(value, (ndarray, MaskedArray)):
            if value.size == 0:
                display = repr(value)
            try:
                display = 'Min: %r\nMax: %r' % (value.min(), value.max())
            except TypeError:
                pass
            except ValueError:
                # Happens when one of the array cell contains a sequence
                pass
        elif isinstance(value, (list, tuple, dict, set)):
            display = CollectionsRepr.repr(value)
        elif isinstance(value, Image):
            display = '%s  Mode: %s' % (address(value), value.mode)
        elif isinstance(value, DataFrame):
            cols = value.columns
            if PY2 and len(cols) > 0:
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                except:
                    ini_col = to_text_string(cols[0])
                cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
            else:
                cols = [to_text_string(c) for c in cols]
            display = 'Column names: ' + ', '.join(list(cols))
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
        elif is_binary_string(value):
            try:
                display = to_text_string(value, 'utf8')
            except:
                pass
        elif is_text_string(value):
            display = value
        else:
            display = repr(value)
            if truncate and len(display) > trunc_len:
                display = display[:trunc_len].rstrip() + ' ...'
    except:
        display = to_text_string(type(value))

    return display
Exemple #7
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    try:
        if isinstance(value, recarray):
            fields = value.names
            display = 'Field names: ' + ', '.join(fields)
        elif minmax and isinstance(value, (ndarray, MaskedArray)):
            if value.size == 0:
                display = repr(value)
            try:
                display = 'Min: %r\nMax: %r' % (value.min(), value.max())
            except TypeError:
                pass
            except ValueError:
                # Happens when one of the array cell contains a sequence
                pass
        elif isinstance(value, (list, tuple, dict, set)):
            display = CollectionsRepr.repr(value)
        elif isinstance(value, Image):
            display = '%s  Mode: %s' % (address(value), value.mode)
        elif isinstance(value, DataFrame):
            cols = value.columns
            if PY2 and len(cols) > 0:
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                except:
                    ini_col = to_text_string(cols[0])
                cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
            else:
                cols = [to_text_string(c) for c in cols]
            display = 'Column names: ' + ', '.join(list(cols))
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
        elif is_binary_string(value):
            try:
                display = to_text_string(value, 'utf8')
            except:
                pass
        elif is_text_string(value):
            display = value
        else:
            display = repr(value)
            if truncate and len(display) > trunc_len:
                display = display[:trunc_len].rstrip() + ' ...'
    except:
        display = to_text_string(type(value))

    return display
Exemple #8
0
    def __init__(self, text, title='', font=None, parent=None,
                 readonly=False, size=(400, 300)):
        QDialog.__init__(self, parent)
        
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)
        
        self.text = None
        
        # Display text as unicode if it comes as bytes, so users see 
        # its right representation
        if is_binary_string(text):
            self.is_binary = True
            text = to_text_string(text, 'utf8')
        else:
            self.is_binary = False
        
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # Text edit
        self.edit = QTextEdit(parent)
        self.edit.textChanged.connect(self.text_changed)
        self.edit.setReadOnly(readonly)
        self.edit.setPlainText(text)
        if font is None:
            font = get_font()
        self.edit.setFont(font)
        self.layout.addWidget(self.edit)

        # Buttons configuration
        buttons = QDialogButtonBox.Ok
        if not readonly:
            buttons = buttons | QDialogButtonBox.Cancel
        bbox = QDialogButtonBox(buttons)
        bbox.accepted.connect(self.accept)
        bbox.rejected.connect(self.reject)
        self.layout.addWidget(bbox)
        
        # Make the dialog act as a window
        self.setWindowFlags(Qt.Window)
        
        self.setWindowIcon(ima.icon('edit'))
        self.setWindowTitle(_("Text editor") + \
                            "%s" % (" - "+str(title) if str(title) else ""))
        self.resize(size[0], size[1])
def to_unicode_from_fs(string):
    """
    Return a unicode version of string decoded using the file system encoding.
    """
    if not is_string(string):  # string is a QString
        string = to_text_string(string.toUtf8(), "utf-8")
    else:
        if is_binary_string(string):
            try:
                unic = string.decode(FS_ENCODING)
            except (UnicodeError, TypeError):
                pass
            else:
                return unic
    return string
Exemple #10
0
def to_unicode_from_fs(string):
    """
    Return a unicode version of string decoded using the file system encoding.
    """
    if not is_string(string):  # string is a QString
        string = to_text_string(string.toUtf8(), 'utf-8')
    else:
        if is_binary_string(string):
            try:
                unic = string.decode(FS_ENCODING)
            except (UnicodeError, TypeError):
                pass
            else:
                return unic
    return string
Exemple #11
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return "Min: %r\nMax: %r" % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return "%s  Mode: %s" % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        if PY2 and cols:
            # Get rid of possible BOM utf-8 data present at the
            # beginning of a file, which gets attached to the first
            # column header when headers are present in the first
            # row.
            # Fixes Issue 2514
            try:
                ini_col = to_text_string(cols[0], encoding="utf-8-sig")
            except:
                ini_col = to_text_string(cols[0])
            cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
        else:
            cols = [to_text_string(c) for c in cols]
        return "Column names: " + ", ".join(list(cols))
    if isinstance(value, NavigableString):
        # Fixes Issue 2448
        return to_text_string(value)
    if is_binary_string(value):
        try:
            value = to_text_string(value, "utf8")
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + " ..."
    return value
Exemple #12
0
def display_to_value(value, default_value, ignore_errors=True):
    """Convert back to value"""
    from qtpy.compat import from_qvariant
    value = from_qvariant(value, to_text_string)
    try:
        np_dtype = get_numpy_dtype(default_value)
        if isinstance(default_value, bool):
            # We must test for boolean before NumPy data types
            # because `bool` class derives from `int` class
            try:
                value = bool(float(value))
            except ValueError:
                value = value.lower() == "true"
        elif np_dtype is not None:
            if 'complex' in str(type(default_value)):
                value = np_dtype(complex(value))
            else:
                value = np_dtype(value)
        elif is_binary_string(default_value):
            value = to_binary_string(value, 'utf8')
        elif is_text_string(default_value):
            value = to_text_string(value)
        elif isinstance(default_value, complex):
            value = complex(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            try:
                value = int(value)
            except ValueError:
                value = float(value)
        elif isinstance(default_value, datetime.datetime):
            value = datestr_to_datetime(value)
        elif isinstance(default_value, datetime.date):
            value = datestr_to_datetime(value).date()
        elif ignore_errors:
            value = try_to_eval(value)
        else:
            value = eval(value)
    except (ValueError, SyntaxError):
        if ignore_errors:
            value = try_to_eval(value)
        else:
            return default_value
    return value
Exemple #13
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    try:
        if isinstance(value, recarray):
            fields = value.names
            display = 'Field names: ' + ', '.join(fields)
        elif isinstance(value, MaskedArray):
            display = 'Masked array'
        elif isinstance(value, ndarray):
            if minmax:
                try:
                    display = 'Min: %r\nMax: %r' % (value.min(), value.max())
                except (TypeError, ValueError):
                    display = repr(value)
            else:
                display = repr(value)
        elif isinstance(value, ndarray):
            display = repr(value)
        elif isinstance(value, (list, tuple, dict, set)):
            display = CollectionsRepr.repr(value)
        elif isinstance(value, Image):
            display = '%s  Mode: %s' % (address(value), value.mode)
        elif isinstance(value, DataFrame):
            cols = value.columns
            if PY2 and len(cols) > 0:
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                except:
                    ini_col = to_text_string(cols[0])
                cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
            else:
                cols = [to_text_string(c) for c in cols]
            display = 'Column names: ' + ', '.join(list(cols))
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
        elif is_binary_string(value):
            try:
                display = to_text_string(value, 'utf8')
            except:
                display = value
        elif is_text_string(value):
            display = value
        elif isinstance(value, NUMERIC_TYPES) or isinstance(value, bool) or \
          isinstance(value, datetime.date):
            display = repr(value)
        else:
            # Note: Don't trust on repr's. They can be inefficient and
            # so freeze Spyder quite easily
            # display = repr(value)
            type_str = to_text_string(type(value))
            display = type_str[1:-1]
            if truncate and len(display) > trunc_len:
                display = display[:trunc_len].rstrip() + ' ...'
    except:
        type_str = to_text_string(type(value))
        display = type_str[1:-1]

    return display