{
    "file_diffs": [
        {
            "old_file_content": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, data, instance in self.traverse_settings(data, instance):\n            if setting.name in data and instance is not None:\n                setattr(instance, setting.name, data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            self.widget_class.migrate_settings(settings, settings.pop(VERSION_KEY, 0))\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, instance in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                setattr(instance, setting.name, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    IF_SELECTED = 1\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, not_attribute=False, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.not_attribute = not_attribute\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        for context in contexts:\n            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            sel_name = getattr(setting, \"selected\", None)\n            selected = set(data.pop(sel_name, []))\n            new_selected, new_value = [], []\n            for i, item in enumerate(value):\n                if self.is_valid_item(setting, item, attrs, metas):\n                    if i in selected:\n                        new_selected.append(len(new_value))\n                    new_value.append(item)\n\n            data[setting.name] = new_value\n            if hasattr(setting, 'selected'):\n                data[setting.selected] = new_selected\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            return copy.copy(value)\n        elif isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return value.name, 100 + vartype(value)\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        if hasattr(setting, 'selected'):\n            selected = set(context.values.get(setting.selected, []))\n        else:\n            selected = set()\n\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            else:\n                if setting.required == ContextSetting.REQUIRED:\n                    raise IncompatibleContext()\n                if setting.IF_SELECTED and i in selected:\n                    raise IncompatibleContext()\n\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\n",
            "new_file_content": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\",\n           \"IncompatibleContext\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, data, instance in self.traverse_settings(data, instance):\n            if setting.name in data and instance is not None:\n                setattr(instance, setting.name, data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            self.widget_class.migrate_settings(settings, settings.pop(VERSION_KEY, 0))\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, instance in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                setattr(instance, setting.name, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    IF_SELECTED = 1\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, not_attribute=False, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.not_attribute = not_attribute\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        i = 0\n        while i < len(contexts):\n            context = contexts[i]\n            try:\n                self.widget_class.migrate_context(\n                    context, context.values.pop(VERSION_KEY, 0))\n            except IncompatibleContext:\n                del contexts[i]\n            else:\n                i += 1\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            sel_name = getattr(setting, \"selected\", None)\n            selected = set(data.pop(sel_name, []))\n            new_selected, new_value = [], []\n            for i, item in enumerate(value):\n                if self.is_valid_item(setting, item, attrs, metas):\n                    if i in selected:\n                        new_selected.append(len(new_value))\n                    new_value.append(item)\n\n            data[setting.name] = new_value\n            if hasattr(setting, 'selected'):\n                data[setting.selected] = new_selected\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            return copy.copy(value)\n        elif isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return value.name, 100 + vartype(value)\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        if hasattr(setting, 'selected'):\n            selected = set(context.values.get(setting.selected, []))\n        else:\n            selected = set()\n\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            else:\n                if setting.required == ContextSetting.REQUIRED:\n                    raise IncompatibleContext()\n                if setting.IF_SELECTED and i in selected:\n                    raise IncompatibleContext()\n\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/settings.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "8be8bf0ae",
                "new_commit_hash": "75ebe4129",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/settings.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/settings.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 49,
                            "length": 7
                        },
                        "new_range": {
                            "start": 49,
                            "length": 8
                        },
                        "section": "log = logging.getLogger(__name__)"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",",
                                "type": "context"
                            },
                            {
                                "content": "           \"ContextSetting\", \"ContextHandler\",",
                                "type": "context"
                            },
                            {
                                "content": "           \"DomainContextHandler\", \"PerfectDomainContextHandler\",",
                                "type": "context"
                            },
                            {
                                "content": "           \"ClassValuesContextHandler\", \"widget_settings_dir\"]",
                                "type": "deleted"
                            },
                            {
                                "content": "           \"ClassValuesContextHandler\", \"widget_settings_dir\",",
                                "type": "added"
                            },
                            {
                                "content": "           \"IncompatibleContext\"]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "_IMMUTABLES = (str, int, bytes, bool, float, tuple)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "statement",
                            "name": "",
                            "content": "__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\",\n           \"IncompatibleContext\"]",
                            "ast_type_str": "Assign",
                            "start_lineno": 49,
                            "end_lineno": 53,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "statement",
                            "name": "",
                            "content": "__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\"]",
                            "ast_type_str": "Assign",
                            "start_lineno": 49,
                            "end_lineno": 52,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 624,
                            "length": 8
                        },
                        "new_range": {
                            "start": 625,
                            "length": 16
                        },
                        "section": "class ContextHandler(SettingsHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._migrate_contexts(self.global_contexts)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _migrate_contexts(self, contexts):",
                                "type": "context"
                            },
                            {
                                "content": "        for context in contexts:",
                                "type": "deleted"
                            },
                            {
                                "content": "            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))",
                                "type": "deleted"
                            },
                            {
                                "content": "        i = 0",
                                "type": "added"
                            },
                            {
                                "content": "        while i < len(contexts):",
                                "type": "added"
                            },
                            {
                                "content": "            context = contexts[i]",
                                "type": "added"
                            },
                            {
                                "content": "            try:",
                                "type": "added"
                            },
                            {
                                "content": "                self.widget_class.migrate_context(",
                                "type": "added"
                            },
                            {
                                "content": "                    context, context.values.pop(VERSION_KEY, 0))",
                                "type": "added"
                            },
                            {
                                "content": "            except IncompatibleContext:",
                                "type": "added"
                            },
                            {
                                "content": "                del contexts[i]",
                                "type": "added"
                            },
                            {
                                "content": "            else:",
                                "type": "added"
                            },
                            {
                                "content": "                i += 1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def write_defaults_file(self, settings_file):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "method",
                            "name": "ContextHandler._migrate_contexts",
                            "content": "class ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        for context in contexts:\n            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 626,
                            "end_lineno": 628,
                            "parent": {
                                "file_name": "Orange/widgets/settings.py",
                                "type": "class",
                                "name": "ContextHandler",
                                "content": "class ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        for context in contexts:\n            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 585,
                                "end_lineno": 862,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "class",
                            "name": "ContextHandler",
                            "content": "class ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        for context in contexts:\n            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 585,
                            "end_lineno": 862,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import pickle\nfrom copy import copy, deepcopy\nfrom io import BytesIO\nfrom unittest import TestCase\nfrom unittest.mock import Mock, patch, call\nfrom Orange.widgets.settings import (\n    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,\n    VERSION_KEY\n)\n\n__author__ = 'anze'\n\n\nclass SimpleWidget:\n    settings_version = 1\n\n    setting = Setting(42)\n    schema_only_setting = Setting(None, schema_only=True)\n\n    context_setting = ContextSetting(42)\n\n    migrate_settings = Mock()\n    migrate_context = Mock()\n\n\nclass DummyContext(Context):\n    id = 0\n\n    def __init__(self, version=None):\n        super().__init__()\n        DummyContext.id += 1\n        self.id = DummyContext.id\n        if version:\n            self.values[VERSION_KEY] = version\n\n    def __repr__(self):\n        return \"Context(id={})\".format(self.id)\n    __str__ = __repr__\n\n    def __eq__(self, other):\n        if not isinstance(other, DummyContext):\n            return False\n        return self.id == other.id\n\n\ndef create_defaults_file(contexts):\n    b = BytesIO()\n    pickle.dump({\"x\": 5}, b)\n    pickle.dump(contexts, b)\n    b.seek(0)\n    return b\n\n\nclass TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)\n\n\nclass TestSettingsPrinter(TestCase):\n    def test_formats_contexts(self):\n        settings = dict(key1=1, key2=2,\n                        context_settings=[\n                            Context(param1=1, param2=2,\n                                    values=dict(value1=1,\n                                                value2=2)),\n                            Context(param1=3, param2=4,\n                                    values=dict(value1=5,\n                                                value2=6))\n                        ])\n        pp = SettingsPrinter()\n\n        output = pp.pformat(settings)\n        # parameter of all contexts should be visible in the output\n        self.assertIn(\"param1=1\", output)\n        self.assertIn(\"param2=2\", output)\n        self.assertIn(\"param1=3\", output)\n        self.assertIn(\"param2=4\", output)\n",
            "new_file_content": "import pickle\nfrom copy import copy, deepcopy\nfrom io import BytesIO\nfrom unittest import TestCase\nfrom unittest.mock import Mock, patch, call\nfrom Orange.widgets.settings import (\n    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,\n    VERSION_KEY, IncompatibleContext\n)\n\n__author__ = 'anze'\n\n\nclass SimpleWidget:\n    settings_version = 1\n\n    setting = Setting(42)\n    schema_only_setting = Setting(None, schema_only=True)\n\n    context_setting = ContextSetting(42)\n\n    migrate_settings = Mock()\n    migrate_context = Mock()\n\n\nclass DummyContext(Context):\n    id = 0\n\n    def __init__(self, version=None):\n        super().__init__()\n        DummyContext.id += 1\n        self.id = DummyContext.id\n        if version:\n            self.values[VERSION_KEY] = version\n\n    def __repr__(self):\n        return \"Context(id={})\".format(self.id)\n    __str__ = __repr__\n\n    def __eq__(self, other):\n        if not isinstance(other, DummyContext):\n            return False\n        return self.id == other.id\n\n\ndef create_defaults_file(contexts):\n    b = BytesIO()\n    pickle.dump({\"x\": 5}, b)\n    pickle.dump(contexts, b)\n    b.seek(0)\n    return b\n\n\nclass TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n\n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n            contexts = widget.context_settings\n            self.assertEqual(len(contexts), 3)\n            self.assertTrue(\n                all(context.foo == i\n                    for i, context in enumerate(contexts)))\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)\n\n\nclass TestSettingsPrinter(TestCase):\n    def test_formats_contexts(self):\n        settings = dict(key1=1, key2=2,\n                        context_settings=[\n                            Context(param1=1, param2=2,\n                                    values=dict(value1=1,\n                                                value2=2)),\n                            Context(param1=3, param2=4,\n                                    values=dict(value1=5,\n                                                value2=6))\n                        ])\n        pp = SettingsPrinter()\n\n        output = pp.pformat(settings)\n        # parameter of all contexts should be visible in the output\n        self.assertIn(\"param1=1\", output)\n        self.assertIn(\"param2=2\", output)\n        self.assertIn(\"param1=3\", output)\n        self.assertIn(\"param2=4\", output)\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/tests/test_context_handler.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a3c94f54d",
                "new_commit_hash": "3ea0c540e",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/tests/test_context_handler.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/tests/test_context_handler.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 5,
                            "length": 7
                        },
                        "new_range": {
                            "start": 5,
                            "length": 7
                        },
                        "section": "from unittest import TestCase"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from unittest.mock import Mock, patch, call",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.widgets.settings import (",
                                "type": "context"
                            },
                            {
                                "content": "    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,",
                                "type": "context"
                            },
                            {
                                "content": "    VERSION_KEY",
                                "type": "deleted"
                            },
                            {
                                "content": "    VERSION_KEY, IncompatibleContext",
                                "type": "added"
                            },
                            {
                                "content": ")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "__author__ = 'anze'",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "from Orange.widgets.settings import (\n    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,\n    VERSION_KEY, IncompatibleContext\n)",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 6,
                            "end_lineno": 9,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "from Orange.widgets.settings import (\n    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,\n    VERSION_KEY\n)",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 6,
                            "end_lineno": 9,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 111,
                            "length": 6
                        },
                        "new_range": {
                            "start": 111,
                            "length": 26
                        },
                        "section": "class TestContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))",
                                "type": "context"
                            },
                            {
                                "content": "        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_migrates_settings_removes_incompatible(self):",
                                "type": "added"
                            },
                            {
                                "content": "        handler = ContextHandler()",
                                "type": "added"
                            },
                            {
                                "content": "        handler.bind(SimpleWidget)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        widget = SimpleWidget()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        def migrate_context(context, _):",
                                "type": "added"
                            },
                            {
                                "content": "            if context.foo == 13:",
                                "type": "added"
                            },
                            {
                                "content": "                raise IncompatibleContext()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):",
                                "type": "added"
                            },
                            {
                                "content": "            handler.initialize(widget, dict(context_settings=contexts))",
                                "type": "added"
                            },
                            {
                                "content": "            contexts = widget.context_settings",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(len(contexts), 3)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertTrue(",
                                "type": "added"
                            },
                            {
                                "content": "                all(context.foo == i",
                                "type": "added"
                            },
                            {
                                "content": "                    for i, context in enumerate(contexts)))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_fast_save(self):",
                                "type": "context"
                            },
                            {
                                "content": "        handler = ContextHandler()",
                                "type": "context"
                            },
                            {
                                "content": "        handler.bind(SimpleWidget)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_context_handler.py",
                            "type": "class",
                            "name": "TestContextHandler",
                            "content": "class TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n\n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n            contexts = widget.context_settings\n            self.assertEqual(len(contexts), 3)\n            self.assertTrue(\n                all(context.foo == i\n                    for i, context in enumerate(contexts)))\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 54,
                            "end_lineno": 214,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_context_handler.py",
                            "type": "method",
                            "name": "TestContextHandler.test_migrates_settings_removes_incompatible",
                            "content": "class TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n\n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n            contexts = widget.context_settings\n            self.assertEqual(len(contexts), 3)\n            self.assertTrue(\n                all(context.foo == i\n                    for i, context in enumerate(contexts)))\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 114,
                            "end_lineno": 132,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_context_handler.py",
                                "type": "class",
                                "name": "TestContextHandler",
                                "content": "class TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n\n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n            contexts = widget.context_settings\n            self.assertEqual(len(contexts), 3)\n            self.assertTrue(\n                all(context.foo == i\n                    for i, context in enumerate(contexts)))\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 54,
                                "end_lineno": 214,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "################################\nTutorial (Settings and Controls)\n################################\n\nIn the :doc:`previous section <tutorial-cont>` of our tutorial we\nhave just built a simple sampling widget. Let us now make this widget\na bit more useful, by allowing a user to set the proportion of data\ninstances to be retained in the sample. Say we want to design a widget\nthat looks something like this:\n\n.. image:: images/dataSamplerBWidget.png\n\n\nWhat we added is an Options box, with a spin entry box to set the\nsample size, and a check box and button to commit (send out) any\nchange we made in setting. If the check box with \"Commit data on\nselection change\" is checked, than any change in the sample size will\nmake the widget send out the sampled dataset. If datasets are large\n(say of several thousands or more) instances, we may want to send out\nthe sample data only after we are done setting the sample size, hence\nwe left the commit check box unchecked and press \"Commit\" when we are\nready for it.\n\nThis is a very simple interface, but there is something more to\nit. We want the settings (the sample size and the state of the commit\nbutton) to be saved. That is, any change we made, we want to save it so\nthat the next time we open the widget the settings is there as we have left\nit\n\n..\n   There is some complication to it, as widget can be part of an\n   application, or part of some schema in the Canvas, and we would like\n   to have the settings application- or schema-specific.\n\n\nWidgets Settings\n****************\n\nLuckily, since we use the base class :class:`~Orange.widgets.widget.OWWidget`,\nthe settings will be handled just fine. We only need to tell which variables\nwe want to use for persistent settings.\n\n..\n   For Python inspired readers: these\n   variables can store any complex object, as long as it is\n   picklable.\n\nIn our widget, we will use two settings variables, and we declare this\nin the widget class definition (after the `inputs`, `outputs` definitions).\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-1\n   :end-before: end-snippet-1\n\n\nAll settings have to specify their default value. When a widget is\ncreated the widget's members are already restored and ready to use\nin its `__init__` method.\nThe contents of the two variables (:obj:`self.proportion` and\n:obj:`self.commitOnChange`) will be saved upon closing our widget.\nIn our widget, we won't be setting these variables directly,\nbut will instead use them in conjunction with GUI controls.\n\n\nControls and module `gui`\n*************************\n\nWe will use the :mod:`Orange.widgets.gui` to create/define the gui.\nWith this library, the GUI definition part of the options box is a bit\ndense but rather very short\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-3\n   :end-before: end-snippet-3\n\n\nWe are already familiar with the first part - the Info group\nbox. To make widget nicer, we put a separator between this and Options\nbox. After defining the option box, here is our first serious\n:mod:`~Orange.widgets.gui` control: a :func:`Orange.widgets.gui.spin`.\nThe first parameter specifies its parent widget/layout, in this case\n:obj:`self.optionsBox` (the resulting widget object will automatically\nappend itself to the parent's layout). The second (:obj:`self`) and\nthird (``'proportion'``) define the *property binding* for the spin box.\nI.e. any change in the spin box control will automatically be propagated\nto the :obj:`self.proportions` and vice versa - changing the value of\n`self.proprotions` in the widget code by assignment\n(e.g. ``self.proprotions = 30``) will update the spin box's state to match.\n\nThe rest of the spin box call gives some parameters for the\ncontrol (minimum and maximum value and the step size), tells about the\nlabel which will be placed on the top, and tells it which functions to\ncall when the value in the spin box is changed. We need the first\ncallback to make a data sample and report in the Info box what is the\nsize of the sample, and a second callback to check if we can send this\ndata out. In :mod:`Orange.widgets.gui`, callbacks are either references\nto functions, or a list with references, just like in our case.\n\nWith all of the above, the parameters for the call of\n:func:`Orange.widgets.gui.checkBox` should be clear as well. Notice that\nthis and a call to :func:`Orange.widgets.gui.spin` do not need a parameter\nwhich would tell the control the value for initialization: upon\nconstruction, both controls will be set to the value that is\npertained in the associated setting variable.\n\nThat's it. Notice though that we have, as a default, disabled all\nthe controls in the Options box. This is because at the start of the\nwidget, there is no data to sample from. But this also means that when\nprocess the input tokens, we should take care for enabling and\ndisabling. The data processing and token sending part of our widget\nnow is\n\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-4\n   :end-before: end-snippet-4\n\n\nYou can now also inspect the :download:`complete code <orange-demo/orangedemo/OWDataSamplerB.py>`\nof this widget. To distinguish it with a widget we have developed in the\nprevious section, we have designed a special\n:download:`icon <orange-demo/orangedemo/icons/DataSamplerB.svg>` for it.\nIf you wish to test this widget in the Orange Canvas, put its code in\nthe `orangedemo` directory we have created for the previous widget and try\nit out using a schema with a File and Data Table widget.\n\n.. image:: images/schemawithdatasamplerB.png\n\nWell-behaved widgets remember their settings - the state of their\ncheckboxes and radio-buttons, the text in their line edits, the\nselections in their combo boxes and similar.\n\nPersisting defaults\n*******************\nWhen a widget is removed, its settings are stored to be used as defaults\nfor future instances of this widget.\n\nUpdated defaults are stored in user's profile. It's location depends\non the operating system:\n(%APPDATA%\\Orange\\<version>\\widgets on windows,\n~/Library/Application\\ Support/orange/<version>/widgets on macOS,\n~/.local/share/Orange/<version>/widgets on linux)\nOriginal default values can be restored by deleting files from this folder,\nby running Orange from command line with `--clear-widget-settings` option,\nor through Options/Reset Widget Settings menu action.\n\nSchema-only settings\n--------------------\nSome settings have defaults that should not change. For instance, when using\na Paint Data widget, drawn points should be saved in a workflow, but a new\nwidget should always start with a blank page - modified value should not\nbe remembered.\n\nThis can be achieved by declaring a setting with a `schema_only` flag. Such\nsetting is saved with a workflow, but its default value never changes.\n\nContext dependent settings\n**************************\n\nContext dependent settings are settings which depend on the widget's\ninput. For instance, the scatter plot widget contains settings that\nspecify the attributes for x and y axis, and the settings that\ndefine the color, shape and size of the examples in the graph.\n\nAn even more complicated case is the widget for data\nselection with which one can select the examples based on values of\ncertain attributes. Before applying the saved settings, these widgets\nneeds to check their compliance with the domain of the actual data\nset. To be truly useful, context dependent settings needs to save a\nsetting configuration for each particular dataset used. That is, when\ngiven a particular dataset, it has to select the saved settings that\nis applicable and matches best currently used dataset.\n\nSaving, loading and matching contexts is taken care of by context\nhandlers. Currently, there are only two classes of context handlers\nimplemented. The first one is the abstract :class:`ContextHandler`\nand the second one is :class:`DomainContextHandler` in which the\ncontext is defined by the dataset domain and where the settings\ncontain attribute names. The latter should cover most of your needs,\nwhile for more complicated widgets you will need to derive a new\nclasses from it. There may even be some cases in which the context is\nnot defined by the domain, in which case the\n:class:`ContextHandler` will be used as a base for your new\nhandler.\n\nContexts need to be declared, opened and closed. Opening and\nclosing usually takes place (in the opposite order) in the function\nthat handles the data signal. This is how it looks in the scatter plot\n(the code is somewhat simplified for clarity).\n\n.. code-block:: python\n\n    @Input.data\n    def set_data(self, data):\n        self.closeContext()\n        self.data = data\n        self.graph.setData(data)\n\n        self.initAttrValues()\n\n        if data is not None:\n            self.openContext(data.domain)\n\n        self.updateGraph()\n        self.sendSelections()\n\nIn general, the function should go like this:\n\n* Do any clean-up you need, but without clearing any of the settings that need\n  to be saved. Scatter plot needs none.\n* Call ``self.closeContext()``; this ensures that all the context dependent\n  settings (e.g. attribute names from the list boxes) are remembered.\n* Initialize the widget state and set the controls to some defaults as\n  if there were no context retrieving mechanism. Scatter plot does it by\n  calling ``self.initAttrValues()`` which assigns the first two attributes to\n  the x and y axis and the class attribute to the color. At this phase, you\n  shouldn't call any functions that depend on the settings, such as drawing\n  the graph.\n* Call ``self.openContext(data.domain)`` (more about the arguments later).\n  This will search for a suitable context and assign the controls new values\n  if one is found. If there is no saved context that can be used, a new\n  context is created and filled with the default values that were assigned\n  at the previous point.\n* Finally, adjust the widget according to the retrieved controls. Scatter plot\n  now plots the graph by calling ``self.updateGraph()``.\n\nWhen opening the context, we provide the arguments on which the context\ndepends. In case of :class:`DomainContextHandler`, which scatter plot uses, we\ncan give it a :class:`Orange.data.Domain`. Whether a saved context can be\nreused is judged upon the presence of attributes in the domain.\n\nIf the widget is constructed appropriately (that is, if it strictly uses\n:mod:`Orange.widgets.gui` controls instead of the Qt's), no other\nadministration is needed to switch the context.\n\nExcept for declaring the context settings, that is. Scatter plot has this in\nits class definition\n\n.. code-block:: python\n\n    settingsHandler = DomainContextHandler()\n    attr_x = ContextSetting(\"\")\n    attr_y = ContextSetting(\"\")\n\n    auto_send_selection = Setting(True)\n    toolbar_selection = Setting(0)\n    color_settings = Setting(None)\n    selected_schema_index = Setting(0)\n\n\n``settingsHandler = DomainContextHandler()`` declares that Scatter plot uses\n:class:`DomainContextHandler`. The :obj:`attr_x` and :obj:`attr_y` are\ndeclared as :class:`~Orange.widgets.settings.ContextSetting`.\n\n\nMigrations\n**********\n\nAt the beginning of this section of the tutorial, we created a widget with\na setting called proportion, which contains a value between 0 and 100. But\nimagine that for some reason, we are not satisfied with the value any more\nand decide that the setting should hold a value between 0 and 1.\n\nWe update the setting's default value, modify the appropriate code and we\nare done. That is, until someone that has already used the old version of\nthe widget open the new one and the widget crashes. Remember, when the\nwidget is opened, it has the same settings that were used the last time.\n\nIs there anything we can do, as settings are replaced with saved before\nthe __init__ function is called? There is! Migrations to the rescue.\n\nWidget has a special attribute called `settings_version`. All widgets start\nwith a settings_version of 1. When incompatible changes are done to the\nwidget's settings, its settings_version should be increased. But increasing\nthe version by it self does not solve our problems. While the widget now\nknows that it uses different settings, the old ones are still broken and\nneed to be updated before they can be used with the new widget. This can be\naccomplished by reimplementing widget's methods `migrate_settings`\n(for ordinary settings) and `migrate_context` (for context settings).\nBoth method are called with the old object and the version of the settings\nstored with it.\n\nIf we bumped settings_version from 1 to 2 when we did the above mentioned\nchange, our migrate_settings method would look like this:\n\n.. code-block:: python\n\n    def migrate_settings(settings, version):\n       if version < 2:\n         if \"proportion\" in settings:\n            settings[\"proportion\"] = settings[\"proportion\"] / 100\n\nYour migration rules can be simple or complex, but try to avoid simply\nforgetting the values, as settings are also used in saved workflows.\nImagine opening a complex workflow you have designed a year ago with the\nnew version of Orange and finding out that all the settings are back to\ndefault. Not fun!\n\n.. warning::\n\n   If you change the format of an existing setting in a backwards-incompatible\n   way, you will also want to *change the name* of that setting. Otherwise,\n   older versions of Orange won't be able to load workflows with the new\n   setting format.\n\nThere are two helper functions you can use.\n:obj:`Orange.widget.settings.rename_settings(settings, old_name, new_name)`\ndoes the obvious operation on `settings`, which can be either a dictionary\nor a context, thus it can be called from `migrate_settings` or\n`migrate_context`.\n\nAnother common operation may be upgrading your widget from storing variable\nnames (as `str`) to storing variables (instances of classes derived from\n`Variable`). In a typical scenario, this happens when combo boxes are upgraded to\nusing models. Function\n:obj:`Orange.widget.settings.migrate_str_to_variable(settings, names=None)`\nmakes the necessary changes to the settings listed in `names`. `names` can be\na list of setting names, a single string or `None`. In the latter case, all\nsettings that may refer to variables (that is two-elements tuples constisting\nof a string and an int) are migrated.\n\nSo take some time, write the migrations and do not forget to bump the\n`settings_version` when you do breaking changes.\n",
            "new_file_content": "################################\nTutorial (Settings and Controls)\n################################\n\nIn the :doc:`previous section <tutorial-cont>` of our tutorial we\nhave just built a simple sampling widget. Let us now make this widget\na bit more useful, by allowing a user to set the proportion of data\ninstances to be retained in the sample. Say we want to design a widget\nthat looks something like this:\n\n.. image:: images/dataSamplerBWidget.png\n\n\nWhat we added is an Options box, with a spin entry box to set the\nsample size, and a check box and button to commit (send out) any\nchange we made in setting. If the check box with \"Commit data on\nselection change\" is checked, than any change in the sample size will\nmake the widget send out the sampled dataset. If datasets are large\n(say of several thousands or more) instances, we may want to send out\nthe sample data only after we are done setting the sample size, hence\nwe left the commit check box unchecked and press \"Commit\" when we are\nready for it.\n\nThis is a very simple interface, but there is something more to\nit. We want the settings (the sample size and the state of the commit\nbutton) to be saved. That is, any change we made, we want to save it so\nthat the next time we open the widget the settings is there as we have left\nit\n\n..\n   There is some complication to it, as widget can be part of an\n   application, or part of some schema in the Canvas, and we would like\n   to have the settings application- or schema-specific.\n\n\nWidgets Settings\n****************\n\nLuckily, since we use the base class :class:`~Orange.widgets.widget.OWWidget`,\nthe settings will be handled just fine. We only need to tell which variables\nwe want to use for persistent settings.\n\n..\n   For Python inspired readers: these\n   variables can store any complex object, as long as it is\n   picklable.\n\nIn our widget, we will use two settings variables, and we declare this\nin the widget class definition (after the `inputs`, `outputs` definitions).\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-1\n   :end-before: end-snippet-1\n\n\nAll settings have to specify their default value. When a widget is\ncreated the widget's members are already restored and ready to use\nin its `__init__` method.\nThe contents of the two variables (:obj:`self.proportion` and\n:obj:`self.commitOnChange`) will be saved upon closing our widget.\nIn our widget, we won't be setting these variables directly,\nbut will instead use them in conjunction with GUI controls.\n\n\nControls and module `gui`\n*************************\n\nWe will use the :mod:`Orange.widgets.gui` to create/define the gui.\nWith this library, the GUI definition part of the options box is a bit\ndense but rather very short\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-3\n   :end-before: end-snippet-3\n\n\nWe are already familiar with the first part - the Info group\nbox. To make widget nicer, we put a separator between this and Options\nbox. After defining the option box, here is our first serious\n:mod:`~Orange.widgets.gui` control: a :func:`Orange.widgets.gui.spin`.\nThe first parameter specifies its parent widget/layout, in this case\n:obj:`self.optionsBox` (the resulting widget object will automatically\nappend itself to the parent's layout). The second (:obj:`self`) and\nthird (``'proportion'``) define the *property binding* for the spin box.\nI.e. any change in the spin box control will automatically be propagated\nto the :obj:`self.proportions` and vice versa - changing the value of\n`self.proprotions` in the widget code by assignment\n(e.g. ``self.proprotions = 30``) will update the spin box's state to match.\n\nThe rest of the spin box call gives some parameters for the\ncontrol (minimum and maximum value and the step size), tells about the\nlabel which will be placed on the top, and tells it which functions to\ncall when the value in the spin box is changed. We need the first\ncallback to make a data sample and report in the Info box what is the\nsize of the sample, and a second callback to check if we can send this\ndata out. In :mod:`Orange.widgets.gui`, callbacks are either references\nto functions, or a list with references, just like in our case.\n\nWith all of the above, the parameters for the call of\n:func:`Orange.widgets.gui.checkBox` should be clear as well. Notice that\nthis and a call to :func:`Orange.widgets.gui.spin` do not need a parameter\nwhich would tell the control the value for initialization: upon\nconstruction, both controls will be set to the value that is\npertained in the associated setting variable.\n\nThat's it. Notice though that we have, as a default, disabled all\nthe controls in the Options box. This is because at the start of the\nwidget, there is no data to sample from. But this also means that when\nprocess the input tokens, we should take care for enabling and\ndisabling. The data processing and token sending part of our widget\nnow is\n\n\n.. literalinclude:: orange-demo/orangedemo/OWDataSamplerB.py\n   :start-after: start-snippet-4\n   :end-before: end-snippet-4\n\n\nYou can now also inspect the :download:`complete code <orange-demo/orangedemo/OWDataSamplerB.py>`\nof this widget. To distinguish it with a widget we have developed in the\nprevious section, we have designed a special\n:download:`icon <orange-demo/orangedemo/icons/DataSamplerB.svg>` for it.\nIf you wish to test this widget in the Orange Canvas, put its code in\nthe `orangedemo` directory we have created for the previous widget and try\nit out using a schema with a File and Data Table widget.\n\n.. image:: images/schemawithdatasamplerB.png\n\nWell-behaved widgets remember their settings - the state of their\ncheckboxes and radio-buttons, the text in their line edits, the\nselections in their combo boxes and similar.\n\nPersisting defaults\n*******************\nWhen a widget is removed, its settings are stored to be used as defaults\nfor future instances of this widget.\n\nUpdated defaults are stored in user's profile. It's location depends\non the operating system:\n(%APPDATA%\\Orange\\<version>\\widgets on windows,\n~/Library/Application\\ Support/orange/<version>/widgets on macOS,\n~/.local/share/Orange/<version>/widgets on linux)\nOriginal default values can be restored by deleting files from this folder,\nby running Orange from command line with `--clear-widget-settings` option,\nor through Options/Reset Widget Settings menu action.\n\nSchema-only settings\n--------------------\nSome settings have defaults that should not change. For instance, when using\na Paint Data widget, drawn points should be saved in a workflow, but a new\nwidget should always start with a blank page - modified value should not\nbe remembered.\n\nThis can be achieved by declaring a setting with a `schema_only` flag. Such\nsetting is saved with a workflow, but its default value never changes.\n\nContext dependent settings\n**************************\n\nContext dependent settings are settings which depend on the widget's\ninput. For instance, the scatter plot widget contains settings that\nspecify the attributes for x and y axis, and the settings that\ndefine the color, shape and size of the examples in the graph.\n\nAn even more complicated case is the widget for data\nselection with which one can select the examples based on values of\ncertain attributes. Before applying the saved settings, these widgets\nneeds to check their compliance with the domain of the actual data\nset. To be truly useful, context dependent settings needs to save a\nsetting configuration for each particular dataset used. That is, when\ngiven a particular dataset, it has to select the saved settings that\nis applicable and matches best currently used dataset.\n\nSaving, loading and matching contexts is taken care of by context\nhandlers. Currently, there are only two classes of context handlers\nimplemented. The first one is the abstract :class:`ContextHandler`\nand the second one is :class:`DomainContextHandler` in which the\ncontext is defined by the dataset domain and where the settings\ncontain attribute names. The latter should cover most of your needs,\nwhile for more complicated widgets you will need to derive a new\nclasses from it. There may even be some cases in which the context is\nnot defined by the domain, in which case the\n:class:`ContextHandler` will be used as a base for your new\nhandler.\n\nContexts need to be declared, opened and closed. Opening and\nclosing usually takes place (in the opposite order) in the function\nthat handles the data signal. This is how it looks in the scatter plot\n(the code is somewhat simplified for clarity).\n\n.. code-block:: python\n\n    @Input.data\n    def set_data(self, data):\n        self.closeContext()\n        self.data = data\n        self.graph.setData(data)\n\n        self.initAttrValues()\n\n        if data is not None:\n            self.openContext(data.domain)\n\n        self.updateGraph()\n        self.sendSelections()\n\nIn general, the function should go like this:\n\n* Do any clean-up you need, but without clearing any of the settings that need\n  to be saved. Scatter plot needs none.\n* Call ``self.closeContext()``; this ensures that all the context dependent\n  settings (e.g. attribute names from the list boxes) are remembered.\n* Initialize the widget state and set the controls to some defaults as\n  if there were no context retrieving mechanism. Scatter plot does it by\n  calling ``self.initAttrValues()`` which assigns the first two attributes to\n  the x and y axis and the class attribute to the color. At this phase, you\n  shouldn't call any functions that depend on the settings, such as drawing\n  the graph.\n* Call ``self.openContext(data.domain)`` (more about the arguments later).\n  This will search for a suitable context and assign the controls new values\n  if one is found. If there is no saved context that can be used, a new\n  context is created and filled with the default values that were assigned\n  at the previous point.\n* Finally, adjust the widget according to the retrieved controls. Scatter plot\n  now plots the graph by calling ``self.updateGraph()``.\n\nWhen opening the context, we provide the arguments on which the context\ndepends. In case of :class:`DomainContextHandler`, which scatter plot uses, we\ncan give it a :class:`Orange.data.Domain`. Whether a saved context can be\nreused is judged upon the presence of attributes in the domain.\n\nIf the widget is constructed appropriately (that is, if it strictly uses\n:mod:`Orange.widgets.gui` controls instead of the Qt's), no other\nadministration is needed to switch the context.\n\nExcept for declaring the context settings, that is. Scatter plot has this in\nits class definition\n\n.. code-block:: python\n\n    settingsHandler = DomainContextHandler()\n    attr_x = ContextSetting(\"\")\n    attr_y = ContextSetting(\"\")\n\n    auto_send_selection = Setting(True)\n    toolbar_selection = Setting(0)\n    color_settings = Setting(None)\n    selected_schema_index = Setting(0)\n\n\n``settingsHandler = DomainContextHandler()`` declares that Scatter plot uses\n:class:`DomainContextHandler`. The :obj:`attr_x` and :obj:`attr_y` are\ndeclared as :class:`~Orange.widgets.settings.ContextSetting`.\n\n\nMigrations\n**********\n\nAt the beginning of this section of the tutorial, we created a widget with\na setting called proportion, which contains a value between 0 and 100. But\nimagine that for some reason, we are not satisfied with the value any more\nand decide that the setting should hold a value between 0 and 1.\n\nWe update the setting's default value, modify the appropriate code and we\nare done. That is, until someone that has already used the old version of\nthe widget open the new one and the widget crashes. Remember, when the\nwidget is opened, it has the same settings that were used the last time.\n\nIs there anything we can do, as settings are replaced with saved before\nthe __init__ function is called? There is! Migrations to the rescue.\n\nWidget has a special attribute called `settings_version`. All widgets start\nwith a settings_version of 1. When incompatible changes are done to the\nwidget's settings, its settings_version should be increased. But increasing\nthe version by it self does not solve our problems. While the widget now\nknows that it uses different settings, the old ones are still broken and\nneed to be updated before they can be used with the new widget. This can be\naccomplished by reimplementing widget's methods `migrate_settings`\n(for ordinary settings) and `migrate_context` (for context settings).\nBoth method are called with the old object and the version of the settings\nstored with it.\n\nIf we bumped settings_version from 1 to 2 when we did the above mentioned\nchange, our migrate_settings method would look like this:\n\n.. code-block:: python\n\n    def migrate_settings(settings, version):\n       if version < 2:\n         if \"proportion\" in settings:\n            settings[\"proportion\"] = settings[\"proportion\"] / 100\n\nYour migration rules can be simple or complex, but try to avoid simply\nforgetting the values, as settings are also used in saved workflows.\nImagine opening a complex workflow you have designed a year ago with the\nnew version of Orange and finding out that all the settings are back to\ndefault. Not fun!\n\n.. warning::\n\n   If you change the format of an existing setting in a backwards-incompatible\n   way, you will also want to *change the name* of that setting. Otherwise,\n   older versions of Orange won't be able to load workflows with the new\n   setting format.\n\nThere are two helper functions you can use.\n:obj:`Orange.widget.settings.rename_settings(settings, old_name, new_name)`\ndoes the obvious operation on `settings`, which can be either a dictionary\nor a context, thus it can be called from `migrate_settings` or\n`migrate_context`.\n\nAnother common operation may be upgrading your widget from storing variable\nnames (as `str`) to storing variables (instances of classes derived from\n`Variable`). In a typical scenario, this happens when combo boxes are upgraded to\nusing models. Function\n:obj:`Orange.widget.settings.migrate_str_to_variable(settings, names=None)`\nmakes the necessary changes to the settings listed in `names`. `names` can be\na list of setting names, a single string or `None`. In the latter case, all\nsettings that may refer to variables (that is two-elements tuples consisting\nof a string and an int) are migrated.\n\nWhat about situations in which some context settings become inapplicable due\nto some changes in the widget? For instance, a widget that used to accept any\nkind of variables is modified so that it requires a numeric variable?\nContext with categorical variables will match and be reused ... and crash the\nwidget. In these (rare) cases, `migrate_context` must raise exception\n:obj:`Orange.widget.settings.IncompatibleContext` and the context will be\nremoved.\n\nSo take some time, write the migrations and do not forget to bump the\n`settings_version` when you do breaking changes.\n",
            "header": {
                "file": {
                    "path": "doc/development/source/tutorial-settings.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "2e65ef3d3",
                "new_commit_hash": "9c679c2b3",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/doc/development/source/tutorial-settings.rst"
            },
            "plus_file": {
                "path": "b/doc/development/source/tutorial-settings.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 316,
                            "length": 8
                        },
                        "new_range": {
                            "start": 316,
                            "length": 16
                        },
                        "section": "using models. Function"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": ":obj:`Orange.widget.settings.migrate_str_to_variable(settings, names=None)`",
                                "type": "context"
                            },
                            {
                                "content": "makes the necessary changes to the settings listed in `names`. `names` can be",
                                "type": "context"
                            },
                            {
                                "content": "a list of setting names, a single string or `None`. In the latter case, all",
                                "type": "context"
                            },
                            {
                                "content": "settings that may refer to variables (that is two-elements tuples constisting",
                                "type": "deleted"
                            },
                            {
                                "content": "settings that may refer to variables (that is two-elements tuples consisting",
                                "type": "added"
                            },
                            {
                                "content": "of a string and an int) are migrated.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "What about situations in which some context settings become inapplicable due",
                                "type": "added"
                            },
                            {
                                "content": "to some changes in the widget? For instance, a widget that used to accept any",
                                "type": "added"
                            },
                            {
                                "content": "kind of variables is modified so that it requires a numeric variable?",
                                "type": "added"
                            },
                            {
                                "content": "Context with categorical variables will match and be reused ... and crash the",
                                "type": "added"
                            },
                            {
                                "content": "widget. In these (rare) cases, `migrate_context` must raise exception",
                                "type": "added"
                            },
                            {
                                "content": ":obj:`Orange.widget.settings.IncompatibleContext` and the context will be",
                                "type": "added"
                            },
                            {
                                "content": "removed.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "So take some time, write the migrations and do not forget to bump the",
                                "type": "context"
                            },
                            {
                                "content": "`settings_version` when you do breaking changes.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "2d9617bd0cb1f0ba61771258410ab8fae8e7e24d^",
    "new_commit_hash": "2d9617bd0cb1f0ba61771258410ab8fae8e7e24d",
    "commit_message": "Settings migration: Allow rejecting a context",
    "commit_date": "2018-10-19T20:23:17+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "2d9617bd0cb1f0ba61771258410ab8fae8e7e24d",
    "test_file_codes": [
        "import pickle\nfrom copy import copy, deepcopy\nfrom io import BytesIO\nfrom unittest import TestCase\nfrom unittest.mock import Mock, patch, call\nfrom Orange.widgets.settings import (\n    ContextHandler, ContextSetting, Context, Setting, SettingsPrinter,\n    VERSION_KEY, IncompatibleContext\n)\n\n__author__ = 'anze'\n\n\nclass SimpleWidget:\n    settings_version = 1\n\n    setting = Setting(42)\n    schema_only_setting = Setting(None, schema_only=True)\n\n    context_setting = ContextSetting(42)\n\n    migrate_settings = Mock()\n    migrate_context = Mock()\n\n\nclass DummyContext(Context):\n    id = 0\n\n    def __init__(self, version=None):\n        super().__init__()\n        DummyContext.id += 1\n        self.id = DummyContext.id\n        if version:\n            self.values[VERSION_KEY] = version\n\n    def __repr__(self):\n        return \"Context(id={})\".format(self.id)\n    __str__ = __repr__\n\n    def __eq__(self, other):\n        if not isinstance(other, DummyContext):\n            return False\n        return self.id == other.id\n\n\ndef create_defaults_file(contexts):\n    b = BytesIO()\n    pickle.dump({\"x\": 5}, b)\n    pickle.dump(contexts, b)\n    b.seek(0)\n    return b\n\n\nclass TestContextHandler(TestCase):\n    def test_read_defaults(self):\n        contexts = [DummyContext() for _ in range(3)]\n\n        handler = ContextHandler()\n        handler.widget_class = SimpleWidget\n\n        # Old settings without version\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context.reset_mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.read_defaults_file(create_defaults_file(contexts))\n        self.assertSequenceEqual(handler.global_contexts, contexts)\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_initialize(self):\n        handler = ContextHandler()\n        handler.provider = Mock()\n        handler.widget_class = SimpleWidget\n\n        # Context settings from data\n        widget = SimpleWidget()\n        context_settings = [DummyContext()]\n        handler.initialize(widget, {'context_settings': context_settings})\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, context_settings)\n\n        # Default (global) context settings\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        self.assertTrue(hasattr(widget, 'context_settings'))\n        self.assertEqual(widget.context_settings, handler.global_contexts)\n\n    def test_initialize_migrates_contexts(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        # Old settings without version\n        contexts = [DummyContext() for _ in range(3)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n        migrate_context.assert_has_calls([call(c, 0) for c in contexts])\n\n        # Settings with version\n        contexts = [DummyContext(version=i) for i in range(1, 4)]\n        migrate_context = Mock()\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=deepcopy(contexts)))\n        migrate_context.assert_has_calls([call(c, c.values[VERSION_KEY]) for c in contexts])\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n\n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n\n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n\n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n            handler.initialize(widget, dict(context_settings=contexts))\n            contexts = widget.context_settings\n            self.assertEqual(len(contexts), 3)\n            self.assertTrue(\n                all(context.foo == i\n                    for i, context in enumerate(contexts)))\n\n    def test_fast_save(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n\n        context = widget.current_context = handler.new_context()\n        handler.fast_save(widget, 'context_setting', 55)\n        self.assertEqual(context.values['context_setting'], 55)\n        self.assertEqual(handler.known_settings['context_setting'].default,\n                         SimpleWidget.context_setting.default)\n\n    def test_find_or_create_context(self):\n        widget = SimpleWidget()\n        handler = ContextHandler()\n        handler.match = lambda context, i: (context.i == i) * 2\n        handler.clone_context = lambda context, i: copy(context)\n\n        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)\n                                              for i in range(1, 10))\n\n        # finding a perfect match in global_contexts should copy it to\n        # the front of context_settings (and leave globals as-is)\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 7)\n        self.assertEqual(context.i, 7)\n        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n        # finding a perfect match in context_settings should move it to\n        # the front of the list\n        widget.context_settings = [c2, c5]\n        handler.global_contexts = [c3, c7]\n        context, new = handler.find_or_create_context(widget, 5)\n        self.assertEqual(context.i, 5)\n        self.assertEqual([c.i for c in widget.context_settings], [5, 2])\n        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])\n\n    def test_pack_settings_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n\n        widget = SimpleWidget()\n        handler.initialize(widget)\n        widget.context_setting = [DummyContext() for _ in range(3)]\n\n        settings = handler.pack_data(widget)\n        self.assertIn(\"context_settings\", settings)\n        for c in settings[\"context_settings\"]:\n            self.assertIn(VERSION_KEY, c.values)\n\n    def test_write_defaults_stores_version(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.current_context = None\n        widget.context_settings = [DummyContext() for _ in range(3)]\n        handler.update_defaults(widget)\n\n        f = BytesIO()\n        f.close = lambda: None\n        with patch(\"builtins.open\", Mock(return_value=f)):\n            handler.write_defaults()\n            f.seek(0)\n            pickle.load(f)  # settings\n            contexts = pickle.load(f)\n            for c in contexts:\n                self.assertEqual(c.values.get(\"__version__\", 0xBAD), 1)\n\n    def test_close_context(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        widget.storeSpecificSettings = Mock()\n        handler.initialize(widget)\n        widget.schema_only_setting = 0xD06F00D\n        widget.current_context = handler.new_context()\n        handler.close_context(widget)\n        self.assertEqual(widget.schema_only_setting, 0xD06F00D)\n\n\nclass TestSettingsPrinter(TestCase):\n    def test_formats_contexts(self):\n        settings = dict(key1=1, key2=2,\n                        context_settings=[\n                            Context(param1=1, param2=2,\n                                    values=dict(value1=1,\n                                                value2=2)),\n                            Context(param1=3, param2=4,\n                                    values=dict(value1=5,\n                                                value2=6))\n                        ])\n        pp = SettingsPrinter()\n\n        output = pp.pformat(settings)\n        # parameter of all contexts should be visible in the output\n        self.assertIn(\"param1=1\", output)\n        self.assertIn(\"param2=2\", output)\n        self.assertIn(\"param1=3\", output)\n        self.assertIn(\"param2=4\", output)\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nrunning build_ext\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpg9iwz7ur/tmp\ncreating /tmp/tmpg9iwz7ur/tmp/tmpg9iwz7ur\ncompile options: '-MMD -MF /tmp/tmpg9iwz7ur/file.c.d -c'\ncc: /tmp/tmpg9iwz7ur/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpxxxrozxr/tmp\ncreating /tmp/tmpxxxrozxr/tmp/tmpxxxrozxr\ncompile options: '-MMD -MF /tmp/tmpxxxrozxr/file.c.d -c'\ncc: /tmp/tmpxxxrozxr/file.c\ncustomize UnixCCompiler using build_ext\nbuilding 'Orange.classification._simple_tree' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_simple_tree.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._tree_scorers' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_tree_scorers.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_valuecount.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_contingency.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_contingency.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_io.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_io.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_variable.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_variable.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/distance/_distance.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/distance/_distance.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/preprocess/_discretize.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/preprocess/_relieff.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/widgets/utils/_grid_density.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nrunning develop\nrunning build_scripts\nrunning egg_info\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncreating Orange3.egg-info\nwriting Orange3.egg-info/PKG-INFO\nwriting dependency_links to Orange3.egg-info/dependency_links.txt\nwriting entry points to Orange3.egg-info/entry_points.txt\nwriting requirements to Orange3.egg-info/requires.txt\nwriting top-level names to Orange3.egg-info/top_level.txt\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest template 'MANIFEST.in'\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.html' under directory 'Orange/canvas'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpfm_k2roz/tmp\ncreating /tmp/tmpfm_k2roz/tmp/tmpfm_k2roz\ncompile options: '-MMD -MF /tmp/tmpfm_k2roz/file.c.d -c'\ncc: /tmp/tmpfm_k2roz/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmptv70ak3d/tmp\ncreating /tmp/tmptv70ak3d/tmp/tmptv70ak3d\ncompile options: '-MMD -MF /tmp/tmptv70ak3d/file.c.d -c'\ncc: /tmp/tmptv70ak3d/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.17.0.dev0+2d9617b to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d\nProcessing dependencies for Orange3==3.17.0.dev0+2d9617b\nSearching for xlrd==2.0.1\nBest match: xlrd 2.0.1\nAdding xlrd 2.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for setuptools==59.8.0\nBest match: setuptools 59.8.0\nAdding setuptools 59.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for serverfiles==0.3.1\nBest match: serverfiles 0.3.1\nAdding serverfiles 0.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for scipy==1.7.3\nBest match: scipy 1.7.3\nAdding scipy 1.7.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for scikit-learn==1.0.2\nBest match: scikit-learn 1.0.2\nAdding scikit-learn 1.0.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for python-louvain==0.16\nBest match: python-louvain 0.16\nAdding python-louvain 0.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for pyqtgraph==0.12.4\nBest match: pyqtgraph 0.12.4\nAdding pyqtgraph 0.12.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for pip==24.0\nBest match: pip 24.0\nAdding pip 24.0 to easy-install.pth file\nInstalling pip script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for numpy==1.17.5\nBest match: numpy 1.17.5\nAdding numpy 1.17.5 to easy-install.pth file\nInstalling f2py script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for networkx==2.6.3\nBest match: networkx 2.6.3\nAdding networkx 2.6.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for matplotlib==3.5.3\nBest match: matplotlib 3.5.3\nAdding matplotlib 3.5.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for keyrings.alt==4.2.0\nBest match: keyrings.alt 4.2.0\nAdding keyrings.alt 4.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for keyring==24.1.1\nBest match: keyring 24.1.1\nAdding keyring 24.1.1 to easy-install.pth file\nInstalling keyring script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for joblib==1.3.2\nBest match: joblib 1.3.2\nAdding joblib 1.3.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for docutils==0.20.1\nBest match: docutils 0.20.1\nAdding docutils 0.20.1 to easy-install.pth file\nInstalling docutils script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for chardet==5.2.0\nBest match: chardet 5.2.0\nAdding chardet 5.2.0 to easy-install.pth file\nInstalling chardetect script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for Bottleneck==1.4.0\nBest match: Bottleneck 1.4.0\nAdding Bottleneck 1.4.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for AnyQt==0.2.0\nBest match: AnyQt 0.2.0\nAdding AnyQt 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for requests==2.31.0\nBest match: requests 2.31.0\nAdding requests 2.31.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for threadpoolctl==3.1.0\nBest match: threadpoolctl 3.1.0\nAdding threadpoolctl 3.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for Pillow==9.5.0\nBest match: Pillow 9.5.0\nAdding Pillow 9.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for fonttools==4.38.0\nBest match: fonttools 4.38.0\nAdding fonttools 4.38.0 to easy-install.pth file\nInstalling fonttools script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for pyparsing==3.1.4\nBest match: pyparsing 3.1.4\nAdding pyparsing 3.1.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for kiwisolver==1.4.5\nBest match: kiwisolver 1.4.5\nAdding kiwisolver 1.4.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for cycler==0.11.0\nBest match: cycler 0.11.0\nAdding cycler 0.11.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for packaging==24.0\nBest match: packaging 24.0\nAdding packaging 24.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for python-dateutil==2.9.0.post0\nBest match: python-dateutil 2.9.0.post0\nAdding python-dateutil 2.9.0.post0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for jaraco.classes==3.2.3\nBest match: jaraco.classes 3.2.3\nAdding jaraco.classes 3.2.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for SecretStorage==3.3.3\nBest match: SecretStorage 3.3.3\nAdding SecretStorage 3.3.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for importlib-metadata==6.7.0\nBest match: importlib-metadata 6.7.0\nAdding importlib-metadata 6.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for jeepney==0.8.0\nBest match: jeepney 0.8.0\nAdding jeepney 0.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for importlib-resources==5.12.0\nBest match: importlib-resources 5.12.0\nAdding importlib-resources 5.12.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for idna==3.10\nBest match: idna 3.10\nAdding idna 3.10 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for certifi==2024.12.14\nBest match: certifi 2024.12.14\nAdding certifi 2024.12.14 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for urllib3==2.0.7\nBest match: urllib3 2.0.7\nAdding urllib3 2.0.7 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for charset-normalizer==3.4.1\nBest match: charset-normalizer 3.4.1\nAdding charset-normalizer 3.4.1 to easy-install.pth file\nInstalling normalizer script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for typing-extensions==4.7.1\nBest match: typing-extensions 4.7.1\nAdding typing-extensions 4.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for six==1.17.0\nBest match: six 1.17.0\nAdding six 1.17.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for more-itertools==9.1.0\nBest match: more-itertools 9.1.0\nAdding more-itertools 9.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for cryptography==44.0.0\nBest match: cryptography 44.0.0\nAdding cryptography 44.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for zipp==3.15.0\nBest match: zipp 3.15.0\nAdding zipp 3.15.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for cffi==1.15.1\nBest match: cffi 1.15.1\nAdding cffi 1.15.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nSearching for pycparser==2.21\nBest match: pycparser 2.21\nAdding pycparser 2.21 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.17.0.dev0+2d9617b\nVerifying Orange installation...\n✅ Orange installation successful!\nSuccessfully installed orange using Python 3.7\n",
    "setup_res_stderr": "Using CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 18 packages in 73ms\nPrepared 18 packages in 31ms\nInstalled 18 packages in 154ms\n + cython==0.29.37\n + exceptiongroup==1.2.2\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + numpy==1.17.5\n + packaging==24.0\n + pluggy==1.2.0\n + pyqt5==5.15.10\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.13.0\n + pyqtwebengine==5.15.6\n + pyqtwebengine-qt5==5.15.16\n + pytest==7.4.4\n + setuptools==59.8.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + wheel==0.42.0\n + zipp==3.15.0\nResolved 31 packages in 138ms\nInstalled 26 packages in 467ms\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + idna==3.10\n + importlib-resources==5.12.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + joblib==1.3.2\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + more-itertools==9.1.0\n + networkx==2.6.3\n + pip==24.0\n + pycparser==2.21\n + python-louvain==0.16\n + requests==2.31.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\nResolved 14 packages in 56ms\nInstalled 11 packages in 115ms\n + anyqt==0.2.0\n + cycler==0.11.0\n + docutils==0.20.1\n + fonttools==4.38.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + pillow==9.5.0\n + pyparsing==3.1.4\n + pyqtgraph==0.12.4\n + python-dateutil==2.9.0.post0\n + six==1.17.0\nResolved 2 packages in 3ms\nInstalled 2 packages in 40ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nResolved 5 packages in 43ms\nInstalled 2 packages in 481ms\n + pandas==1.3.5\n + pytz==2024.2\nAudited 2 packages in 1ms\nOrange/classification/_simple_tree.c: In function ‘gain_ratio_c’:\nOrange/classification/_simple_tree.c:63:9: warning: implicit declaration of function ‘qsort_r’; did you mean ‘qsort’? [-Wimplicit-function-declaration]\n   63 |         qsort_r(base, nel, size, compar, thunk)\n      |         ^~~~~~~\nOrange/classification/_simple_tree.c:147:9: note: in expansion of macro ‘QSORT_R_FUNC’\n  147 |         QSORT_R_FUNC(examples, size, sizeof(struct Example), (void*) &compar_attr, compar_examples);\n      |         ^~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_2find_threshold_entropy’:\nOrange/classification/_tree_scorers.c:3115:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3115 |   __pyx_t_7 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_6find_threshold_MSE’:\nOrange/classification/_tree_scorers.c:4619:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4619 |   __pyx_t_1 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_8find_binarization_MSE’:\nOrange/classification/_tree_scorers.c:5396:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5396 |           for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5517:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5517 |           __pyx_t_27 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5523:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5523 |           __pyx_t_27 = (((__pyx_v_N - __pyx_v_left) >= __pyx_v_min_leaf) != 0);\n      |                                                     ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_14compute_predictions_csr’:\nOrange/classification/_tree_scorers.c:7051:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7051 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_16compute_predictions_csc’:\nOrange/classification/_tree_scorers.c:7741:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7741 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7801:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7801 |               __pyx_t_17 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_18 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/data/_io.c: In function ‘__pyx_pf_6Orange_4data_3_io_sparse_read_float.constprop’:\nOrange/data/_io.c:3881:24: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3881 |           __pyx_v_decs = (__pyx_v_decs / 10.0);\n      |           ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:4070:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4070 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 221, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:480:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  480 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1301:7: note: ‘__pyx_v_attr_index’ was declared here\n 1301 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:2935:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2935 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:581:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/setuptools/command/easy_install.py:159: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.\n  EasyInstallDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d/.venv/lib/python3.7/site-packages/setuptools/command/egg_info.py:628: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'.\nPlease extend command classes from setuptools instead of distutils.\n  SetuptoolsDeprecationWarning\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d\ncollected 10 items\n\nr2e_tests/test_1.py ..........                                           [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestContextHandler::test_close_context\nPASSED r2e_tests/test_1.py::TestContextHandler::test_fast_save\nPASSED r2e_tests/test_1.py::TestContextHandler::test_find_or_create_context\nPASSED r2e_tests/test_1.py::TestContextHandler::test_initialize\nPASSED r2e_tests/test_1.py::TestContextHandler::test_initialize_migrates_contexts\nPASSED r2e_tests/test_1.py::TestContextHandler::test_migrates_settings_removes_incompatible\nPASSED r2e_tests/test_1.py::TestContextHandler::test_pack_settings_stores_version\nPASSED r2e_tests/test_1.py::TestContextHandler::test_read_defaults\nPASSED r2e_tests/test_1.py::TestContextHandler::test_write_defaults_stores_version\nPASSED r2e_tests/test_1.py::TestSettingsPrinter::test_formats_contexts\n============================== 10 passed in 0.60s ==============================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2d9617bd0cb1f0ba61771258410ab8fae8e7e24d\ncollected 10 items\n\nr2e_tests/test_1.py .....F....                                           [100%]\n\n=================================== FAILURES ===================================\n________ TestContextHandler.test_migrates_settings_removes_incompatible ________\n\nself = <r2e_tests.test_1.TestContextHandler testMethod=test_migrates_settings_removes_incompatible>\n\n    def test_migrates_settings_removes_incompatible(self):\n        handler = ContextHandler()\n        handler.bind(SimpleWidget)\n    \n        widget = SimpleWidget()\n    \n        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]\n    \n        def migrate_context(context, _):\n            if context.foo == 13:\n                raise IncompatibleContext()\n    \n        with patch.object(SimpleWidget, \"migrate_context\", migrate_context):\n>           handler.initialize(widget, dict(context_settings=contexts))\n\nr2e_tests/test_1.py:127: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/settings.py:615: in initialize\n    self._migrate_contexts(instance.context_settings)\nOrange/widgets/settings.py:628: in _migrate_contexts\n    self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\ncontext = <Orange.widgets.settings.Context object at 0x7f05b374ebd0>, _ = 0\n\n    def migrate_context(context, _):\n        if context.foo == 13:\n>           raise IncompatibleContext()\nE           Orange.widgets.settings.IncompatibleContext\n\nr2e_tests/test_1.py:124: IncompatibleContext\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestContextHandler::test_close_context\nPASSED r2e_tests/test_1.py::TestContextHandler::test_fast_save\nPASSED r2e_tests/test_1.py::TestContextHandler::test_find_or_create_context\nPASSED r2e_tests/test_1.py::TestContextHandler::test_initialize\nPASSED r2e_tests/test_1.py::TestContextHandler::test_initialize_migrates_contexts\nPASSED r2e_tests/test_1.py::TestContextHandler::test_pack_settings_stores_version\nPASSED r2e_tests/test_1.py::TestContextHandler::test_read_defaults\nPASSED r2e_tests/test_1.py::TestContextHandler::test_write_defaults_stores_version\nPASSED r2e_tests/test_1.py::TestSettingsPrinter::test_formats_contexts\nFAILED r2e_tests/test_1.py::TestContextHandler::test_migrates_settings_removes_incompatible\n========================= 1 failed, 9 passed in 0.57s ==========================\n",
    "old_commit_res_stderr": ""
}
Orange/widgets/settings.py Orange/widgets/tests/test_context_handler.py doc/development/source/tutorial-settings.rst
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Context migration fails to remove incompatible contexts, causing initialization errors

**Description:**
When initializing the `ContextHandler` with a mix of compatible and incompatible contexts, the migration process does not remove the incompatible contexts as expected. Instead, it raises an `IncompatibleContext` error, preventing successful initialization.

**Example Code:**
```python
handler = ContextHandler()
handler.bind(SimpleWidget)

widget = SimpleWidget()
contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]

def migrate_context(context, _):
    if context.foo == 13:
        raise IncompatibleContext()

handler.initialize(widget, dict(context_settings=contexts))
# Expected: Incompatible contexts with foo=13 should be removed
# Actual: IncompatibleContext error is raised, and contexts are not removed
```

**Expected Behavior:**
During initialization, contexts that are incompatible (e.g., those that cause `IncompatibleContext` to be raised) should be automatically removed, allowing the `ContextHandler` to proceed with only the compatible contexts.

**Actual Behavior:**
The `ContextHandler` does not remove incompatible contexts, resulting in an `IncompatibleContext` error being raised and preventing successful initialization.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/settings.py
"""Widget Settings and Settings Handlers

Settings are used to declare widget attributes that persist through sessions.
When widget is removed or saved to a schema file, its settings are packed,
serialized and stored. When a new widget is created, values of attributes
marked as settings are read from disk. When schema is loaded, attribute values
are set to one stored in schema.

Each widget has its own SettingsHandler that takes care of serializing and
storing of settings and SettingProvider that is incharge of reading and
writing the setting values.

All widgets extending from OWWidget use SettingsHandler, unless they
declare otherwise. SettingsHandler ensures that setting attributes
are replaced with default (last used) setting values when the widget is
initialized and stored when the widget is removed.

Widgets with settings whose values depend on the widget inputs use
settings handlers based on ContextHandler. These handlers have two
additional methods, open_context and close_context.

open_context is called when widgets receives new data. It finds a suitable
context and sets the widget attributes to the values stored in context.
If no suitable context exists, a new one is created and values from widget
are copied to it.

close_context stores values that were last used on the widget to the context
so they can be used alter. It should be called before widget starts modifying
(initializing) the value of the setting attributes.
"""

import copy
import itertools
import os
import logging
import pickle
import pprint
import time
import warnings
from operator import itemgetter

from Orange.data import Domain, Variable
from Orange.misc.environ import widget_settings_dir
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.utils import vartype

log = logging.getLogger(__name__)

__all__ = ["Setting", "SettingsHandler", "SettingProvider",
           "ContextSetting", "ContextHandler",
           "DomainContextHandler", "PerfectDomainContextHandler",
           "ClassValuesContextHandler", "widget_settings_dir"]

_IMMUTABLES = (str, int, bytes, bool, float, tuple)

VERSION_KEY = "__version__"


class Setting:
    """Description of a setting.
    """

    # Settings are automatically persisted to disk
    packable = True

    # Setting is only persisted to schema (default value does not change)
    schema_only = False

    def __new__(cls, default, *args, **kwargs):
        """A misleading docstring for providing type hints for Settings

        :type: default: T
        :rtype: T
        """
        return super().__new__(cls)

    def __init__(self, default, **data):
        self.name = None  # Name gets set in widget's meta class
        self.default = default
        self.__dict__.update(data)

    def __str__(self):
        return '{0} "{1}"'.format(self.__class__.__name__, self.name)

    __repr__ = __str__

    def __getnewargs__(self):
        return (self.default, )


class SettingProvider:
    """A hierarchical structure keeping track of settings belonging to
    a class and child setting providers.

    At instantiation, it creates a dict of all Setting and SettingProvider
    members of the class. This dict is used to get/set values of settings
    from/to the instances of the class this provider belongs to.
    """

    def __init__(self, provider_class):
        """ Construct a new instance of SettingProvider.

        Traverse provider_class members and store all instances of
        Setting and SettingProvider.

        Parameters
        ----------
        provider_class : class
            class containing settings definitions
        """
        self.name = ""
        self.provider_class = provider_class
        self.providers = {}
        """:type: dict[str, SettingProvider]"""
        self.settings = {}
        """:type: dict[str, Setting]"""
        self.initialization_data = None

        for name in dir(provider_class):
            value = getattr(provider_class, name, None)
            if isinstance(value, Setting):
                value = copy.deepcopy(value)
                value.name = name
                self.settings[name] = value
            if isinstance(value, SettingProvider):
                value = copy.deepcopy(value)
                value.name = name
                self.providers[name] = value

    def initialize(self, instance, data=None):
        """Initialize instance settings to their default values.

        Mutable values are (shallow) copied before they are assigned to the
        widget. Immutable are used as-is.

        Parameters
        ----------
        instance : OWWidget
            widget instance to initialize
        data : Optional[dict]
            optional data used to override the defaults
            (used when settings are loaded from schema)
        """
        if data is None and self.initialization_data is not None:
            data = self.initialization_data

        self._initialize_settings(instance, data)
        self._initialize_providers(instance, data)

    def _initialize_settings(self, instance, data):
        if data is None:
            data = {}
        for name, setting in self.settings.items():
            value = data.get(name, setting.default)
            if isinstance(value, _IMMUTABLES):
                setattr(instance, name, value)
            else:
                setattr(instance, name, copy.copy(value))

    def _initialize_providers(self, instance, data):
        if not data:
            return

        for name, provider in self.providers.items():
            if name not in data:
                continue

            member = getattr(instance, name, None)
            if member is None or isinstance(member, SettingProvider):
                provider.store_initialization_data(data[name])
            else:
                provider.initialize(member, data[name])

    def store_initialization_data(self, initialization_data):
        """Store initialization data for later use.

        Used when settings handler is initialized, but member for this
        provider does not exists yet (because handler.initialize is called in
        __new__, but member will be created in __init__.

        Parameters
        ----------
        initialization_data : dict
            data to be used for initialization when the component is created
        """
        self.initialization_data = initialization_data

    @staticmethod
    def _default_packer(setting, instance):
        """A simple packet that yields setting name and value.

        Parameters
        ----------
        setting : Setting
        instance : OWWidget
        """
        if setting.packable:
            if hasattr(instance, setting.name):
                yield setting.name, getattr(instance, setting.name)
            else:
                warnings.warn("{0} is declared as setting on {1} "
                              "but not present on instance."
                              .format(setting.name, instance))

    def pack(self, instance, packer=None):
        """Pack instance settings in a name:value dict.

        Parameters
        ----------
        instance : OWWidget
            widget instance
        packer: callable (Setting, OWWidget) -> Generator[(str, object)]
            optional packing function
            it will be called with setting and instance parameters and
            should yield (name, value) pairs that will be added to the
            packed_settings.
        """
        if packer is None:
            packer = self._default_packer

        packed_settings = dict(itertools.chain(
            *(packer(setting, instance) for setting in self.settings.values())
        ))

        packed_settings.update({
            name: provider.pack(getattr(instance, name), packer)
            for name, provider in self.providers.items()
            if hasattr(instance, name)
        })
        return packed_settings

    def unpack(self, instance, data):
        """Restore settings from data to the instance.

        Parameters
        ----------
        instance : OWWidget
            instance to restore settings to
        data : dict
            packed data
        """
        for setting, data, instance in self.traverse_settings(data, instance):
            if setting.name in data and instance is not None:
                setattr(instance, setting.name, data[setting.name])

    def get_provider(self, provider_class):
        """Return provider for provider_class.

        If this provider matches, return it, otherwise pass
        the call to child providers.

        Parameters
        ----------
        provider_class : class
        """
        if issubclass(provider_class, self.provider_class):
            return self

        for subprovider in self.providers.values():
            provider = subprovider.get_provider(provider_class)
            if provider:
                return provider

    def traverse_settings(self, data=None, instance=None):
        """Generator of tuples (setting, data, instance) for each setting
        in this and child providers..

        Parameters
        ----------
        data : dict
            dictionary with setting values
        instance : OWWidget
            instance matching setting_provider
        """
        data = data if data is not None else {}

        for setting in self.settings.values():
            yield setting, data, instance

        for provider in self.providers.values():
            data_ = data.get(provider.name, {})
            instance_ = getattr(instance, provider.name, None)
            for setting, component_data, component_instance in \
                    provider.traverse_settings(data_, instance_):
                yield setting, component_data, component_instance


class SettingsHandler:
    """Reads widget setting files and passes them to appropriate providers."""

    def __init__(self):
        """Create a setting handler template.

        Used in class definition. Bound instance will be created
        when SettingsHandler.create is called.
        """
        self.widget_class = None
        self.provider = None
        """:type: SettingProvider"""
        self.defaults = {}
        self.known_settings = {}

    @staticmethod
    def create(widget_class, template=None):
        """Create a new settings handler based on the template and bind it to
        widget_class.

        Parameters
        ----------
        widget_class : class
        template : SettingsHandler
            SettingsHandler to copy setup from

        Returns
        -------
        SettingsHandler
        """

        if template is None:
            template = SettingsHandler()

        setting_handler = copy.copy(template)
        setting_handler.defaults = {}
        setting_handler.bind(widget_class)
        return setting_handler

    def bind(self, widget_class):
        """Bind settings handler instance to widget_class.

        Parameters
        ----------
        widget_class : class
        """
        self.widget_class = widget_class
        self.provider = SettingProvider(widget_class)
        self.known_settings = {}
        self.analyze_settings(self.provider, "")
        self.read_defaults()

    def analyze_settings(self, provider, prefix):
        """Traverse through all settings known to the provider
        and analyze each of them.

        Parameters
        ----------
        provider : SettingProvider
        prefix : str
            prefix the provider is registered to handle
        """
        for setting in provider.settings.values():
            self.analyze_setting(prefix, setting)

        for name, sub_provider in provider.providers.items():
            new_prefix = '{0}{1}.'.format(prefix or '', name)
            self.analyze_settings(sub_provider, new_prefix)

    def analyze_setting(self, prefix, setting):
        """Perform any initialization task related to setting.

        Parameters
        ----------
        prefix : str
        setting : Setting
        """
        self.known_settings[prefix + setting.name] = setting

    def read_defaults(self):
        """Read (global) defaults for this widget class from a file.
        Opens a file and calls :obj:`read_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        if os.path.isfile(filename):
            settings_file = open(filename, "rb")
            try:
                self.read_defaults_file(settings_file)
            # Unpickling exceptions can be of any type
            # pylint: disable=broad-except
            except Exception as ex:
                warnings.warn("Could not read defaults for widget {0}\n"
                              "The following error occurred:\n\n{1}"
                              .format(self.widget_class, ex))
            finally:
                settings_file.close()

    def read_defaults_file(self, settings_file):
        """Read (global) defaults for this widget class from a file.

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = pickle.load(settings_file)
        self.defaults = {
            key: value
            for key, value in defaults.items()
            if not isinstance(value, Setting)
        }
        self._migrate_settings(self.defaults)

    def write_defaults(self):
        """Write (global) defaults for this widget class to a file.
        Opens a file and calls :obj:`write_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        try:
            settings_file = open(filename, "wb")
            try:
                self.write_defaults_file(settings_file)
            except (EOFError, IOError, pickle.PicklingError) as ex:
                log.error("Could not write default settings for %s (%s).",
                          self.widget_class, type(ex).__name__)
                settings_file.close()
                os.remove(filename)
            else:
                settings_file.close()
        except PermissionError as ex:
            log.error("Could not write default settings for %s (%s).",
                      self.widget_class, type(ex).__name__)

    def write_defaults_file(self, settings_file):
        """Write defaults for this widget class to a file

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = dict(self.defaults)
        defaults[VERSION_KEY] = self.widget_class.settings_version
        pickle.dump(defaults, settings_file, -1)

    def _get_settings_filename(self):
        """Return the name of the file with default settings for the widget"""
        return os.path.join(widget_settings_dir(),
                            "{0.__module__}.{0.__qualname__}.pickle"
                            .format(self.widget_class))

    def initialize(self, instance, data=None):
        """
        Initialize widget's settings.

        Replace all instance settings with their default values.

        Parameters
        ----------
        instance : OWWidget
        data : dict or bytes that unpickle into a dict
            values used to override the defaults
        """
        provider = self._select_provider(instance)

        if isinstance(data, bytes):
            data = pickle.loads(data)
        self._migrate_settings(data)

        if provider is self.provider:
            data = self._add_defaults(data)

        provider.initialize(instance, data)

    def _migrate_settings(self, settings):
        """Ask widget to migrate settings to the latest version."""
        if settings:
            self.widget_class.migrate_settings(settings, settings.pop(VERSION_KEY, 0))

    def _select_provider(self, instance):
        provider = self.provider.get_provider(instance.__class__)
        if provider is None:
            message = "{0} has not been declared as setting provider in {1}. " \
                      "Settings will not be saved/loaded properly. Defaults will be used instead." \
                      .format(instance.__class__, self.widget_class)
            warnings.warn(message)
            provider = SettingProvider(instance.__class__)
        return provider

    def _add_defaults(self, data):
        if data is None:
            return self.defaults

        new_data = self.defaults.copy()
        new_data.update(data)
        return new_data

    def pack_data(self, widget):
        """
        Pack the settings for the given widget. This method is used when
        saving schema, so that when the schema is reloaded the widget is
        initialized with its proper data and not the class-based defaults.
        See :obj:`SettingsHandler.initialize` for detailed explanation of its
        use.

        Inherited classes add other data, in particular widget-specific
        local contexts.

        Parameters
        ----------
        widget : OWWidget
        """
        packed_settings = self.provider.pack(widget)
        packed_settings[VERSION_KEY] = self.widget_class.settings_version
        return packed_settings

    def update_defaults(self, widget):
        """
        Writes widget instance's settings to class defaults. Called when the
        widget is deleted.

        Parameters
        ----------
        widget : OWWidget
        """
        self.defaults = self.provider.pack(widget)
        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):
            if setting.schema_only:
                data.pop(setting.name, None)
        self.write_defaults()

    def fast_save(self, widget, name, value):
        """Store the (changed) widget's setting immediately to the context.

        Parameters
        ----------
        widget : OWWidget
        name : str
        value : object

        """
        if name in self.known_settings:
            setting = self.known_settings[name]
            if not setting.schema_only:
                setting.default = value

    def reset_settings(self, instance):
        """Reset widget settings to defaults

        Parameters
        ----------
        instance : OWWidget
        """
        for setting, _, instance in self.provider.traverse_settings(instance=instance):
            if setting.packable:
                setattr(instance, setting.name, setting.default)


class ContextSetting(Setting):
    """Description of a context dependent setting"""

    OPTIONAL = 0
    IF_SELECTED = 1
    REQUIRED = 2

    # Context settings are not persisted, but are stored in context instead.
    packable = False

    # These flags are not general - they assume that the setting has to do
    # something with the attributes. Large majority does, so this greatly
    # simplifies the declaration of settings in widget at no (visible)
    # cost to those settings that don't need it
    def __init__(self, default, *, not_attribute=False, required=2,
                 exclude_attributes=False, exclude_metas=False, **data):
        super().__init__(default, **data)
        self.not_attribute = not_attribute
        self.exclude_attributes = exclude_attributes
        self.exclude_metas = exclude_metas
        self.required = required


class Context:
    """Class for data thad defines context and
    values that should be applied to widget if given context
    is encountered."""
    def __init__(self, **argkw):
        self.time = time.time()
        self.values = {}
        self.__dict__.update(argkw)

    def __getstate__(self):
        state = dict(self.__dict__)
        for nc in getattr(self, "no_copy", []):
            if nc in state:
                del state[nc]
        return state


class ContextHandler(SettingsHandler):
    """Base class for setting handlers that can handle contexts.

    Classes deriving from it need to implement method `match`.
    """

    NO_MATCH = 0
    PERFECT_MATCH = 2

    MAX_SAVED_CONTEXTS = 50

    def __init__(self):
        super().__init__()
        self.global_contexts = []
        self.known_settings = {}

    def analyze_setting(self, prefix, setting):
        super().analyze_setting(prefix, setting)
        if isinstance(setting, ContextSetting):
            if hasattr(setting, 'selected'):
                self.known_settings[prefix + setting.selected] = setting

    def initialize(self, instance, data=None):
        """Initialize the widget: call the inherited initialization and
        add an attribute 'context_settings' to the widget. This method
        does not open a context."""
        instance.current_context = None
        super().initialize(instance, data)
        if data and "context_settings" in data:
            instance.context_settings = data["context_settings"]
            self._migrate_contexts(instance.context_settings)
        else:
            instance.context_settings = []

    def read_defaults_file(self, settings_file):
        """Call the inherited method, then read global context from the
           pickle."""
        super().read_defaults_file(settings_file)
        self.global_contexts = pickle.load(settings_file)
        self._migrate_contexts(self.global_contexts)

    def _migrate_contexts(self, contexts):
        for context in contexts:
            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))

    def write_defaults_file(self, settings_file):
        """Call the inherited method, then add global context to the pickle."""
        super().write_defaults_file(settings_file)

        def add_version(context):
            context = copy.copy(context)
            context.values = dict(context.values)
            context.values[VERSION_KEY] = self.widget_class.settings_version
            return context

        pickle.dump([add_version(context) for context in self.global_contexts],
                    settings_file, -1)

    def pack_data(self, widget):
        """Call the inherited method, then add local contexts to the dict."""
        data = super().pack_data(widget)
        self.settings_from_widget(widget)
        for context in widget.context_settings:
            context.values[VERSION_KEY] = self.widget_class.settings_version
        data["context_settings"] = widget.context_settings
        return data

    def update_defaults(self, widget):
        """
        Reimplemented from SettingsHandler

        Merge the widgets local contexts into the global contexts and persist
        the settings (including the contexts) to disk.
        """
        self.settings_from_widget(widget)
        globs = self.global_contexts
        assert widget.context_settings is not globs
        ids = {id(c) for c in globs}
        globs += (c for c in widget.context_settings if id(c) not in ids)
        globs.sort(key=lambda c: -c.time)
        del globs[self.MAX_SAVED_CONTEXTS:]

        super().update_defaults(widget)

    def new_context(self, *args):
        """Create a new context."""
        return Context()

    def open_context(self, widget, *args):
        """Open a context by finding one and setting the widget data or
        creating one and fill with the data from the widget."""
        widget.current_context, is_new = \
            self.find_or_create_context(widget, *args)
        if is_new:
            try:
                self.settings_from_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_from_widget in {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_from_widget(widget)
        else:
            try:
                self.settings_to_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_to_widget {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_to_widget(widget)

    def match(self, context, *args):
        """Return the degree to which the stored `context` matches the data
        passed in additional arguments).
        When match returns 0 (ContextHandler.NO_MATCH), the context will not
        be used. When it returns ContextHandler.PERFECT_MATCH, the context
        is a perfect match so no further search is necessary.

        If imperfect matching is not desired, match should only
        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.

        Derived classes must overload this method.
        """
        raise NotImplementedError

    def find_or_create_context(self, widget, *args):
        """Find the best matching context or create a new one if nothing
        useful is found. The returned context is moved to or added to the top
        of the context list."""

        # First search the contexts that were already used in this widget instance
        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)
        # If the exact data was used, reuse the context
        if best_score == self.PERFECT_MATCH:
            return best_context, False

        # Otherwise check if a better match is available in global_contexts
        best_context, best_score = self.find_context(self.global_contexts, args,
                                                     best_score, best_context)
        if best_context:
            context = self.clone_context(best_context, *args)
        else:
            context = self.new_context(*args)
        # Store context in widget instance. It will be pushed to global_contexts
        # when (if) update defaults is called.
        self.add_context(widget.context_settings, context)
        return context, best_context is None

    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):
        """Search the given list of contexts and return the context
         which best matches the given args.

        best_score and best_context can be used to provide base_values.
        """

        for i, context in enumerate(known_contexts):
            score = self.match(context, *args)
            if score == self.PERFECT_MATCH:
                if move_up:
                    self.move_context_up(known_contexts, i)
                return context, score
            if score > best_score:  # NO_MATCH is not OK!
                best_context, best_score = context, score
        return best_context, best_score

    @staticmethod
    def move_context_up(contexts, index):
        """Move the context to the top of the list and set
        the timestamp to current."""
        setting = contexts.pop(index)
        setting.time = time.time()
        contexts.insert(0, setting)

    def add_context(self, contexts, setting):
        """Add the context to the top of the list."""
        contexts.insert(0, setting)
        del contexts[self.MAX_SAVED_CONTEXTS:]

    def clone_context(self, old_context, *args):
        """Construct a copy of the context settings suitable for the context
        described by additional arguments. The method is called by
        find_or_create_context with the same arguments. A class that overloads
        :obj:`match` to accept additional arguments must also overload
        :obj:`clone_context`."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)

        traverse = self.provider.traverse_settings
        for setting, data, _ in traverse(data=context.values):
            if not isinstance(setting, ContextSetting):
                continue

            self.filter_value(setting, data, *args)
        return context

    @staticmethod
    def filter_value(setting, data, *args):
        """Remove values related to setting that are invalid given args."""

    def close_context(self, widget):
        """Close the context by calling :obj:`settings_from_widget` to write
        any relevant widget settings to the context."""
        if widget.current_context is None:
            return

        self.settings_from_widget(widget)
        widget.current_context = None

    def settings_to_widget(self, widget, *args):
        """Apply context settings stored in currently opened context
        to the widget.
        """
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name])
            setattr(instance, setting.name, value)
            if hasattr(setting, "selected") and setting.selected in data:
                setattr(instance, setting.selected, data[setting.selected])

    def settings_from_widget(self, widget, *args):
        """Update the current context with the setting values from the widget.
        """

        context = widget.current_context
        if context is None:
            return

        widget.storeSpecificSettings()

        def packer(setting, instance):
            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):
                value = getattr(instance, setting.name)
                yield setting.name, self.encode_setting(context, setting, value)
                if hasattr(setting, "selected"):
                    yield setting.selected, list(getattr(instance, setting.selected))

        context.values = self.provider.pack(widget, packer=packer)

    def fast_save(self, widget, name, value):
        """Update value of `name` setting in the current context to `value`
        """
        setting = self.known_settings.get(name)
        if isinstance(setting, ContextSetting):
            context = widget.current_context
            if context is None:
                return

            value = self.encode_setting(context, setting, value)
            self.update_packed_data(context.values, name, value)
        else:
            super().fast_save(widget, name, value)

    @staticmethod
    def update_packed_data(data, name, value):
        """Updates setting value stored in data dict"""

        *prefixes, name = name.split('.')
        for prefix in prefixes:
            data = data.setdefault(prefix, {})
        data[name] = value

    def encode_setting(self, context, setting, value):
        """Encode value to be stored in settings dict"""
        return copy.copy(value)

    def decode_setting(self, setting, value):
        """Decode settings value from the setting dict format"""
        return value


class DomainContextHandler(ContextHandler):
    """Context handler for widgets with settings that depend on
    the input dataset. Suitable settings are selected based on the
    data domain."""

    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)

    def __init__(self, *, match_values=0, **kwargs):
        super().__init__()
        self.match_values = match_values

        for name in kwargs:
            warnings.warn(
                "{} is not a valid parameter for DomainContextHandler"
                .format(name), OrangeDeprecationWarning
            )

    def encode_domain(self, domain):
        """
        domain: Orange.data.domain to encode
        return: dict mapping attribute name to type or list of values
                (based on the value of self.match_values attribute)
        """

        match = self.match_values
        encode = self.encode_variables
        if match == self.MATCH_VALUES_CLASS:
            attributes = encode(domain.attributes, False)
            attributes.update(encode(domain.class_vars, True))
        else:
            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)

        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)

        return attributes, metas

    @staticmethod
    def encode_variables(attributes, encode_values):
        """Encode variables to a list mapping name to variable type
        or a list of values."""

        if not encode_values:
            return {v.name: vartype(v) for v in attributes}

        return {v.name: v.values if v.is_discrete else vartype(v)
                for v in attributes}

    def new_context(self, domain, attributes, metas):
        """Create a new context."""
        context = super().new_context()
        context.attributes = attributes
        context.metas = metas
        return context

    def open_context(self, widget, domain):
        if domain is None:
            return None, False

        if not isinstance(domain, Domain):
            domain = domain.domain

        super().open_context(widget, domain, *self.encode_domain(domain))

    def filter_value(self, setting, data, domain, attrs, metas):
        value = data.get(setting.name, None)
        if isinstance(value, list):
            sel_name = getattr(setting, "selected", None)
            selected = set(data.pop(sel_name, []))
            new_selected, new_value = [], []
            for i, item in enumerate(value):
                if self.is_valid_item(setting, item, attrs, metas):
                    if i in selected:
                        new_selected.append(len(new_value))
                    new_value.append(item)

            data[setting.name] = new_value
            if hasattr(setting, 'selected'):
                data[setting.selected] = new_selected
        elif value is not None:
            if (value[1] >= 0 and
                    not self._var_exists(setting, value, attrs, metas)):
                del data[setting.name]

    def settings_to_widget(self, widget, domain, *args):
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name], domain)
            setattr(instance, setting.name, value)
            if hasattr(setting, "selected") and setting.selected in data:
                setattr(instance, setting.selected, data[setting.selected])

    def encode_setting(self, context, setting, value):
        if isinstance(value, list):
            return copy.copy(value)
        elif isinstance(setting, ContextSetting):
            if isinstance(value, str):
                if not setting.exclude_attributes and value in context.attributes:
                    return value, context.attributes[value]
                if not setting.exclude_metas and value in context.metas:
                    return value, context.metas[value]
            elif isinstance(value, Variable):
                return value.name, 100 + vartype(value)
        return copy.copy(value), -2

    def decode_setting(self, setting, value, domain=None):
        if isinstance(value, tuple):
            if value[1] >= 100:
                if domain is None:
                    raise ValueError("Cannot decode variable without domain")
                return domain[value[0]]
            return value[0]
        else:
            return value

    @staticmethod
    def _var_exists(setting, value, attributes, metas):
        if not isinstance(value, tuple) or len(value) != 2:
            return False

        attr_name, attr_type = value
        if attr_type >= 100:
            attr_type -= 100
        return (not setting.exclude_attributes and
                attributes.get(attr_name, -1) == attr_type or
                not setting.exclude_metas and
                metas.get(attr_name, -1) == attr_type)

    def match(self, context, domain, attrs, metas):
        if (attrs, metas) == (context.attributes, context.metas):
            return self.PERFECT_MATCH

        matches = []
        try:
            for setting, data, _ in \
                    self.provider.traverse_settings(data=context.values):
                if not isinstance(setting, ContextSetting):
                    continue
                value = data.get(setting.name, None)

                if isinstance(value, list):
                    matches.append(
                        self.match_list(setting, value, context, attrs, metas))
                elif value is not None:
                    matches.append(
                        self.match_value(setting, value, attrs, metas))
        except IncompatibleContext:
            return self.NO_MATCH

        matches.append((0, 0))
        matched, available = [sum(m) for m in zip(*matches)]

        return matched / available if available else 0.1

    def match_list(self, setting, value, context, attrs, metas):
        """Match a list of values with the given context.
        returns a tuple containing number of matched and all values.
        """
        matched = 0
        if hasattr(setting, 'selected'):
            selected = set(context.values.get(setting.selected, []))
        else:
            selected = set()

        for i, item in enumerate(value):
            if self.is_valid_item(setting, item, attrs, metas):
                matched += 1
            else:
                if setting.required == ContextSetting.REQUIRED:
                    raise IncompatibleContext()
                if setting.IF_SELECTED and i in selected:
                    raise IncompatibleContext()

        return matched, len(value)

    def match_value(self, setting, value, attrs, metas):
        """Match a single value """
        if value[1] < 0:
            return 0, 0

        if self._var_exists(setting, value, attrs, metas):
            return 1, 1
        elif setting.required == setting.OPTIONAL:
            return 0, 1
        else:
            raise IncompatibleContext()

    def is_valid_item(self, setting, item, attrs, metas):
        """Return True if given item can be used with attrs and metas

        Subclasses can override this method to checks data in alternative
        representations.
        """
        if not isinstance(item, tuple):
            return True
        return self._var_exists(setting, item, attrs, metas)


class IncompatibleContext(Exception):
    """Raised when a required variable in context is not available in data."""
    pass


class ClassValuesContextHandler(ContextHandler):
    """Context handler used for widgets that work with
    a single discrete variable"""

    def open_context(self, widget, classes):
        if isinstance(classes, Variable):
            if classes.is_discrete:
                classes = classes.values
            else:
                classes = None

        super().open_context(widget, classes)

    def new_context(self, classes):
        context = super().new_context()
        context.classes = classes
        return context

    def match(self, context, classes):
        if isinstance(classes, Variable) and classes.is_continuous:
            return (self.PERFECT_MATCH if context.classes is None
                    else self.NO_MATCH)
        else:
            return (self.PERFECT_MATCH if context.classes == classes
                    else self.NO_MATCH)


class PerfectDomainContextHandler(DomainContextHandler):
    """Context handler that matches a context only when
    the same domain is available.

    It uses a different encoding than the DomainContextHandler.
    """

    def new_context(self, domain, attributes, class_vars, metas):
        """Same as DomainContextHandler, but also store class_vars"""
        context = super().new_context(domain, attributes, metas)
        context.class_vars = class_vars
        return context

    def clone_context(self, old_context, *args):
        """Copy of context is always valid, since widgets are using
        the same domain."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)
        return context

    def encode_domain(self, domain):
        """Encode domain into tuples (name, type)
        A tuple is returned for each of attributes, class_vars and metas.
        """

        if self.match_values == self.MATCH_VALUES_ALL:
            def _encode(attrs):
                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))
                             for v in attrs)
        else:
            def _encode(attrs):
                return tuple((v.name, vartype(v)) for v in attrs)
        return (_encode(domain.attributes),
                _encode(domain.class_vars),
                _encode(domain.metas))

    def match(self, context, domain, attributes, class_vars, metas):
        """Context only matches when domains are the same"""

        return (self.PERFECT_MATCH
                if (context.attributes == attributes and
                    context.class_vars == class_vars and
                    context.metas == metas)
                else self.NO_MATCH)

    def encode_setting(self, context, setting, value):
        """Same as is domain context handler, but handles separately stored
        class_vars."""

        if isinstance(setting, ContextSetting) and isinstance(value, str):

            def _candidate_variables():
                if not setting.exclude_attributes:
                    yield from itertools.chain(context.attributes,
                                               context.class_vars)
                if not setting.exclude_metas:
                    yield from context.metas

            for aname, atype in _candidate_variables():
                if aname == value:
                    return value, atype

            return value, -1
        else:
            return super().encode_setting(context, setting, value)


class SettingsPrinter(pprint.PrettyPrinter):
    """Pretty Printer that knows how to properly format Contexts."""

    def _format(self, obj, stream, indent, allowance, context, level):
        if not isinstance(obj, Context):
            return super()._format(obj, stream, indent,
                                   allowance, context, level)

        stream.write("Context(")
        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):
            if key == "values":
                continue
            stream.write(key)
            stream.write("=")
            stream.write(self._repr(value, context, level + 1))
            stream.write(",\n")
            stream.write(" " * (indent + 8))
        stream.write("values=")
        stream.write(" ")
        self._format(obj.values, stream, indent+15,
                     allowance+1, context, level + 1)
        stream.write(")")


def rename_setting(settings, old_name, new_name):
    """
    Rename setting from `old_name` to `new_name`. Used in migrations.

    The argument `settings` can be `dict` or `Context`.
    """
    if isinstance(settings, Context):
        rename_setting(settings.values, old_name, new_name)
    else:
        settings[new_name] = settings.pop(old_name)


def migrate_str_to_variable(settings, names=None):
    """
    Change variables stored as `(str, int)` to `(Variable, int)`.

    Args:
        settings (Context): context that is being migrated
        names (sequence): names of settings to be migrated. If omitted,
            all settings with values `(str, int)` are migrated.
    """
    def _fix(name):
        var, vartype = settings.values[name]
        if 0 <= vartype <= 100:
            settings.values[name] = (var, 100 + vartype)

    if names is None:
        for name, setting in settings.values.items():
            if isinstance(setting, tuple) and len(setting) == 2 and \
                    isinstance(setting[0], str) and isinstance(setting[1], int):
                _fix(name)
    elif isinstance(names, str):
        _fix(names)
    else:
        for name in names:
            _fix(name)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Context migration fails to remove incompatible contexts, causing initialization errors

**Description:**
When initializing the `ContextHandler` with a mix of compatible and incompatible contexts, the migration process does not remove the incompatible contexts as expected. Instead, it raises an `IncompatibleContext` error, preventing successful initialization.

**Example Code:**
```python
handler = ContextHandler()
handler.bind(SimpleWidget)

widget = SimpleWidget()
contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]

def migrate_context(context, _):
    if context.foo == 13:
        raise IncompatibleContext()

handler.initialize(widget, dict(context_settings=contexts))
# Expected: Incompatible contexts with foo=13 should be removed
# Actual: IncompatibleContext error is raised, and contexts are not removed
```

**Expected Behavior:**
During initialization, contexts that are incompatible (e.g., those that cause `IncompatibleContext` to be raised) should be automatically removed, allowing the `ContextHandler` to proceed with only the compatible contexts.

**Actual Behavior:**
The `ContextHandler` does not remove incompatible contexts, resulting in an `IncompatibleContext` error being raised and preventing successful initialization.

[/ISSUE]
{
    "TestContextHandler.test_close_context": "PASSED",
    "TestContextHandler.test_fast_save": "PASSED",
    "TestContextHandler.test_find_or_create_context": "PASSED",
    "TestContextHandler.test_initialize": "PASSED",
    "TestContextHandler.test_initialize_migrates_contexts": "PASSED",
    "TestContextHandler.test_migrates_settings_removes_incompatible": "PASSED",
    "TestContextHandler.test_pack_settings_stores_version": "PASSED",
    "TestContextHandler.test_read_defaults": "PASSED",
    "TestContextHandler.test_write_defaults_stores_version": "PASSED",
    "TestSettingsPrinter.test_formats_contexts": "PASSED"
}
diff --git a/Orange/widgets/settings.py b/Orange/widgets/settings.py
index 8be8bf0ae..75ebe4129 100644
--- a/Orange/widgets/settings.py
+++ b/Orange/widgets/settings.py
@@ -49,7 +49,8 @@ log = logging.getLogger(__name__)
 __all__ = ["Setting", "SettingsHandler", "SettingProvider",
            "ContextSetting", "ContextHandler",
            "DomainContextHandler", "PerfectDomainContextHandler",
-           "ClassValuesContextHandler", "widget_settings_dir"]
+           "ClassValuesContextHandler", "widget_settings_dir",
+           "IncompatibleContext"]
 
 _IMMUTABLES = (str, int, bytes, bool, float, tuple)
 
@@ -624,8 +625,16 @@ class ContextHandler(SettingsHandler):
         self._migrate_contexts(self.global_contexts)
 
     def _migrate_contexts(self, contexts):
-        for context in contexts:
-            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))
+        i = 0
+        while i < len(contexts):
+            context = contexts[i]
+            try:
+                self.widget_class.migrate_context(
+                    context, context.values.pop(VERSION_KEY, 0))
+            except IncompatibleContext:
+                del contexts[i]
+            else:
+                i += 1
 
     def write_defaults_file(self, settings_file):
         """Call the inherited method, then add global context to the pickle."""

{"Orange/widgets/settings.py": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, data, instance in self.traverse_settings(data, instance):\n            if setting.name in data and instance is not None:\n                setattr(instance, setting.name, data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            self.widget_class.migrate_settings(settings, settings.pop(VERSION_KEY, 0))\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, instance in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                setattr(instance, setting.name, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    IF_SELECTED = 1\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, not_attribute=False, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.not_attribute = not_attribute\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def analyze_setting(self, prefix, setting):\n        super().analyze_setting(prefix, setting)\n        if isinstance(setting, ContextSetting):\n            if hasattr(setting, 'selected'):\n                self.known_settings[prefix + setting.selected] = setting\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        for context in contexts:\n            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        for context in widget.context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = widget.context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        super().update_defaults(widget)\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name])\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n                if hasattr(setting, \"selected\"):\n                    yield setting.selected, list(getattr(instance, setting.selected))\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            sel_name = getattr(setting, \"selected\", None)\n            selected = set(data.pop(sel_name, []))\n            new_selected, new_value = [], []\n            for i, item in enumerate(value):\n                if self.is_valid_item(setting, item, attrs, metas):\n                    if i in selected:\n                        new_selected.append(len(new_value))\n                    new_value.append(item)\n\n            data[setting.name] = new_value\n            if hasattr(setting, 'selected'):\n                data[setting.selected] = new_selected\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            setattr(instance, setting.name, value)\n            if hasattr(setting, \"selected\") and setting.selected in data:\n                setattr(instance, setting.selected, data[setting.selected])\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            return copy.copy(value)\n        elif isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return value.name, 100 + vartype(value)\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        if hasattr(setting, 'selected'):\n            selected = set(context.values.get(setting.selected, []))\n        else:\n            selected = set()\n\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            else:\n                if setting.required == ContextSetting.REQUIRED:\n                    raise IncompatibleContext()\n                if setting.IF_SELECTED and i in selected:\n                    raise IncompatibleContext()\n\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Context migration fails to remove incompatible contexts, causing initialization errors

**Description:**
When initializing the `ContextHandler` with a mix of compatible and incompatible contexts, the migration process does not remove the incompatible contexts as expected. Instead, it raises an `IncompatibleContext` error, preventing successful initialization.

**Example Code:**
```python
handler = ContextHandler()
handler.bind(SimpleWidget)

widget = SimpleWidget()
contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]

def migrate_context(context, _):
    if context.foo == 13:
        raise IncompatibleContext()

handler.initialize(widget, dict(context_settings=contexts))
# Expected: Incompatible contexts with foo=13 should be removed
# Actual: IncompatibleContext error is raised, and contexts are not removed
```

**Expected Behavior:**
During initialization, contexts that are incompatible (e.g., those that cause `IncompatibleContext` to be raised) should be automatically removed, allowing the `ContextHandler` to proceed with only the compatible contexts.

**Actual Behavior:**
The `ContextHandler` does not remove incompatible contexts, resulting in an `IncompatibleContext` error being raised and preventing successful initialization.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/settings.py
"""Widget Settings and Settings Handlers

Settings are used to declare widget attributes that persist through sessions.
When widget is removed or saved to a schema file, its settings are packed,
serialized and stored. When a new widget is created, values of attributes
marked as settings are read from disk. When schema is loaded, attribute values
are set to one stored in schema.

Each widget has its own SettingsHandler that takes care of serializing and
storing of settings and SettingProvider that is incharge of reading and
writing the setting values.

All widgets extending from OWWidget use SettingsHandler, unless they
declare otherwise. SettingsHandler ensures that setting attributes
are replaced with default (last used) setting values when the widget is
initialized and stored when the widget is removed.

Widgets with settings whose values depend on the widget inputs use
settings handlers based on ContextHandler. These handlers have two
additional methods, open_context and close_context.

open_context is called when widgets receives new data. It finds a suitable
context and sets the widget attributes to the values stored in context.
If no suitable context exists, a new one is created and values from widget
are copied to it.

close_context stores values that were last used on the widget to the context
so they can be used alter. It should be called before widget starts modifying
(initializing) the value of the setting attributes.
"""

import copy
import itertools
import os
import logging
import pickle
import pprint
import time
import warnings
from operator import itemgetter

from Orange.data import Domain, Variable
from Orange.misc.environ import widget_settings_dir
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.utils import vartype

log = logging.getLogger(__name__)

__all__ = ["Setting", "SettingsHandler", "SettingProvider",
           "ContextSetting", "ContextHandler",
           "DomainContextHandler", "PerfectDomainContextHandler",
           "ClassValuesContextHandler", "widget_settings_dir"]

_IMMUTABLES = (str, int, bytes, bool, float, tuple)

VERSION_KEY = "__version__"


class Setting:
    """Description of a setting.
    """

    # Settings are automatically persisted to disk
    packable = True

    # Setting is only persisted to schema (default value does not change)
    schema_only = False

    def __new__(cls, default, *args, **kwargs):
        """A misleading docstring for providing type hints for Settings

        :type: default: T
        :rtype: T
        """
        return super().__new__(cls)

    def __init__(self, default, **data):
        self.name = None  # Name gets set in widget's meta class
        self.default = default
        self.__dict__.update(data)

    def __str__(self):
        return '{0} "{1}"'.format(self.__class__.__name__, self.name)

    __repr__ = __str__

    def __getnewargs__(self):
        return (self.default, )


class SettingProvider:
    """A hierarchical structure keeping track of settings belonging to
    a class and child setting providers.

    At instantiation, it creates a dict of all Setting and SettingProvider
    members of the class. This dict is used to get/set values of settings
    from/to the instances of the class this provider belongs to.
    """

    def __init__(self, provider_class):
        """ Construct a new instance of SettingProvider.

        Traverse provider_class members and store all instances of
        Setting and SettingProvider.

        Parameters
        ----------
        provider_class : class
            class containing settings definitions
        """
        self.name = ""
        self.provider_class = provider_class
        self.providers = {}
        """:type: dict[str, SettingProvider]"""
        self.settings = {}
        """:type: dict[str, Setting]"""
        self.initialization_data = None

        for name in dir(provider_class):
            value = getattr(provider_class, name, None)
            if isinstance(value, Setting):
                value = copy.deepcopy(value)
                value.name = name
                self.settings[name] = value
            if isinstance(value, SettingProvider):
                value = copy.deepcopy(value)
                value.name = name
                self.providers[name] = value

    def initialize(self, instance, data=None):
        """Initialize instance settings to their default values.

        Mutable values are (shallow) copied before they are assigned to the
        widget. Immutable are used as-is.

        Parameters
        ----------
        instance : OWWidget
            widget instance to initialize
        data : Optional[dict]
            optional data used to override the defaults
            (used when settings are loaded from schema)
        """
        if data is None and self.initialization_data is not None:
            data = self.initialization_data

        self._initialize_settings(instance, data)
        self._initialize_providers(instance, data)

    def _initialize_settings(self, instance, data):
        if data is None:
            data = {}
        for name, setting in self.settings.items():
            value = data.get(name, setting.default)
            if isinstance(value, _IMMUTABLES):
                setattr(instance, name, value)
            else:
                setattr(instance, name, copy.copy(value))

    def _initialize_providers(self, instance, data):
        if not data:
            return

        for name, provider in self.providers.items():
            if name not in data:
                continue

            member = getattr(instance, name, None)
            if member is None or isinstance(member, SettingProvider):
                provider.store_initialization_data(data[name])
            else:
                provider.initialize(member, data[name])

    def store_initialization_data(self, initialization_data):
        """Store initialization data for later use.

        Used when settings handler is initialized, but member for this
        provider does not exists yet (because handler.initialize is called in
        __new__, but member will be created in __init__.

        Parameters
        ----------
        initialization_data : dict
            data to be used for initialization when the component is created
        """
        self.initialization_data = initialization_data

    @staticmethod
    def _default_packer(setting, instance):
        """A simple packet that yields setting name and value.

        Parameters
        ----------
        setting : Setting
        instance : OWWidget
        """
        if setting.packable:
            if hasattr(instance, setting.name):
                yield setting.name, getattr(instance, setting.name)
            else:
                warnings.warn("{0} is declared as setting on {1} "
                              "but not present on instance."
                              .format(setting.name, instance))

    def pack(self, instance, packer=None):
        """Pack instance settings in a name:value dict.

        Parameters
        ----------
        instance : OWWidget
            widget instance
        packer: callable (Setting, OWWidget) -> Generator[(str, object)]
            optional packing function
            it will be called with setting and instance parameters and
            should yield (name, value) pairs that will be added to the
            packed_settings.
        """
        if packer is None:
            packer = self._default_packer

        packed_settings = dict(itertools.chain(
            *(packer(setting, instance) for setting in self.settings.values())
        ))

        packed_settings.update({
            name: provider.pack(getattr(instance, name), packer)
            for name, provider in self.providers.items()
            if hasattr(instance, name)
        })
        return packed_settings

    def unpack(self, instance, data):
        """Restore settings from data to the instance.

        Parameters
        ----------
        instance : OWWidget
            instance to restore settings to
        data : dict
            packed data
        """
        for setting, data, instance in self.traverse_settings(data, instance):
            if setting.name in data and instance is not None:
                setattr(instance, setting.name, data[setting.name])

    def get_provider(self, provider_class):
        """Return provider for provider_class.

        If this provider matches, return it, otherwise pass
        the call to child providers.

        Parameters
        ----------
        provider_class : class
        """
        if issubclass(provider_class, self.provider_class):
            return self

        for subprovider in self.providers.values():
            provider = subprovider.get_provider(provider_class)
            if provider:
                return provider

    def traverse_settings(self, data=None, instance=None):
        """Generator of tuples (setting, data, instance) for each setting
        in this and child providers..

        Parameters
        ----------
        data : dict
            dictionary with setting values
        instance : OWWidget
            instance matching setting_provider
        """
        data = data if data is not None else {}

        for setting in self.settings.values():
            yield setting, data, instance

        for provider in self.providers.values():
            data_ = data.get(provider.name, {})
            instance_ = getattr(instance, provider.name, None)
            for setting, component_data, component_instance in \
                    provider.traverse_settings(data_, instance_):
                yield setting, component_data, component_instance


class SettingsHandler:
    """Reads widget setting files and passes them to appropriate providers."""

    def __init__(self):
        """Create a setting handler template.

        Used in class definition. Bound instance will be created
        when SettingsHandler.create is called.
        """
        self.widget_class = None
        self.provider = None
        """:type: SettingProvider"""
        self.defaults = {}
        self.known_settings = {}

    @staticmethod
    def create(widget_class, template=None):
        """Create a new settings handler based on the template and bind it to
        widget_class.

        Parameters
        ----------
        widget_class : class
        template : SettingsHandler
            SettingsHandler to copy setup from

        Returns
        -------
        SettingsHandler
        """

        if template is None:
            template = SettingsHandler()

        setting_handler = copy.copy(template)
        setting_handler.defaults = {}
        setting_handler.bind(widget_class)
        return setting_handler

    def bind(self, widget_class):
        """Bind settings handler instance to widget_class.

        Parameters
        ----------
        widget_class : class
        """
        self.widget_class = widget_class
        self.provider = SettingProvider(widget_class)
        self.known_settings = {}
        self.analyze_settings(self.provider, "")
        self.read_defaults()

    def analyze_settings(self, provider, prefix):
        """Traverse through all settings known to the provider
        and analyze each of them.

        Parameters
        ----------
        provider : SettingProvider
        prefix : str
            prefix the provider is registered to handle
        """
        for setting in provider.settings.values():
            self.analyze_setting(prefix, setting)

        for name, sub_provider in provider.providers.items():
            new_prefix = '{0}{1}.'.format(prefix or '', name)
            self.analyze_settings(sub_provider, new_prefix)

    def analyze_setting(self, prefix, setting):
        """Perform any initialization task related to setting.

        Parameters
        ----------
        prefix : str
        setting : Setting
        """
        self.known_settings[prefix + setting.name] = setting

    def read_defaults(self):
        """Read (global) defaults for this widget class from a file.
        Opens a file and calls :obj:`read_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        if os.path.isfile(filename):
            settings_file = open(filename, "rb")
            try:
                self.read_defaults_file(settings_file)
            # Unpickling exceptions can be of any type
            # pylint: disable=broad-except
            except Exception as ex:
                warnings.warn("Could not read defaults for widget {0}\n"
                              "The following error occurred:\n\n{1}"
                              .format(self.widget_class, ex))
            finally:
                settings_file.close()

    def read_defaults_file(self, settings_file):
        """Read (global) defaults for this widget class from a file.

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = pickle.load(settings_file)
        self.defaults = {
            key: value
            for key, value in defaults.items()
            if not isinstance(value, Setting)
        }
        self._migrate_settings(self.defaults)

    def write_defaults(self):
        """Write (global) defaults for this widget class to a file.
        Opens a file and calls :obj:`write_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        try:
            settings_file = open(filename, "wb")
            try:
                self.write_defaults_file(settings_file)
            except (EOFError, IOError, pickle.PicklingError) as ex:
                log.error("Could not write default settings for %s (%s).",
                          self.widget_class, type(ex).__name__)
                settings_file.close()
                os.remove(filename)
            else:
                settings_file.close()
        except PermissionError as ex:
            log.error("Could not write default settings for %s (%s).",
                      self.widget_class, type(ex).__name__)

    def write_defaults_file(self, settings_file):
        """Write defaults for this widget class to a file

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = dict(self.defaults)
        defaults[VERSION_KEY] = self.widget_class.settings_version
        pickle.dump(defaults, settings_file, -1)

    def _get_settings_filename(self):
        """Return the name of the file with default settings for the widget"""
        return os.path.join(widget_settings_dir(),
                            "{0.__module__}.{0.__qualname__}.pickle"
                            .format(self.widget_class))

    def initialize(self, instance, data=None):
        """
        Initialize widget's settings.

        Replace all instance settings with their default values.

        Parameters
        ----------
        instance : OWWidget
        data : dict or bytes that unpickle into a dict
            values used to override the defaults
        """
        provider = self._select_provider(instance)

        if isinstance(data, bytes):
            data = pickle.loads(data)
        self._migrate_settings(data)

        if provider is self.provider:
            data = self._add_defaults(data)

        provider.initialize(instance, data)

    def _migrate_settings(self, settings):
        """Ask widget to migrate settings to the latest version."""
        if settings:
            self.widget_class.migrate_settings(settings, settings.pop(VERSION_KEY, 0))

    def _select_provider(self, instance):
        provider = self.provider.get_provider(instance.__class__)
        if provider is None:
            message = "{0} has not been declared as setting provider in {1}. " \
                      "Settings will not be saved/loaded properly. Defaults will be used instead." \
                      .format(instance.__class__, self.widget_class)
            warnings.warn(message)
            provider = SettingProvider(instance.__class__)
        return provider

    def _add_defaults(self, data):
        if data is None:
            return self.defaults

        new_data = self.defaults.copy()
        new_data.update(data)
        return new_data

    def pack_data(self, widget):
        """
        Pack the settings for the given widget. This method is used when
        saving schema, so that when the schema is reloaded the widget is
        initialized with its proper data and not the class-based defaults.
        See :obj:`SettingsHandler.initialize` for detailed explanation of its
        use.

        Inherited classes add other data, in particular widget-specific
        local contexts.

        Parameters
        ----------
        widget : OWWidget
        """
        packed_settings = self.provider.pack(widget)
        packed_settings[VERSION_KEY] = self.widget_class.settings_version
        return packed_settings

    def update_defaults(self, widget):
        """
        Writes widget instance's settings to class defaults. Called when the
        widget is deleted.

        Parameters
        ----------
        widget : OWWidget
        """
        self.defaults = self.provider.pack(widget)
        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):
            if setting.schema_only:
                data.pop(setting.name, None)
        self.write_defaults()

    def fast_save(self, widget, name, value):
        """Store the (changed) widget's setting immediately to the context.

        Parameters
        ----------
        widget : OWWidget
        name : str
        value : object

        """
        if name in self.known_settings:
            setting = self.known_settings[name]
            if not setting.schema_only:
                setting.default = value

    def reset_settings(self, instance):
        """Reset widget settings to defaults

        Parameters
        ----------
        instance : OWWidget
        """
        for setting, _, instance in self.provider.traverse_settings(instance=instance):
            if setting.packable:
                setattr(instance, setting.name, setting.default)


class ContextSetting(Setting):
    """Description of a context dependent setting"""

    OPTIONAL = 0
    IF_SELECTED = 1
    REQUIRED = 2

    # Context settings are not persisted, but are stored in context instead.
    packable = False

    # These flags are not general - they assume that the setting has to do
    # something with the attributes. Large majority does, so this greatly
    # simplifies the declaration of settings in widget at no (visible)
    # cost to those settings that don't need it
    def __init__(self, default, *, not_attribute=False, required=2,
                 exclude_attributes=False, exclude_metas=False, **data):
        super().__init__(default, **data)
        self.not_attribute = not_attribute
        self.exclude_attributes = exclude_attributes
        self.exclude_metas = exclude_metas
        self.required = required


class Context:
    """Class for data thad defines context and
    values that should be applied to widget if given context
    is encountered."""
    def __init__(self, **argkw):
        self.time = time.time()
        self.values = {}
        self.__dict__.update(argkw)

    def __getstate__(self):
        state = dict(self.__dict__)
        for nc in getattr(self, "no_copy", []):
            if nc in state:
                del state[nc]
        return state


class ContextHandler(SettingsHandler):
    """Base class for setting handlers that can handle contexts.

    Classes deriving from it need to implement method `match`.
    """

    NO_MATCH = 0
    PERFECT_MATCH = 2

    MAX_SAVED_CONTEXTS = 50

    def __init__(self):
        super().__init__()
        self.global_contexts = []
        self.known_settings = {}

    def analyze_setting(self, prefix, setting):
        super().analyze_setting(prefix, setting)
        if isinstance(setting, ContextSetting):
            if hasattr(setting, 'selected'):
                self.known_settings[prefix + setting.selected] = setting

    def initialize(self, instance, data=None):
        """Initialize the widget: call the inherited initialization and
        add an attribute 'context_settings' to the widget. This method
        does not open a context."""
        instance.current_context = None
        super().initialize(instance, data)
        if data and "context_settings" in data:
            instance.context_settings = data["context_settings"]
            self._migrate_contexts(instance.context_settings)
        else:
            instance.context_settings = []

    def read_defaults_file(self, settings_file):
        """Call the inherited method, then read global context from the
           pickle."""
        super().read_defaults_file(settings_file)
        self.global_contexts = pickle.load(settings_file)
        self._migrate_contexts(self.global_contexts)

    def _migrate_contexts(self, contexts):
        for context in contexts:
            self.widget_class.migrate_context(context, context.values.pop(VERSION_KEY, 0))

    def write_defaults_file(self, settings_file):
        """Call the inherited method, then add global context to the pickle."""
        super().write_defaults_file(settings_file)

        def add_version(context):
            context = copy.copy(context)
            context.values = dict(context.values)
            context.values[VERSION_KEY] = self.widget_class.settings_version
            return context

        pickle.dump([add_version(context) for context in self.global_contexts],
                    settings_file, -1)

    def pack_data(self, widget):
        """Call the inherited method, then add local contexts to the dict."""
        data = super().pack_data(widget)
        self.settings_from_widget(widget)
        for context in widget.context_settings:
            context.values[VERSION_KEY] = self.widget_class.settings_version
        data["context_settings"] = widget.context_settings
        return data

    def update_defaults(self, widget):
        """
        Reimplemented from SettingsHandler

        Merge the widgets local contexts into the global contexts and persist
        the settings (including the contexts) to disk.
        """
        self.settings_from_widget(widget)
        globs = self.global_contexts
        assert widget.context_settings is not globs
        ids = {id(c) for c in globs}
        globs += (c for c in widget.context_settings if id(c) not in ids)
        globs.sort(key=lambda c: -c.time)
        del globs[self.MAX_SAVED_CONTEXTS:]

        super().update_defaults(widget)

    def new_context(self, *args):
        """Create a new context."""
        return Context()

    def open_context(self, widget, *args):
        """Open a context by finding one and setting the widget data or
        creating one and fill with the data from the widget."""
        widget.current_context, is_new = \
            self.find_or_create_context(widget, *args)
        if is_new:
            try:
                self.settings_from_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_from_widget in {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_from_widget(widget)
        else:
            try:
                self.settings_to_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_to_widget {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_to_widget(widget)

    def match(self, context, *args):
        """Return the degree to which the stored `context` matches the data
        passed in additional arguments).
        When match returns 0 (ContextHandler.NO_MATCH), the context will not
        be used. When it returns ContextHandler.PERFECT_MATCH, the context
        is a perfect match so no further search is necessary.

        If imperfect matching is not desired, match should only
        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.

        Derived classes must overload this method.
        """
        raise NotImplementedError

    def find_or_create_context(self, widget, *args):
        """Find the best matching context or create a new one if nothing
        useful is found. The returned context is moved to or added to the top
        of the context list."""

        # First search the contexts that were already used in this widget instance
        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)
        # If the exact data was used, reuse the context
        if best_score == self.PERFECT_MATCH:
            return best_context, False

        # Otherwise check if a better match is available in global_contexts
        best_context, best_score = self.find_context(self.global_contexts, args,
                                                     best_score, best_context)
        if best_context:
            context = self.clone_context(best_context, *args)
        else:
            context = self.new_context(*args)
        # Store context in widget instance. It will be pushed to global_contexts
        # when (if) update defaults is called.
        self.add_context(widget.context_settings, context)
        return context, best_context is None

    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):
        """Search the given list of contexts and return the context
         which best matches the given args.

        best_score and best_context can be used to provide base_values.
        """

        for i, context in enumerate(known_contexts):
            score = self.match(context, *args)
            if score == self.PERFECT_MATCH:
                if move_up:
                    self.move_context_up(known_contexts, i)
                return context, score
            if score > best_score:  # NO_MATCH is not OK!
                best_context, best_score = context, score
        return best_context, best_score

    @staticmethod
    def move_context_up(contexts, index):
        """Move the context to the top of the list and set
        the timestamp to current."""
        setting = contexts.pop(index)
        setting.time = time.time()
        contexts.insert(0, setting)

    def add_context(self, contexts, setting):
        """Add the context to the top of the list."""
        contexts.insert(0, setting)
        del contexts[self.MAX_SAVED_CONTEXTS:]

    def clone_context(self, old_context, *args):
        """Construct a copy of the context settings suitable for the context
        described by additional arguments. The method is called by
        find_or_create_context with the same arguments. A class that overloads
        :obj:`match` to accept additional arguments must also overload
        :obj:`clone_context`."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)

        traverse = self.provider.traverse_settings
        for setting, data, _ in traverse(data=context.values):
            if not isinstance(setting, ContextSetting):
                continue

            self.filter_value(setting, data, *args)
        return context

    @staticmethod
    def filter_value(setting, data, *args):
        """Remove values related to setting that are invalid given args."""

    def close_context(self, widget):
        """Close the context by calling :obj:`settings_from_widget` to write
        any relevant widget settings to the context."""
        if widget.current_context is None:
            return

        self.settings_from_widget(widget)
        widget.current_context = None

    def settings_to_widget(self, widget, *args):
        """Apply context settings stored in currently opened context
        to the widget.
        """
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name])
            setattr(instance, setting.name, value)
            if hasattr(setting, "selected") and setting.selected in data:
                setattr(instance, setting.selected, data[setting.selected])

    def settings_from_widget(self, widget, *args):
        """Update the current context with the setting values from the widget.
        """

        context = widget.current_context
        if context is None:
            return

        widget.storeSpecificSettings()

        def packer(setting, instance):
            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):
                value = getattr(instance, setting.name)
                yield setting.name, self.encode_setting(context, setting, value)
                if hasattr(setting, "selected"):
                    yield setting.selected, list(getattr(instance, setting.selected))

        context.values = self.provider.pack(widget, packer=packer)

    def fast_save(self, widget, name, value):
        """Update value of `name` setting in the current context to `value`
        """
        setting = self.known_settings.get(name)
        if isinstance(setting, ContextSetting):
            context = widget.current_context
            if context is None:
                return

            value = self.encode_setting(context, setting, value)
            self.update_packed_data(context.values, name, value)
        else:
            super().fast_save(widget, name, value)

    @staticmethod
    def update_packed_data(data, name, value):
        """Updates setting value stored in data dict"""

        *prefixes, name = name.split('.')
        for prefix in prefixes:
            data = data.setdefault(prefix, {})
        data[name] = value

    def encode_setting(self, context, setting, value):
        """Encode value to be stored in settings dict"""
        return copy.copy(value)

    def decode_setting(self, setting, value):
        """Decode settings value from the setting dict format"""
        return value


class DomainContextHandler(ContextHandler):
    """Context handler for widgets with settings that depend on
    the input dataset. Suitable settings are selected based on the
    data domain."""

    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)

    def __init__(self, *, match_values=0, **kwargs):
        super().__init__()
        self.match_values = match_values

        for name in kwargs:
            warnings.warn(
                "{} is not a valid parameter for DomainContextHandler"
                .format(name), OrangeDeprecationWarning
            )

    def encode_domain(self, domain):
        """
        domain: Orange.data.domain to encode
        return: dict mapping attribute name to type or list of values
                (based on the value of self.match_values attribute)
        """

        match = self.match_values
        encode = self.encode_variables
        if match == self.MATCH_VALUES_CLASS:
            attributes = encode(domain.attributes, False)
            attributes.update(encode(domain.class_vars, True))
        else:
            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)

        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)

        return attributes, metas

    @staticmethod
    def encode_variables(attributes, encode_values):
        """Encode variables to a list mapping name to variable type
        or a list of values."""

        if not encode_values:
            return {v.name: vartype(v) for v in attributes}

        return {v.name: v.values if v.is_discrete else vartype(v)
                for v in attributes}

    def new_context(self, domain, attributes, metas):
        """Create a new context."""
        context = super().new_context()
        context.attributes = attributes
        context.metas = metas
        return context

    def open_context(self, widget, domain):
        if domain is None:
            return None, False

        if not isinstance(domain, Domain):
            domain = domain.domain

        super().open_context(widget, domain, *self.encode_domain(domain))

    def filter_value(self, setting, data, domain, attrs, metas):
        value = data.get(setting.name, None)
        if isinstance(value, list):
            sel_name = getattr(setting, "selected", None)
            selected = set(data.pop(sel_name, []))
            new_selected, new_value = [], []
            for i, item in enumerate(value):
                if self.is_valid_item(setting, item, attrs, metas):
                    if i in selected:
                        new_selected.append(len(new_value))
                    new_value.append(item)

            data[setting.name] = new_value
            if hasattr(setting, 'selected'):
                data[setting.selected] = new_selected
        elif value is not None:
            if (value[1] >= 0 and
                    not self._var_exists(setting, value, attrs, metas)):
                del data[setting.name]

    def settings_to_widget(self, widget, domain, *args):
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name], domain)
            setattr(instance, setting.name, value)
            if hasattr(setting, "selected") and setting.selected in data:
                setattr(instance, setting.selected, data[setting.selected])

    def encode_setting(self, context, setting, value):
        if isinstance(value, list):
            return copy.copy(value)
        elif isinstance(setting, ContextSetting):
            if isinstance(value, str):
                if not setting.exclude_attributes and value in context.attributes:
                    return value, context.attributes[value]
                if not setting.exclude_metas and value in context.metas:
                    return value, context.metas[value]
            elif isinstance(value, Variable):
                return value.name, 100 + vartype(value)
        return copy.copy(value), -2

    def decode_setting(self, setting, value, domain=None):
        if isinstance(value, tuple):
            if value[1] >= 100:
                if domain is None:
                    raise ValueError("Cannot decode variable without domain")
                return domain[value[0]]
            return value[0]
        else:
            return value

    @staticmethod
    def _var_exists(setting, value, attributes, metas):
        if not isinstance(value, tuple) or len(value) != 2:
            return False

        attr_name, attr_type = value
        if attr_type >= 100:
            attr_type -= 100
        return (not setting.exclude_attributes and
                attributes.get(attr_name, -1) == attr_type or
                not setting.exclude_metas and
                metas.get(attr_name, -1) == attr_type)

    def match(self, context, domain, attrs, metas):
        if (attrs, metas) == (context.attributes, context.metas):
            return self.PERFECT_MATCH

        matches = []
        try:
            for setting, data, _ in \
                    self.provider.traverse_settings(data=context.values):
                if not isinstance(setting, ContextSetting):
                    continue
                value = data.get(setting.name, None)

                if isinstance(value, list):
                    matches.append(
                        self.match_list(setting, value, context, attrs, metas))
                elif value is not None:
                    matches.append(
                        self.match_value(setting, value, attrs, metas))
        except IncompatibleContext:
            return self.NO_MATCH

        matches.append((0, 0))
        matched, available = [sum(m) for m in zip(*matches)]

        return matched / available if available else 0.1

    def match_list(self, setting, value, context, attrs, metas):
        """Match a list of values with the given context.
        returns a tuple containing number of matched and all values.
        """
        matched = 0
        if hasattr(setting, 'selected'):
            selected = set(context.values.get(setting.selected, []))
        else:
            selected = set()

        for i, item in enumerate(value):
            if self.is_valid_item(setting, item, attrs, metas):
                matched += 1
            else:
                if setting.required == ContextSetting.REQUIRED:
                    raise IncompatibleContext()
                if setting.IF_SELECTED and i in selected:
                    raise IncompatibleContext()

        return matched, len(value)

    def match_value(self, setting, value, attrs, metas):
        """Match a single value """
        if value[1] < 0:
            return 0, 0

        if self._var_exists(setting, value, attrs, metas):
            return 1, 1
        elif setting.required == setting.OPTIONAL:
            return 0, 1
        else:
            raise IncompatibleContext()

    def is_valid_item(self, setting, item, attrs, metas):
        """Return True if given item can be used with attrs and metas

        Subclasses can override this method to checks data in alternative
        representations.
        """
        if not isinstance(item, tuple):
            return True
        return self._var_exists(setting, item, attrs, metas)


class IncompatibleContext(Exception):
    """Raised when a required variable in context is not available in data."""
    pass


class ClassValuesContextHandler(ContextHandler):
    """Context handler used for widgets that work with
    a single discrete variable"""

    def open_context(self, widget, classes):
        if isinstance(classes, Variable):
            if classes.is_discrete:
                classes = classes.values
            else:
                classes = None

        super().open_context(widget, classes)

    def new_context(self, classes):
        context = super().new_context()
        context.classes = classes
        return context

    def match(self, context, classes):
        if isinstance(classes, Variable) and classes.is_continuous:
            return (self.PERFECT_MATCH if context.classes is None
                    else self.NO_MATCH)
        else:
            return (self.PERFECT_MATCH if context.classes == classes
                    else self.NO_MATCH)


class PerfectDomainContextHandler(DomainContextHandler):
    """Context handler that matches a context only when
    the same domain is available.

    It uses a different encoding than the DomainContextHandler.
    """

    def new_context(self, domain, attributes, class_vars, metas):
        """Same as DomainContextHandler, but also store class_vars"""
        context = super().new_context(domain, attributes, metas)
        context.class_vars = class_vars
        return context

    def clone_context(self, old_context, *args):
        """Copy of context is always valid, since widgets are using
        the same domain."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)
        return context

    def encode_domain(self, domain):
        """Encode domain into tuples (name, type)
        A tuple is returned for each of attributes, class_vars and metas.
        """

        if self.match_values == self.MATCH_VALUES_ALL:
            def _encode(attrs):
                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))
                             for v in attrs)
        else:
            def _encode(attrs):
                return tuple((v.name, vartype(v)) for v in attrs)
        return (_encode(domain.attributes),
                _encode(domain.class_vars),
                _encode(domain.metas))

    def match(self, context, domain, attributes, class_vars, metas):
        """Context only matches when domains are the same"""

        return (self.PERFECT_MATCH
                if (context.attributes == attributes and
                    context.class_vars == class_vars and
                    context.metas == metas)
                else self.NO_MATCH)

    def encode_setting(self, context, setting, value):
        """Same as is domain context handler, but handles separately stored
        class_vars."""

        if isinstance(setting, ContextSetting) and isinstance(value, str):

            def _candidate_variables():
                if not setting.exclude_attributes:
                    yield from itertools.chain(context.attributes,
                                               context.class_vars)
                if not setting.exclude_metas:
                    yield from context.metas

            for aname, atype in _candidate_variables():
                if aname == value:
                    return value, atype

            return value, -1
        else:
            return super().encode_setting(context, setting, value)


class SettingsPrinter(pprint.PrettyPrinter):
    """Pretty Printer that knows how to properly format Contexts."""

    def _format(self, obj, stream, indent, allowance, context, level):
        if not isinstance(obj, Context):
            return super()._format(obj, stream, indent,
                                   allowance, context, level)

        stream.write("Context(")
        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):
            if key == "values":
                continue
            stream.write(key)
            stream.write("=")
            stream.write(self._repr(value, context, level + 1))
            stream.write(",\n")
            stream.write(" " * (indent + 8))
        stream.write("values=")
        stream.write(" ")
        self._format(obj.values, stream, indent+15,
                     allowance+1, context, level + 1)
        stream.write(")")


def rename_setting(settings, old_name, new_name):
    """
    Rename setting from `old_name` to `new_name`. Used in migrations.

    The argument `settings` can be `dict` or `Context`.
    """
    if isinstance(settings, Context):
        rename_setting(settings.values, old_name, new_name)
    else:
        settings[new_name] = settings.pop(old_name)


def migrate_str_to_variable(settings, names=None):
    """
    Change variables stored as `(str, int)` to `(Variable, int)`.

    Args:
        settings (Context): context that is being migrated
        names (sequence): names of settings to be migrated. If omitted,
            all settings with values `(str, int)` are migrated.
    """
    def _fix(name):
        var, vartype = settings.values[name]
        if 0 <= vartype <= 100:
            settings.values[name] = (var, 100 + vartype)

    if names is None:
        for name, setting in settings.values.items():
            if isinstance(setting, tuple) and len(setting) == 2 and \
                    isinstance(setting[0], str) and isinstance(setting[1], int):
                _fix(name)
    elif isinstance(names, str):
        _fix(names)
    else:
        for name in names:
            _fix(name)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user