Ignore:
Files:
25 edited

Legend:

Unmodified
Added
Removed
  • Orange/OrangeCanvas/orngSignalManager.py

    r10996 r11461  
    1010 
    1111import __builtin__ 
     12 
     13from collections import deque 
    1214 
    1315import orange 
     
    617619        skipWidgets = self.getBlockedWidgets() # Widgets that are blocking 
    618620         
    619          
     621        self.addEvent("Blocked widgets %s." % 
     622                      [w.captionTitle for w in skipWidgets], 
     623                      eventVerbosity=2) 
    620624        # start propagating 
    621625        self.signalProcessingInProgress = 1 
     
    680684        # there is no link... 
    681685        return 0 
    682      
    683686 
    684687    def widgetDescendants(self, widget): 
    685         """ Return all widget descendants of `widget` 
    686         """ 
    687         queue = [widget] 
    688         queue_set = set(queue) 
    689          
    690         index = self.widgets.index(widget) 
    691         for i in range(index, len(self.widgets)): 
    692             widget = self.widgets[i] 
    693             if widget not in queue: 
    694                 continue 
    695             linked = [link.widgetTo for link in self.links.get(widget, []) if link.enabled] 
     688        """ Return all widget descendants of `widget`. 
     689 
     690        .. note:: 
     691            Includes only widgets which are reachable by *enabled* links. 
     692 
     693        """ 
     694        queue = deque([widget]) 
     695        descendants = set() 
     696 
     697        while queue: 
     698            w = queue.popleft() 
     699            linked = [link.widgetTo for link in self.links.get(widget, []) 
     700                      if link.enabled] 
    696701            for w in linked: 
    697                 if w not in queue_set: 
    698                     queue.append(widget) 
    699                     queue_set.add(widget) 
    700         return queue 
    701      
    702      
     702                if w not in descendants: 
     703                    queue.append(w) 
     704                    descendants.add(w) 
     705 
     706        return list(descendants) 
     707 
    703708    def isWidgetBlocked(self, widget): 
    704709        """ Is this widget or any of its up-stream connected widgets blocked. 
     
    707712            return True 
    708713        else: 
    709             widgets = [link.widgetFrom for link in self.getLinks(None, widget, None, None)] 
    710             if widgets: 
    711                 return any(self.isWidgetBlocked(w) for w in widgets) 
    712             else: 
    713                 return False 
    714              
    715              
     714            widgets = [link.widgetFrom 
     715                       for link in self.getLinks(None, widget, None, None) 
     716                       if link.enabled] 
     717            return any(self.isWidgetBlocked(w) for w in widgets) 
     718 
    716719    def getBlockedWidgets(self): 
    717720        """ Return a set of all widgets that are blocked. 
     
    720723        for w in self.widgets: 
    721724            if w not in blocked and w.isBlocking(): 
    722                 blocked.update(self.widgetDescendants(w)) 
     725                blocked.update(set([w]).union(set(self.widgetDescendants(w)))) 
    723726        return blocked 
    724      
    725                  
     727 
    726728    def freeze(self, widget=None): 
    727729        """ Return a context manager that freezes the signal processing 
  • Orange/OrangeWidgets/OWBaseWidget.py

    r11296 r11458  
    460460### 
    461461                settings[contextHandler.localContextName+"Version"] = (contextStructureVersion, contextHandler.contextDataVersion) 
    462              
     462 
    463463        return settings 
    464464 
     465    def getDefaultSettingsFilename(self): 
     466        fs_encoding = sys.getfilesystemencoding() 
     467        basename = self.captionTitle + ".ini" 
     468        filename = os.path.join( 
     469            self.widgetSettingsDir,  # is assumed to be a str in FS encoding 
     470            basename.encode(fs_encoding)) 
     471        return filename 
    465472 
    466473    def getSettingsFile(self, file): 
    467         if file==None: 
    468             file = os.path.join(self.widgetSettingsDir, self.captionTitle + ".ini") 
     474        if file is None: 
     475            file = self.getDefaultSettingsFilename() 
     476 
    469477            if not os.path.exists(file): 
    470478                try: 
     
    473481                    f.close() 
    474482                except IOError: 
    475                     return  
     483                    return 
    476484        if isinstance(file, basestring): 
    477485            if os.path.exists(file): 
     
    523531        settings = self.getSettings(globalContexts=True) 
    524532        if settings: 
    525             if file==None: 
    526                 file = os.path.join(self.widgetSettingsDir, self.captionTitle + ".ini") 
     533            if file is None: 
     534                file = self.getDefaultSettingsFilename() 
     535 
    527536            if isinstance(file, basestring): 
    528537                file = open(file, "w") 
  • Orange/OrangeWidgets/Regression/OWEarth.py

    r11217 r11455  
    1414from Orange.regression import earth 
    1515from orngWrap import PreprocessedLearner 
    16   
     16 
     17 
    1718class OWEarth(OWWidget): 
    1819    settingsList = ["name", "degree", "terms", "penalty"] 
     
    2021    def __init__(self, parent=None, signalManager=None, 
    2122                 title="Earth"): 
    22         OWWidget.__init__(self, parent, signalManager, title, wantMainArea=False) 
     23        OWWidget.__init__(self, parent, signalManager, title, 
     24                          wantMainArea=False) 
    2325 
    2426        self.inputs = [("Data", Orange.data.Table, self.set_data), 
    25                        ("Preprocessor", PreprocessedLearner, self.set_preprocessor)] 
     27                       ("Preprocessor", PreprocessedLearner, 
     28                        self.set_preprocessor)] 
    2629 
    2730        self.outputs = [("Learner", earth.EarthLearner, Default), 
     
    4043        ##### 
    4144 
    42         OWGUI.lineEdit(self.controlArea, self, "name",  
     45        OWGUI.lineEdit(self.controlArea, self, "name", 
    4346                       box="Learner/Classifier Name", 
    4447                       tooltip="Name for the learner/predictor") 
     
    4649        box = OWGUI.widgetBox(self.controlArea, "Forward Pass", addSpace=True) 
    4750        OWGUI.spin(box, self, "degree", 1, 3, step=1, 
    48                    label="Max. term degree",  
    49                    tooltip="Maximum degree of the terms derived (number of hinge functions).") 
     51                   label="Max. term degree", 
     52                   tooltip="Maximum degree of the terms derived " 
     53                           "(number of hinge functions).") 
    5054        s = OWGUI.spin(box, self, "terms", 1, 200, step=1, 
    5155                       label="Max. terms", 
    52                        tooltip="Maximum number of terms derived in the forward pass.") 
     56                       tooltip="Maximum number of terms derived in the " 
     57                               "forward pass.") 
    5358        s.control.setSpecialValueText("Automatic") 
    5459 
     
    7681 
    7782    def apply(self): 
    78         learner = earth.EarthLearner(degree=self.degree, 
    79                                     terms=self.terms if self.terms >= 2 else None, 
    80                                     penalty=self.penalty, 
    81                                     name=self.name) 
     83        learner = earth.EarthLearner( 
     84            degree=self.degree, 
     85            terms=self.terms if self.terms >= 2 else None, 
     86            penalty=self.penalty, 
     87            name=self.name) 
     88 
    8289        predictor = None 
    8390        basis_matrix = None 
     
    93100                self.error(0, "An error during learning: %r" % ex) 
    94101 
    95             if predictor is not None:      
     102            if predictor is not None: 
    96103                base_features = predictor.base_features() 
    97                 basis_domain = Orange.data.Domain(base_features,  
    98                                                   self.data.domain.class_var) 
     104                basis_domain = Orange.data.Domain( 
     105                    base_features, 
     106                    self.data.domain.class_var, 
     107                    self.data.domain.class_vars) 
     108                basis_domain.add_metas(self.data.domain.get_metas()) 
    99109                basis_matrix = Orange.data.Table(basis_domain, self.data) 
    100110 
     
    104114 
    105115    def sendReport(self): 
    106         self.reportSettings("Learning parameters",  
    107                             [("Degree", self.degree), 
    108                              ("Terms", self.terms if self.terms >= 2 else "Automatic"), 
    109                              ("Knot penalty", "%.2f" % self.penalty) 
    110                              ]) 
     116        self.reportSettings( 
     117            "Learning parameters", 
     118            [("Degree", self.degree), 
     119             ("Terms", self.terms if self.terms >= 2 else "Automatic"), 
     120             ("Knot penalty", "%.2f" % self.penalty) 
     121             ]) 
     122 
    111123        self.reportData(self.data) 
    112124 
  • Orange/OrangeWidgets/Unsupervised/OWPCA.py

    r11217 r11454  
    109109        cutoff = curve_data[0][0] 
    110110        return x1 < cutoff and cutoff < x2 
     111 
    111112 
    112113class CutoffCurve(OWCurve): 
     
    297298 
    298299    def apply(self): 
    299         """Apply PCA on input data, caching the full projection, 
    300         then updating the selected components. 
    301          
     300        """ 
     301        Apply PCA on input data, caching the full projection and 
     302        updating the selected components. 
     303 
    302304        """ 
    303305        pca = self.construct_pca_all_comp() 
     
    347349                                         variance_sum=variance_sum) 
    348350        projected_data = projector(self.data) 
     351 
     352        append_metas(projected_data, self.data) 
     353 
    349354        eigenvectors = self.eigenvectors_as_table(components) 
    350355 
     
    448453 
    449454 
     455def append_metas(dest, source): 
     456    """ 
     457    Append all meta attributes from the `source` table to `dest` table. 
     458    The tables must be of the same length. 
     459 
     460    :param dest: 
     461        An data table into which the meta values will be copied. 
     462    :type dest: :class:`Orange.data.Table` 
     463 
     464    :param source: 
     465        A data table with the meta attributes/values to be copied into `dest`. 
     466    :type source: :class:`Orange.data.Table` 
     467 
     468    """ 
     469    if len(dest) != len(source): 
     470        raise ValueError("'dest' and 'source' must have the same length.") 
     471 
     472    dest.domain.add_metas(source.domain.get_metas()) 
     473    for dest_inst, source_inst in zip(dest, source): 
     474        for meta_id, val in source_inst.get_metas().items(): 
     475            dest_inst[meta_id] = val 
     476 
     477 
    450478if __name__ == "__main__": 
    451479    app = QApplication(sys.argv) 
  • Orange/classification/__init__.py

    r11051 r11459  
    1818    def __new__(cls, data=None, **kwds): 
    1919        learner = object.__new__(cls) 
    20         if data: 
     20        if data is not None: 
    2121            learner.__init__(**kwds) # force init 
    2222            return learner(data) 
  • Orange/classification/bayes.py

    r10580 r11459  
    4545    """ 
    4646     
    47     def __new__(cls, data = None, weight_id = 0, **argkw): 
     47    def __new__(cls, data=None, weight_id=0, **argkw): 
    4848        self = Orange.classification.Learner.__new__(cls, **argkw) 
    49         if data: 
     49        if data is not None: 
    5050            self.__init__(**argkw) 
    5151            return self.__call__(data, weight_id) 
  • Orange/classification/logreg.py

    r11398 r11459  
    106106    def __new__(cls, data=None, weight_id=0, **argkw): 
    107107        self = Orange.classification.Learner.__new__(cls, **argkw) 
    108         if data: 
     108        if data is not None: 
    109109            self.__init__(**argkw) 
    110110            return self.__call__(data, weight_id) 
     
    183183    def __new__(cls, data=None, **argkw): 
    184184        self = Orange.classification.Learner.__new__(cls, **argkw) 
    185         if data: 
     185        if data is not None: 
    186186            self.__init__(**argkw) 
    187187            return self.__call__(data) 
     
    221221    def __new__(cls, data=None, weight_id=0, **argkw): 
    222222        self = object.__new__(cls) 
    223         if data: 
     223        if data is not None: 
    224224            self.__init__(**argkw) 
    225225            return self.__call__(data, weight_id) 
     
    893893    def __new__(cls, data=None, **argkw): 
    894894        self = object.__new__(cls) 
    895         if data: 
     895        if data is not None: 
    896896            self.__init__(**argkw) 
    897897            return self.__call__(data) 
  • Orange/classification/tree.py

    r10959 r11459  
    15201520    def __new__(cls, instances=None, weightID=0, **argkw): 
    15211521        self = Orange.classification.Learner.__new__(cls, **cls._rename_dict(argkw)) 
    1522         if instances: 
     1522        if instances is not None: 
    15231523            self.__init__(**argkw) 
    15241524            return self.__call__(instances, weightID) 
     
    18641864    def __new__(cls, data=None, weightID=0, **argkw): 
    18651865        self = Orange.core.Learner.__new__(cls, **argkw) 
    1866         if data: 
     1866        if data is not None: 
    18671867            self.__init__(**argkw) 
    18681868            return self.__call__(data, weightID) 
  • Orange/distance/__init__.py

    r10580 r11459  
    3131        self = DistanceConstructor.__new__(cls, **argkw) 
    3232        self.__dict__.update(argkw) 
    33         if data: 
     33        if data is not None: 
    3434            return self.__call__(data) 
    3535        else: 
     
    7777        self = DistanceConstructor.__new__(cls, **argkw) 
    7878        self.__dict__.update(argkw) 
    79         if data: 
     79        if data is not None: 
    8080            return self.__call__(data) 
    8181        else: 
     
    121121        self = DistanceConstructor.__new__(cls, **argkw) 
    122122        self.__dict__.update(argkw) 
    123         if data: 
     123        if data is not None: 
    124124            return self.__call__(data) 
    125125        else: 
  • Orange/feature/imputation.py

    r10580 r11459  
    1818 
    1919class ImputeLearner(orange.Learner): 
    20     def __new__(cls, data = None, weight_id = 0, **keyw): 
     20    def __new__(cls, data=None, weight_id=0, **keyw): 
    2121        self = orange.Learner.__new__(cls, **keyw) 
    2222        self.dont_impute_classifier = False 
    2323        self.__dict__.update(keyw) 
    24         if data: 
     24        if data is not None: 
    2525            return self.__call__(data, weight_id) 
    2626        else: 
  • Orange/multilabel/br.py

    r10502 r11459  
    6767            self.base_learner = _BayesLearner 
    6868         
    69         if instances: 
     69        if instances is not None: 
    7070            self.__init__(**argkw) 
    7171            return self.__call__(instances, weight_id) 
  • Orange/multilabel/brknn.py

    r10502 r11459  
    8585        self.ext = ext 
    8686         
    87         if instances: 
     87        if instances is not None: 
    8888            self.instances = instances 
    8989            self.__init__(**argkw) 
  • Orange/multilabel/lp.py

    r10502 r11459  
    7676        self = _multibase.MultiLabelLearner.__new__(cls, **argkw) 
    7777         
    78         if instances: 
     78        if instances is not None: 
    7979            self.__init__(**argkw) 
    8080            return self.__call__(instances, base_learner, weight_id) 
  • Orange/multilabel/mlknn.py

    r10502 r11459  
    135135        self.smooth = smooth 
    136136         
    137         if instances: 
     137        if instances is not None: 
    138138            self.__init__(**argkw) 
    139139            return self.__call__(instances,weight_id) 
  • Orange/projection/linear.py

    r10863 r11459  
    11491149    def __new__(cls, freeviz=None, instances=None, weight_id=0, **argkw): 
    11501150        self = classification.Learner.__new__(cls, **argkw) 
    1151         if instances: 
     1151        if instances is not None: 
    11521152            self.__init__(freeviz, **argkw) 
    11531153            return self.__call__(instances, weight_id) 
     
    11761176    def __new__(cls, freeviz=None, instances=None, weight_id=0, **argkw): 
    11771177        self = classification.Learner.__new__(cls, **argkw) 
    1178         if instances: 
     1178        if instances is not None: 
    11791179            self.__init__(freeviz, **argkw) 
    11801180            return self.__call__(instances, weight_id) 
     
    13121312        optimizer = object.__new__(cls) 
    13131313 
    1314         if dataset: 
     1314        if dataset is not None: 
    13151315            optimizer.__init__(**kwds) 
    13161316            return optimizer(dataset) 
     
    16091609    def __new__(cls, dataset=None): 
    16101610        self = object.__new__(cls) 
    1611         if dataset: 
     1611        if dataset is not None: 
    16121612            self.__init__() 
    16131613            return self.__call__(dataset) 
  • Orange/tuning/__init__.py

    r10712 r11459  
    9595    def __new__(cls, data=None, weight_id=0, **argkw): 
    9696        self = Orange.classification.Learner.__new__(cls, **argkw) 
    97         if data: 
     97        if data is not None: 
    9898            for name, value in argkw.items(): 
    9999                setattr(self, name, value) 
     
    346346    def __new__(cls, data=None, weight_id=0, **kwds): 
    347347        self = Orange.classification.Learner.__new__(cls, **kwds) 
    348         if data: 
     348        if data is not None: 
    349349            self.__init__(**kwargs) 
    350350            return self.__call__(data, weight_id) 
     
    443443    def __new__(cls, data=None, weight_id=0, **kwds): 
    444444        self = Orange.classification.Learner.__new__(cls, **kwds) 
    445         if data: 
     445        if data is not None: 
    446446            self.__init__(**kwds) 
    447447            return self.__call__(data, weight_id) 
  • Orange/utils/__init__.py

    r10998 r11457  
    697697 
    698698import selection 
     699 
     700import render 
  • Orange/utils/environ.py

    r11410 r11456  
    9292""" 
    9393 
    94 import os, sys 
     94import os 
     95import sys 
     96 
    9597import ConfigParser 
    9698import pkg_resources 
    9799from pkg_resources import working_set 
    98100 
     101 
    99102def _path_fix(): 
    100     """ Fix some common problems with $(PATH) and sys.path 
     103    """Fix some common problems with $(PATH) and sys.path 
    101104    """ 
    102105    if os.name == "nt": 
    103106        ## Move any miktex paths containing Qt's dll to the end of the %PATH% 
    104107        paths = os.environ["PATH"].split(";") 
    105         paths.sort(lambda x,y: -1 if "PyQt4" in x else (1 if "miktex" in y and \ 
    106                         os.path.exists(os.path.join(y, "QtCore4.dll")) else 0)) 
     108        paths = sorted(paths, key=lambda path: 1 if "miktex" in path else 0) 
    107109        os.environ["PATH"] = ";".join(paths) 
    108          
     110 
    109111    if sys.platform == "darwin": 
    110112        ## PyQt4 installed from fink is installed in %{FINK_ROOT}lib/qt4-mac/lib/python${PYVERSION}/site-packages" 
    111         posible_fink_pyqt4_path = os.path.join(sys.prefix,  
    112                 "lib/qt4-mac/lib/python" + sys.version[:3] + "/site-packages") 
     113        posible_fink_pyqt4_path = os.path.join( 
     114            sys.prefix, "lib/qt4-mac/lib/python" + sys.version[:3] + "/site-packages") 
    113115        if os.path.exists(posible_fink_pyqt4_path): 
    114116            sys.path.append(posible_fink_pyqt4_path) 
    115              
     117 
    116118_path_fix() 
     119 
    117120 
    118121def _get_default_env(): 
  • Orange/utils/render.py

    r10633 r11457  
    77.. index:: 
    88   single: utils; render 
     9 
    910""" 
    1011 
    1112from __future__ import with_statement 
    1213 
     14import os 
    1315import sys 
     16import math 
     17import warnings 
     18import StringIO 
     19import gc 
     20import copy 
     21import binascii 
     22 
     23from functools import wraps 
     24from contextlib import contextmanager 
     25 
    1426import numpy 
    15 import math 
    16 import os.path 
    1727 
    1828from Orange.utils.environ import install_dir 
    1929 
    20 class GeneratorContextManager(object): 
    21    def __init__(self, gen): 
    22        self.gen = gen 
    23    def __enter__(self): 
    24        try: 
    25            return self.gen.next() 
    26        except StopIteration: 
    27            raise RuntimeError("generator didn't yield") 
    28    def __exit__(self, type, value, traceback): 
    29        if type is None: 
    30            try: 
    31                self.gen.next() 
    32            except StopIteration: 
    33                return 
    34            else: 
    35                raise RuntimeError("generator didn't stop") 
    36        else: 
    37            try: 
    38                self.gen.throw(type, value, traceback) 
    39                raise RuntimeError("generator didn't stop after throw()") 
    40            except StopIteration: 
    41                return True 
    42            except: 
    43                # only re-raise if it's *not* the exception that was 
    44                # passed to throw(), because __exit__() must not raise 
    45                # an exception unless __exit__() itself failed.  But 
    46                # throw() has to raise the exception to signal 
    47                # propagation, so this fixes the impedance mismatch  
    48                # between the throw() protocol and the __exit__() 
    49                # protocol. 
    50                # 
    51                if sys.exc_info()[1] is not value: 
    52                    raise 
    53  
    54 def contextmanager(func): 
    55     def helper(*args, **kwds): 
    56         return GeneratorContextManager(func(*args, **kwds)) 
    57     return helper 
    58  
    59 from functools import wraps 
     30 
     31def _pil_safe_import(module): 
     32 
     33    pil, module = module.split(".", 1) 
     34    if pil != "PIL": 
     35        raise ValueError("Expected a module name inside PIL namespace.") 
     36 
     37    if module in sys.modules: 
     38        # 'module' is already imported in the global namespace 
     39        pil_mod = sys.modules.get("PIL." + module) 
     40        if pil_mod is None: 
     41            # The PIL package was not yet imported. 
     42            try: 
     43                # Make sure "PIL" is in sys.modules 
     44                import PIL 
     45            except ImportError: 
     46                # PIL was installed as an egg (it's broken, 
     47                # PIL package can not be imported) 
     48                return None 
     49            # Insert 'module' into the PIL namespace 
     50            sys.modules["PIL." + module] = sys.modules[module] 
     51 
     52        return sys.modules["PIL." + module] 
     53 
     54    try: 
     55        mod = __import__("PIL." + module, fromlist=[module]) 
     56    except ImportError: 
     57        mod = None 
     58 
     59    if mod is not None: 
     60        sys.modules[module] = mod 
     61 
     62    return mod 
     63 
     64# scipy and matplotlib both import modules from PIL but depending 
     65# on the installed version might use different conventions, i.e. 
     66# 
     67# >>> import Image 
     68# >>> from PIL import Image 
     69# 
     70# This can crash the python interpreter with a: 
     71# AccessInit: hash collision: 3 for both 1 and 1 
     72# 
     73# (This is a known common problem with PIL imports and is triggered 
     74# in libImaging/Access.c:add_item) 
     75# 
     76# So we preempt the imports and use a hack where we manually insert 
     77# modules from PIL namespace into global namespace or vice versa 
     78# 
     79# PIL is imported by (as currently imported from Orange): 
     80#    - 'scipy.utils.pilutils' (PIL.Image and PIL.ImageFilter) 
     81#    - 'matplotlib.backend_bases' (PIL.Image) 
     82#    - 'matplotlib.image' (PIL.Image) 
     83# 
     84# Based on grep 'import _imaging PIL/*.py the following modules 
     85# import C extensions: 
     86#    - Image (_imaging) 
     87#    - ImageCms (_imagingcms) 
     88#    - ImageDraw (_imagingagg) 
     89#    - ImageFont (_imagingft) 
     90#    - ImageGL (_imaginggl) 
     91#    - ImageMath (_imagingmath) 
     92#    - ImageTk (_imagingtk) 
     93#    - GifImagePlugin (_imaging_gif) 
     94# 
     95# However only '_imaging' seems to cause the crash. 
     96 
     97 
     98_pil_safe_import("PIL._imaging") 
     99 
     100 
    60101def with_state(func): 
    61102    @wraps(func) 
     
    66107    return wrap 
    67108 
     109 
    68110def with_gc_disabled(func): 
    69     import gc 
    70111    def disabler(): 
    71112        gc.disable() 
     
    74115        finally: 
    75116            gc.enable() 
     117 
    76118    @wraps(func) 
    77119    def wrapper(*args, **kwargs): 
     
    84126    def __init__(self, colors, gamma=None, overflow=(255, 255, 255), underflow=(255, 255, 255), unknown=(0, 0, 0)): 
    85127        self.colors = colors 
    86         self.gamma_func = lambda x, gamma:((math.exp(gamma * math.log(2 * x - 1)) if x > 0.5 else -math.exp(gamma * math.log(-2 * x + 1)) if x != 0.5 else 0.0) + 1) / 2.0 
     128        self.gamma_func = lambda x, gamma: ((math.exp(gamma * math.log(2 * x - 1)) if x > 0.5 else -math.exp(gamma * math.log(-2 * x + 1)) if x != 0.5 else 0.0) + 1) / 2.0 
    87129        self.gamma = gamma 
    88130        self.overflow = overflow 
     
    100142            return self.overflow 
    101143        elif index == len(self.colors) - 1: 
    102             return tuple(self.colors[-1][i] for i in range(3)) # self.colors[-1].green(), self.colors[-1].blue()) 
     144            return tuple(self.colors[-1][i] for i in range(3))  # self.colors[-1].green(), self.colors[-1].blue()) 
    103145        else: 
    104             red1, green1, blue1 = [self.colors[index][i] for i in range(3)] #, self.colors[index].green(), self.colors[index].blue() 
    105             red2, green2, blue2 = [self.colors[index + 1][i] for i in range(3)] #, self.colors[index + 1].green(), self.colors[index + 1].blue() 
     146            red1, green1, blue1 = [self.colors[index][i] for i in range(3)]  # , self.colors[index].green(), self.colors[index].blue() 
     147            red2, green2, blue2 = [self.colors[index + 1][i] for i in range(3)]  # , self.colors[index + 1].green(), self.colors[index + 1].blue() 
    106148            x = val * (len(self.colors) - 1) - index 
    107149            if gamma is not None: 
     
    112154        return self.get_rgb(val, gamma) 
    113155 
     156 
    114157def as_open_file(file, mode="rb"): 
    115158    if isinstance(file, basestring): 
    116159        file = open(file, mode) 
    117     else: # assuming it is file like with proper mode, could check for write, read 
     160    else:  # assuming it is file like with proper mode, could check for write, read 
    118161        pass 
    119162    return file 
     163 
    120164 
    121165class Renderer(object): 
     
    188232 
    189233    def save_render_state(self): 
    190         import copy 
    191234        self.render_state_stack.append(copy.deepcopy(self.render_state)) 
    192235 
     
    237280 
    238281    def string_size_hint(self, text, **kwargs): 
    239         raise NotImpemented 
     282        raise NotImplemented 
    240283 
    241284    @contextmanager 
     
    258301        pass 
    259302 
     303 
    260304class EPSRenderer(Renderer): 
    261     EPS_DRAW_RECT = """/draw_rect  
     305    EPS_DRAW_RECT = """/draw_rect 
    262306{/h exch def /w exch def 
    263307 /y exch def /x exch def 
     
    299343  0 rmoveto 
    300344  show } def 
    301    
     345 
    302346/right_align_show 
    303347{ dup stringwidth pop 
     
    306350  show } def 
    307351""" 
     352 
    308353    def __init__(self, width, height): 
    309354        Renderer.__init__(self, width, height) 
    310         from StringIO import StringIO 
    311         self._eps = StringIO() 
     355        self._eps = StringIO.StringIO() 
    312356        self._eps.write("%%!PS-Adobe-3.0 EPSF-3.0\n%%%%BoundingBox: 0 0 %i %i\n" % (width, height)) 
    313357        self._eps.write(self.EPS_SHOW_FUNCTIONS) 
     
    315359        self.set_font(*self.render_state["font"]) 
    316360        self._inline_func = dict(stroke_color=lambda color: "%f %f %f setrgbcolor" % tuple(255.0 / c for c in color), 
    317                                  fill_color=lambda color:"%f %f %f setrgbcolor" % tuple(255.0 / c for c in color), 
     361                                 fill_color=lambda color: "%f %f %f setrgbcolor" % tuple(255.0 / c for c in color), 
    318362                                 stroke_width=lambda w: "%f setlinewidth" % w) 
    319363 
     
    330374        (x1, y1, x2, y2), samples = gradient 
    331375        binary = "".join([chr(int(c)) for p, s in samples for c in s]) 
    332         import binascii 
    333376        self._eps.write(self.EPS_SET_GRADIENT % (x1, y1, x2, y2, len(samples), binascii.hexlify(binary))) 
    334377 
     
    344387        Renderer.set_render_hints(self, hints) 
    345388        if hints.get("linecap", None): 
    346             map = {"butt":0, "round":1, "rect":2} 
     389            map = {"butt": 0, "round": 1, "rect": 2} 
    347390            self._eps.write("%i setlinecap\n" % (map.get(hints.get("linecap"), 0))) 
    348391 
     
    353396    @with_state 
    354397    def draw_rect(self, x, y, w, h, **kwargs): 
    355         self._eps.write("newpath\n%(x)f %(y)f moveto %(w)f 0 rlineto\n0 %(h)f rlineto %(w)f neg 0 rlineto\nclosepath\n" % dict(x=x, y= -y, w=w, h= -h)) 
     398        self._eps.write("newpath\n%(x)f %(y)f moveto %(w)f 0 rlineto\n0 %(h)f rlineto %(w)f neg 0 rlineto\nclosepath\n" % dict(x=x, y=-y, w=w, h=-h)) 
    356399        self._eps.write("gsave\n") 
    357400        if self.gradient(): 
     
    409452 
    410453    def string_size_hint(self, text, **kwargs): 
    411         import warnings 
    412454        warnings.warn("EpsRenderer class does not suport exact string width estimation", stacklevel=2) 
    413455        return len(text) * self.font()[1] 
    414456 
     457 
    415458def _int_color(color): 
    416459    """ Transform the color tuple (with floats) to tuple with ints 
    417     (needed by PIL)  
     460    (needed by PIL) 
    418461    """ 
    419462    return tuple(map(int, color)) 
     463 
    420464 
    421465class PILRenderer(Renderer): 
    422466    def __init__(self, width, height): 
    423467        Renderer.__init__(self, width, height) 
    424         import Image, ImageDraw, ImageFont 
     468        from PIL import Image, ImageDraw, ImageFont 
    425469        self._pil_image = Image.new("RGB", (int(width), int(height)), (255, 255, 255)) 
    426470        self._draw = ImageDraw.Draw(self._pil_image, "RGB") 
     
    433477    def set_font(self, family, size): 
    434478        Renderer.set_font(self, family, size) 
    435         import ImageFont 
     479        from PIL import ImageFont 
    436480        try: 
    437481            font_file = os.path.join(install_dir, "utils", family + ".ttf") 
     
    441485                self._pil_font = ImageFont.truetype(family + ".ttf", int(size)) 
    442486        except Exception: 
    443             import warnings 
    444487            warnings.warn("Could not load %s.ttf font!" % family, stacklevel=2) 
    445488            try: 
     
    460503        x1, y1 = self._transform(x, y) 
    461504        x2, y2 = self._transform(x + w, y + h) 
    462         self._draw.rectangle((x1, y1, x2 , y2), fill=_int_color(self.fill_color()), 
     505        self._draw.rectangle((x1, y1, x2, y2), fill=_int_color(self.fill_color()), 
    463506                             outline=_int_color(self.stroke_color())) 
    464507 
     
    489532</svg> 
    490533""" 
     534 
    491535    def __init__(self, width, height): 
    492536        Renderer.__init__(self, width, height) 
    493537        self.transform_count_stack = [0] 
    494         import StringIO 
    495538        self._svg = StringIO.StringIO() 
    496539        self._defs = StringIO.StringIO() 
     
    517560 
    518561    def get_stroke(self): 
    519 #        if self.render_state["gradient"]: 
    520 #            return "" 
    521 #        else: 
    522             return 'stroke="rgb(%i, %i, %i)"' % self.stroke_color() + ' stroke-width="%f"' % self.stroke_width() 
     562        return 'stroke="rgb(%i, %i, %i)"' % self.stroke_color() + ' stroke-width="%f"' % self.stroke_width() 
    523563 
    524564    def get_text_alignment(self): 
     
    531571    def draw_line(self, sx, sy, ex, ey): 
    532572        self._svg.write('<line x1="%f" y1="%f" x2="%f" y2="%f" %s %s/>\n' % ((sx, sy, ex, ey) + (self.get_stroke(), self.get_linecap()))) 
    533  
    534 #    @with_state 
    535 #    def draw_lines(self): 
    536573 
    537574    @with_state 
     
    580617        file.write(self.SVG_HEADER % (self.height, self.width, self._defs.getvalue(), self._svg.getvalue())) 
    581618 
     619 
    582620class CairoRenderer(Renderer): 
    583621    def __init__(self, width, height): 
    584622        Renderer.__init__(self, width, height) 
    585  
  • docs/extend-widgets/rst/basics.rst

    r11424 r11439  
    158158            self.resize(100,50) 
    159159 
    160 In initialization, the widget calls the :obj:`init` function 
     160In initialization, the widget calls the :obj:`__init__` function 
    161161of a base class, passing the name 'SampleData' which will, 
    162162essentially, be used for nothing else than a stem of a file for saving 
     
    182182Orange widgets are most often split to control and main area. Control 
    183183area appears on the left and should include any controls for settings 
    184 or options that your widget will use. Main are would most often 
     184or options that your widget will use. Main area would most often 
    185185include a graph, table or some drawing that will be based on the 
    186186inputs to the widget and current options/setting in the control 
     
    225225"Sampled Data". 
    226226 
    227 Notice that the token can be empty (:obj:`dataset==None`), 
     227Notice that the token can be empty (``dataset is None``), 
    228228resulting from either the sending widget to which we have connected 
    229229intentionally emptying the channel, or when the link between the two 
  • docs/extend-widgets/rst/channels.rst

    r11424 r11439  
    22Channels and Tokens 
    33################### 
    4   
     4 
    55Our data sampler widget was, regarding the channels, rather simple 
    66and linear: the widget was designed to receive the token from one 
     
    5555Notice that everything is pretty much the same as it was with 
    5656widgets from previous lessons, the only difference being 
    57 :obj:`Multiple + Default` as the last value in the list that defines 
    58 the :obj:`Learner` channel. This :obj:`Multiple + Default` says 
     57``Multiple + Default`` as the last value in the list that defines 
     58the :obj:`Learner` channel. This ``Multiple + Default`` says 
    5959that this is a multi-input channel and is the default input for its type. 
    6060If it would be unspecified then by default value of 
    61 :obj:`Single + NonDefault` would be used. That would mean that the 
     61``Single + NonDefault`` would be used. That would mean that the 
    6262widget can receive the input only from one widget and is not the default input 
    6363channel for its type (more on default channels later). 
     
    147147scoring functions from stats. I rather like 
    148148the easy by which new scoring functions are added to the widget, since 
    149 all that is needed is the augmenting the list :: 
     149all that is needed is the augmenting the list:: 
    150150 
    151151    self.scoring = [("Classification Accuracy", orngStat.CA), 
     
    234234That is, the :obj:`Train Data` channel is a single-token 
    235235channel which is a default one (third parameter). Note that the flags can 
    236 be added (or OR-d) together so :obj:`Default + Multiple` is a valid flag. 
     236be added (or OR-d) together so ``Default + Multiple`` is a valid flag. 
    237237To test how this works, connect a file widget to a learning curve widget and 
    238238- nothing will really happen: 
  • docs/extend-widgets/rst/graphing.rst

    r11424 r11439  
    5656learner, and use a trick allowed in Orange that we can simply store 
    5757this as a new attribute to the learning object. By default, Orange 
    58 would give a warning of the type :: 
     58would give a warning of the type:: 
    5959 
    6060    c:\Python23\Lib\site-packages\orange\OrangeWidgets\Test\OWLearningCurveC.py:269: 
     
    6262      setattr(learner, "curve", curve) 
    6363 
    64 but we surpress such warnings with a line :: 
     64but we surpress such warnings with a line:: 
    6565 
    6666    warnings.filterwarnings("ignore", ".*builtin attribute.*", orange.AttributeWarning) 
     67 
     68 
     69.. warning:: 
     70 
     71   This is a very bad design. Please do **not** store widget data in the 
     72   input objects. 
     73 
    6774 
    6875in the initialization part of the widget. In this way, each learner 
     
    157164            l.isSelected = i in self.selectedLearners 
    158165 
    159 The complete code of this widget is available :download:`here <OWLearningCurveC.py>`.  
     166The complete code of this widget is available :download:`here <OWLearningCurveC.py>`. 
    160167This is almost like a typical 
    161168widget that is include in a standard Orange distribution, with a 
  • docs/extend-widgets/rst/owgui.rst

    r11424 r11439  
     1.. module:: OWGUI 
     2 
    13##################################### 
    24OWGUI: Library of Common GUI Controls 
  • docs/extend-widgets/rst/settings.rst

    r11424 r11439  
    175175should be a corresponding widget's attribute recording the check box's 
    176176state so that when the user changes a check box, the attribute changes 
    177 and vice-versa. Although you can create such a link manually, you 
    178 should always use the module :doc:`OWGUI <owgui>` instead; 
    179 for instance, for a check box, use :obj:`OWGUI.checkBox` and not 
    180 simply the Qt's :obj:`QCheckBox`. 
     177and vice-versa. You can create such a link manually, or you can use 
     178the :doc:`OWGUI <owgui>` module instead; for instance, for a check 
     179box, use :func:`OWGUI.checkBox`. 
    181180 
    182181The settings fall into two groups. Some of them do not depend on 
    183182the data, while other are context-dependent. For the first to be saved 
    184183properly, you only need to list them in the :obj:`settingsList` 
    185 in the widget definition, as already described :doc:`elsewhere <settings>` 
     184in the widget definition, as already described. 
     185 
     186 
     187.. module:: OWContexts 
    186188 
    187189************************** 
     
    204206Saving, loading and matching contexts is taken care of by context 
    205207handlers. Currently, there are only two classes of context handlers 
    206 implemented. The first one is the abstract :obj:`ContextHandler` 
    207 and the second one is :obj:`DomainContextHandler` in which the 
     208implemented. The first one is the abstract :class:`ContextHandler` 
     209and the second one is :class:`DomainContextHandler` in which the 
    208210context is defined by the data set domain and where the settings 
    209211contain attribute names. The latter should cover most of your needs, 
     
    211213classes from it. There may even be some cases in which the context is 
    212214not defined by the domain, in which case the 
    213 :obj:`ContextHandler` will be used as a base for your new 
     215:class:`ContextHandler` will be used as a base for your new 
    214216handler. 
    215217 
     
    217219closing usually takes place (in the opposite order) in the function 
    218220that handles the data signal. This is how it looks in the scatter plot 
    219 (the code is somewhat simplified for clarity). :: 
     221(the code is somewhat simplified for clarity). 
     222 
     223:: 
    220224 
    221225    def cdata(self, data, clearResults = 1): 
     
    269273 
    270274Except for declaring the context settings, that is. Scatter plot has this just 
    271 below the :obj:`settingsList`:: 
     275below the :obj:`settingsList` :: 
    272276 
    273277    contextHandlers = {"": DomainContextHandler("", 
     
    298302same flags, so they can be grouped into :obj:`(["attrLabel", 
    299303"attrShape", "attrSize"], DomainContextHandler.Optional)`. So 
    300 what scatter plot really says is :: 
     304what scatter plot really says is:: 
    301305 
    302306    contextHandlers = {"": DomainContextHandler("", [ 
  • install-scripts/mac/bundle-build-hg.sh

    r11074 r11460  
    2929fi 
    3030 
    31 #Python interpreter in the bundle 
     31# Python interpreter in the bundle 
    3232PYTHON=${TMP_BUNDLE_DIR}/Orange.app/Contents/MacOS/python 
    3333 
    34 #easy_install script in the bundle 
     34# easy_install script in the bundle 
    3535EASY_INSTALL=${TMP_BUNDLE_DIR}/Orange.app/Contents/MacOS/easy_install 
    3636 
     
    8484echo "+++++++++++++++++++++++" 
    8585./bundle-inject-pypi.sh suds-0.4 http://pypi.python.org/packages/source/s/suds/suds-0.4.tar.gz $REPOS_DIR ${TMP_BUNDLE_DIR}/Orange.app 
     86 
     87echo "Instaling slumber library" 
     88echo "+++++++++++++++++++++++++" 
     89$EASY_INSTALL slumber 
    8690 
    8791echo "Removing unnecessary files." 
Note: See TracChangeset for help on using the changeset viewer.