{
    "file_diffs": [
        {
            "old_file_content": "import operator\nimport os\nimport threading\nimport warnings\nimport weakref\nimport zlib\nfrom collections import Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock\n\nimport bottleneck as bn\nimport numpy as np\nfrom Orange.misc.collections import frozendict\nfrom Orange.util import OrangeDeprecationWarning\nfrom scipy import sparse as sp\nfrom scipy.sparse import issparse, csc_matrix\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES,\n    DomainConversion)\nfrom Orange.data.util import SharedComputeValue, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse, get_unique_names_duplicates\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\nclass _ThreadLocal(threading.local):\n    def __init__(self):\n        super().__init__()\n        # Domain conversion cache used in Table.from_table. It is defined\n        # here instead of as a class variable of a Table so that caching also works\n        # with descendants of Table.\n        self.conversion_cache = None\n\n\n_thread_local = _ThreadLocal()\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(Sequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    domain = Domain([])\n    X = _Y = metas = W = np.zeros((0, 0))\n    X.setflags(write=False)\n    ids = np.zeros(0)\n    ids.setflags(write=False)\n    attributes = frozendict()\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        if sp.issparse(value):\n            value = value.toarray()\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        def warn_deprecated(method):\n            warnings.warn(\"Direct calls to Table's constructor are deprecated \"\n                          \"and will be removed. Replace this call with \"\n                          f\"Table.{method}\", OrangeDeprecationWarning,\n                          stacklevel=3)\n\n        if not args:\n            if not kwargs:\n                return super().__new__(cls)\n            else:\n                raise TypeError(\"Table() must not be called directly\")\n\n        if isinstance(args[0], str):\n            if len(args) > 1:\n                raise TypeError(\"Table(name: str) expects just one argument\")\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0], **kwargs)\n\n        elif isinstance(args[0], Table):\n            if len(args) > 1:\n                raise TypeError(\"Table(table: Table) expects just one argument\")\n            return cls.from_table(args[0].domain, args[0], **kwargs)\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                warn_deprecated(\"from_domain\")\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                warn_deprecated(\"from_table\")\n                return cls.from_table(domain, *args, **kwargs)\n            elif isinstance(args[0], list):\n                warn_deprecated(\"from_list\")\n                return cls.from_list(domain, *args, **kwargs)\n        else:\n            warnings.warn(\"Omitting domain in a call to Table(X, Y, metas), is \"\n                          \"deprecated and will be removed. \"\n                          \"Call Table.from_numpy(None, X, Y, metas) instead.\",\n                          OrangeDeprecationWarning, stacklevel=2)\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        def valid_refs(weakrefs):\n            for r in weakrefs:\n                if r() is None:\n                    return False\n            return True\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64,\n                        is_sparse=False, variables=[]):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize arrays & set `match_density` for columns\n            # F-order enables faster writing to the array while accessing and\n            # matrix operations work with same speed (e.g. dot)\n            a = None if is_sparse else np.zeros(\n                (n_rows, len(src_cols)), order=\"F\", dtype=dtype)\n            data = []\n            sp_col = []\n            sp_row = []\n            match_density = (\n                assure_column_sparse if is_sparse else assure_column_dense\n            )\n\n            # converting to csc before instead of each column is faster\n            # do not convert if not required\n            if any([isinstance(x, int) for x in src_cols]):\n                X = csc_matrix(source.X) if is_sparse else source.X\n                Y = csc_matrix(source._Y) if is_sparse else source._Y\n\n            shared_cache = _thread_local.conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    col_array = match_density(\n                        np.full((n_rows, 1), variables[i].Unknown)\n                    )\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        shared, weakrefs = shared_cache.get(\n                            (id(col.compute_shared), id(source)),\n                            (None, None)\n                        )\n                        if shared is None or not valid_refs(weakrefs):\n                            shared, _ = shared_cache[(id(col.compute_shared), id(source))] = \\\n                                col.compute_shared(source), \\\n                                (weakref.ref(col.compute_shared), weakref.ref(source))\n\n                        if row_indices is not ...:\n                            col_array = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            col_array = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            col_array = match_density(col(source)[row_indices])\n                        else:\n                            col_array = match_density(col(source))\n                elif col < 0:\n                    col_array = match_density(\n                        source.metas[row_indices, -1 - col]\n                    )\n                elif col < n_src_attrs:\n                    col_array = match_density(X[row_indices, col])\n                else:\n                    col_array = match_density(\n                        Y[row_indices, col - n_src_attrs]\n                    )\n\n                if is_sparse:\n                    # col_array should be coo matrix\n                    data.append(col_array.data)\n                    sp_col.append(np.full(len(col_array.data), i))\n                    sp_row.append(col_array.indices)  # row indices should be same\n                else:\n                    a[:, i] = col_array\n\n            if is_sparse:\n                # creating csr directly would need plenty of manual work which\n                # would probably slow down the process - conversion coo to csr\n                # is fast\n                a = sp.coo_matrix(\n                    (np.hstack(data), (np.hstack(sp_row), np.hstack(sp_col))),\n                    shape=(n_rows, len(src_cols)),\n                    dtype=dtype\n                )\n                a = a.tocsr()\n\n            return a\n\n        new_cache = _thread_local.conversion_cache is None\n        try:\n            if new_cache:\n                _thread_local.conversion_cache = {}\n            else:\n                cached, weakrefs = \\\n                    _thread_local.conversion_cache.get((id(domain), id(source)), (None, None))\n                if cached and valid_refs(weakrefs):\n                    return cached\n            if domain is source.domain:\n                table = cls.from_table_rows(source, row_indices)\n                # assure resulting domain is the instance passed on input\n                table.domain = domain\n                # since sparse flags are not considered when checking for\n                # domain equality, fix manually.\n                table = assure_domain_conversion_sparsity(table, source)\n                return table\n\n            if isinstance(row_indices, slice):\n                start, stop, stride = row_indices.indices(source.X.shape[0])\n                n_rows = (stop - start) // stride\n                if n_rows < 0:\n                    n_rows = 0\n            elif row_indices is ...:\n                n_rows = len(source)\n            else:\n                n_rows = len(row_indices)\n\n            self = cls()\n            self.domain = domain\n            conversion = DomainConversion(source.domain, domain)\n            self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                 is_sparse=conversion.sparse_X,\n                                 variables=domain.attributes)\n            if self.X.ndim == 1:\n                self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n            self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                 is_sparse=conversion.sparse_Y,\n                                 variables=domain.class_vars)\n\n            dtype = np.float64\n            if any(isinstance(var, StringVariable) for var in domain.metas):\n                dtype = np.object\n            self.metas = get_columns(row_indices, conversion.metas,\n                                     n_rows, dtype,\n                                     is_sparse=conversion.sparse_metas,\n                                     variables=domain.metas)\n            if self.metas.ndim == 1:\n                self.metas = self.metas.reshape(-1, len(self.domain.metas))\n            if source.has_weights():\n                self.W = source.W[row_indices]\n            else:\n                self.W = np.empty((n_rows, 0))\n            self.name = getattr(source, 'name', '')\n            if hasattr(source, 'ids'):\n                self.ids = source.ids[row_indices]\n            else:\n                cls._init_ids(self)\n            self.attributes = getattr(source, 'attributes', {})\n            _thread_local.conversion_cache[(id(domain), id(source))] = \\\n                self, (weakref.ref(domain), weakref.ref(source))\n            return self\n        finally:\n            if new_cache:\n                _thread_local.conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None,\n                   attributes=None, ids=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object, shape_1=X.shape[0])\n        ids, = _check_arrays(ids, dtype=int, shape_1=X.shape[0])\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        if ids is None:\n            cls._init_ids(self)\n        else:\n            self.ids = ids\n        self.attributes = {} if attributes is None else attributes\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    val = self.X[row_idx, col_idx]\n                elif col_idx >= len(self.domain.attributes):\n                    val = self._Y[row_idx,\n                                  col_idx - len(self.domain.attributes)]\n                else:\n                    val = self.metas[row_idx, -1 - col_idx]\n                if isinstance(col_idx, DiscreteVariable) and var is not col_idx:\n                    val = col_idx.get_mapper_from(var)(val)\n                return Value(var, val)\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            if isinstance(col_idx, DiscreteVariable) \\\n                    and self.domain[col_idx] != col_idx:\n                values = self.domain[col_idx].get_mapper_from(col_idx)(values)\n            for val, col_idx in zip(values, col_idx):\n                if not isinstance(val, Integral):\n                    val = self.domain[col_idx].to_val(val)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = val\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = val\n                else:\n                    self.metas[row_idx, -1 - col_idx] = val\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    @classmethod\n    def concatenate(cls, tables, axis=0):\n        \"\"\"Concatenate tables into a new table\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if axis == 1:\n            raise ValueError(\"concatenate no longer supports axis 1\")\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        domain = tables[0].domain\n        if any(table.domain != domain for table in tables):\n            raise ValueError('concatenated tables must have the same domain')\n\n        conc = cls.from_numpy(\n            domain,\n            vstack(collect(\"X\")),\n            merge1d(collect(\"Y\")),\n            vstack(collect(\"metas\")),\n            merge1d(collect(\"W\"))\n        )\n        conc.ids = np.hstack([t.ids for t in tables])\n        names = [table.name for table in tables if table.name != \"untitled\"]\n        if names:\n            conc.name = names[0]\n        # TODO: Add attributes = {} to __init__\n        conc.attributes = getattr(conc, \"attributes\", {})\n        for table in reversed(tables):\n            conc.attributes.update(table.attributes)\n        return conc\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if isinstance(index, Integral):\n            col_index = index\n        else:\n            col_index = self.domain.index(index)\n        if col_index >= 0:\n            if col_index < self.X.shape[1]:\n                col = rx(self.X[:, col_index])\n            else:\n                col = rx(self._Y[:, col_index - self.X.shape[1]])\n        else:\n            col = rx(self.metas[:, -1 - col_index])\n\n        if isinstance(index, DiscreteVariable) \\\n                and index.values != self.domain[col_index].values:\n            col = index.get_mapper_from(self.domain[col_index])(col[0]), col[1]\n            col[0].flags.writeable = False\n        return col\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        # structure of function is obvious; pylint: disable=too-many-branches\n        def _sp_anynan(a):\n            return a.indptr[1:] != a[-1:] + a.shape[1]\n\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = _sp_anynan(self.X)\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove += _sp_anynan(self._Y)\n            else:\n                remove += bn.anynan(self._Y, axis=1)\n            if sp.issparse(self.metas):\n                remove += _sp_anynan(self._metas)\n            else:\n                for i, var in enumerate(self.domain.metas):\n                    col = self.metas[:, i].flatten()\n                    if var.is_primitive():\n                        remove += np.isnan(col.astype(float))\n                    else:\n                        remove += ~col.astype(bool)\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove += col == 0\n                elif self.domain[column].is_primitive():\n                    remove += bn.anynan([col.astype(float)], axis=0)\n                else:\n                    remove += col.astype(bool)\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, IsDefined, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        def get_col_indices():\n            cols = chain(self.domain.variables, self.domain.metas)\n            if isinstance(filter, IsDefined):\n                if filter.columns is not None:\n                    return list(filter.columns)\n                else:\n                    return list(cols)\n\n            if filter.column is not None:\n                return [filter.column]\n\n            if isinstance(filter, FilterDiscrete):\n                raise ValueError(\"Discrete filter can't be applied across rows\")\n            if isinstance(filter, FilterContinuous):\n                return [col for col in cols if col.is_continuous]\n            if isinstance(filter,\n                          (FilterString, FilterStringList, FilterRegex)):\n                return [col for col in cols if col.is_string]\n            raise TypeError(\"Invalid filter\")\n\n        def col_filter(col_idx):\n            col = self.get_column_view(col_idx)[0]\n            if isinstance(filter, IsDefined):\n                if self.domain[col_idx].is_primitive():\n                    return ~np.isnan(col.astype(float))\n                else:\n                    return col.astype(np.bool)\n            if isinstance(filter, FilterDiscrete):\n                return self._discrete_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterContinuous):\n                return self._continuous_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterString):\n                return self._string_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterStringList):\n                if not filter.case_sensitive:\n                    col = np.char.lower(np.array(col, dtype=str))\n                    vals = [val.lower() for val in filter.values]\n                else:\n                    vals = filter.values\n                return reduce(operator.add, (col == val for val in vals))\n            if isinstance(filter, FilterRegex):\n                return np.vectorize(filter)(col)\n            raise TypeError(\"Invalid filter\")\n\n        col_indices = get_col_indices()\n        if len(col_indices) == 1:\n            sel = col_filter(col_indices[0])\n        else:\n            sel = np.ones(len(self), dtype=bool)\n            for col_idx in col_indices:\n                sel *= col_filter(col_idx)\n\n        if isinstance(filter, IsDefined) and filter.negate:\n            sel = ~sel\n        return sel\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        with np.errstate(invalid=\"ignore\"):   # nan's are properly discarded\n            if filter.oper == filter.Equal:\n                return col == fmin\n            if filter.oper == filter.NotEqual:\n                return col != fmin\n            if filter.oper == filter.Less:\n                return col < fmin\n            if filter.oper == filter.LessEqual:\n                return col <= fmin\n            if filter.oper == filter.Greater:\n                return col > fmin\n            if filter.oper == filter.GreaterEqual:\n                return col >= fmin\n            if filter.oper == filter.Between:\n                return (col >= fmin) * (col <= fmax)\n            if filter.oper == filter.Outside:\n                return (col < fmin) + (col > fmax)\n\n            raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        # when we select a column in sparse matrix it is still two dimensional\n        # and sparse - since it is just a column we can afford to transform\n        # it to dense and make it 1D\n        if issparse(row_data):\n            row_data = row_data.toarray().ravel()\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans_cols, nans_rows, nans = contingency(\n                        arr, row_data, max_vals - 1, n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (\n                            conts[arr_i][:, :n_vals], nans_cols[arr_i],\n                            nans_rows[arr_i], nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n                W_ = None\n                if W is not None:\n                    W_ = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W_ is None else W_[rows]\n                        classes_ = row_data[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W_, row_data\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    contingencies[col_i] = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n\n        return contingencies\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\",\n                  meta_attr_name=\"Feature name\", feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :param feature_name: str - default feature name prefix\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        if feature_names_column:\n            names = [str(row[feature_names_column]) for row in table]\n            names = get_unique_names_duplicates(names)\n            attributes = [ContinuousVariable(name) for name in names]\n        else:\n            places = int(np.ceil(np.log10(n_cols))) if n_cols else 1\n            attributes = [ContinuousVariable(f\"{feature_name} {i:0{places}}\")\n                          for i in range(1, n_cols + 1)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None, shape_1=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    if shape_1 is None:\n        shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            array[np.isinf(array)] = np.nan\n            warnings.warn(\"Array contains infinity.\", RuntimeWarning)\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = DomainConversion(source.domain, target.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\n",
            "new_file_content": "import operator\nimport os\nimport threading\nimport warnings\nimport weakref\nimport zlib\nfrom collections import Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock\n\nimport bottleneck as bn\nimport numpy as np\nfrom Orange.misc.collections import frozendict\nfrom Orange.util import OrangeDeprecationWarning\nfrom scipy import sparse as sp\nfrom scipy.sparse import issparse, csc_matrix\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES,\n    DomainConversion)\nfrom Orange.data.util import SharedComputeValue, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse, get_unique_names_duplicates\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\nclass _ThreadLocal(threading.local):\n    def __init__(self):\n        super().__init__()\n        # Domain conversion cache used in Table.from_table. It is defined\n        # here instead of as a class variable of a Table so that caching also works\n        # with descendants of Table.\n        self.conversion_cache = None\n\n\n_thread_local = _ThreadLocal()\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(Sequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    domain = Domain([])\n    X = _Y = metas = W = np.zeros((0, 0))\n    X.setflags(write=False)\n    ids = np.zeros(0)\n    ids.setflags(write=False)\n    attributes = frozendict()\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        if sp.issparse(value):\n            value = value.toarray()\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        def warn_deprecated(method):\n            warnings.warn(\"Direct calls to Table's constructor are deprecated \"\n                          \"and will be removed. Replace this call with \"\n                          f\"Table.{method}\", OrangeDeprecationWarning,\n                          stacklevel=3)\n\n        if not args:\n            if not kwargs:\n                return super().__new__(cls)\n            else:\n                raise TypeError(\"Table() must not be called directly\")\n\n        if isinstance(args[0], str):\n            if len(args) > 1:\n                raise TypeError(\"Table(name: str) expects just one argument\")\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0], **kwargs)\n\n        elif isinstance(args[0], Table):\n            if len(args) > 1:\n                raise TypeError(\"Table(table: Table) expects just one argument\")\n            return cls.from_table(args[0].domain, args[0], **kwargs)\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                warn_deprecated(\"from_domain\")\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                warn_deprecated(\"from_table\")\n                return cls.from_table(domain, *args, **kwargs)\n            elif isinstance(args[0], list):\n                warn_deprecated(\"from_list\")\n                return cls.from_list(domain, *args, **kwargs)\n        else:\n            warnings.warn(\"Omitting domain in a call to Table(X, Y, metas), is \"\n                          \"deprecated and will be removed. \"\n                          \"Call Table.from_numpy(None, X, Y, metas) instead.\",\n                          OrangeDeprecationWarning, stacklevel=2)\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        def valid_refs(weakrefs):\n            for r in weakrefs:\n                if r() is None:\n                    return False\n            return True\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64,\n                        is_sparse=False, variables=[]):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize arrays & set `match_density` for columns\n            # F-order enables faster writing to the array while accessing and\n            # matrix operations work with same speed (e.g. dot)\n            a = None if is_sparse else np.zeros(\n                (n_rows, len(src_cols)), order=\"F\", dtype=dtype)\n            data = []\n            sp_col = []\n            sp_row = []\n            match_density = (\n                assure_column_sparse if is_sparse else assure_column_dense\n            )\n\n            # converting to csc before instead of each column is faster\n            # do not convert if not required\n            if any([isinstance(x, int) for x in src_cols]):\n                X = csc_matrix(source.X) if is_sparse else source.X\n                Y = csc_matrix(source._Y) if is_sparse else source._Y\n\n            shared_cache = _thread_local.conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    col_array = match_density(\n                        np.full((n_rows, 1), variables[i].Unknown)\n                    )\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        shared, weakrefs = shared_cache.get(\n                            (id(col.compute_shared), id(source)),\n                            (None, None)\n                        )\n                        if shared is None or not valid_refs(weakrefs):\n                            shared, _ = shared_cache[(id(col.compute_shared), id(source))] = \\\n                                col.compute_shared(source), \\\n                                (weakref.ref(col.compute_shared), weakref.ref(source))\n\n                        if row_indices is not ...:\n                            col_array = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            col_array = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            col_array = match_density(col(source)[row_indices])\n                        else:\n                            col_array = match_density(col(source))\n                elif col < 0:\n                    col_array = match_density(\n                        source.metas[row_indices, -1 - col]\n                    )\n                elif col < n_src_attrs:\n                    col_array = match_density(X[row_indices, col])\n                else:\n                    col_array = match_density(\n                        Y[row_indices, col - n_src_attrs]\n                    )\n\n                if is_sparse:\n                    # col_array should be coo matrix\n                    data.append(col_array.data)\n                    sp_col.append(np.full(len(col_array.data), i))\n                    sp_row.append(col_array.indices)  # row indices should be same\n                else:\n                    a[:, i] = col_array\n\n            if is_sparse:\n                # creating csr directly would need plenty of manual work which\n                # would probably slow down the process - conversion coo to csr\n                # is fast\n                a = sp.coo_matrix(\n                    (np.hstack(data), (np.hstack(sp_row), np.hstack(sp_col))),\n                    shape=(n_rows, len(src_cols)),\n                    dtype=dtype\n                )\n                a = a.tocsr()\n\n            return a\n\n        new_cache = _thread_local.conversion_cache is None\n        try:\n            if new_cache:\n                _thread_local.conversion_cache = {}\n            else:\n                cached, weakrefs = \\\n                    _thread_local.conversion_cache.get((id(domain), id(source)), (None, None))\n                if cached and valid_refs(weakrefs):\n                    return cached\n            if domain is source.domain:\n                table = cls.from_table_rows(source, row_indices)\n                # assure resulting domain is the instance passed on input\n                table.domain = domain\n                # since sparse flags are not considered when checking for\n                # domain equality, fix manually.\n                table = assure_domain_conversion_sparsity(table, source)\n                return table\n\n            if isinstance(row_indices, slice):\n                start, stop, stride = row_indices.indices(source.X.shape[0])\n                n_rows = (stop - start) // stride\n                if n_rows < 0:\n                    n_rows = 0\n            elif row_indices is ...:\n                n_rows = len(source)\n            else:\n                n_rows = len(row_indices)\n\n            self = cls()\n            self.domain = domain\n            conversion = DomainConversion(source.domain, domain)\n            self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                 is_sparse=conversion.sparse_X,\n                                 variables=domain.attributes)\n            if self.X.ndim == 1:\n                self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n            self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                 is_sparse=conversion.sparse_Y,\n                                 variables=domain.class_vars)\n\n            dtype = np.float64\n            if any(isinstance(var, StringVariable) for var in domain.metas):\n                dtype = np.object\n            self.metas = get_columns(row_indices, conversion.metas,\n                                     n_rows, dtype,\n                                     is_sparse=conversion.sparse_metas,\n                                     variables=domain.metas)\n            if self.metas.ndim == 1:\n                self.metas = self.metas.reshape(-1, len(self.domain.metas))\n            if source.has_weights():\n                self.W = source.W[row_indices]\n            else:\n                self.W = np.empty((n_rows, 0))\n            self.name = getattr(source, 'name', '')\n            if hasattr(source, 'ids'):\n                self.ids = source.ids[row_indices]\n            else:\n                cls._init_ids(self)\n            self.attributes = getattr(source, 'attributes', {})\n            _thread_local.conversion_cache[(id(domain), id(source))] = \\\n                self, (weakref.ref(domain), weakref.ref(source))\n            return self\n        finally:\n            if new_cache:\n                _thread_local.conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None,\n                   attributes=None, ids=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object, shape_1=X.shape[0])\n        ids, = _check_arrays(ids, dtype=int, shape_1=X.shape[0])\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        if ids is None:\n            cls._init_ids(self)\n        else:\n            self.ids = ids\n        self.attributes = {} if attributes is None else attributes\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    val = self.X[row_idx, col_idx]\n                elif col_idx >= len(self.domain.attributes):\n                    val = self._Y[row_idx,\n                                  col_idx - len(self.domain.attributes)]\n                else:\n                    val = self.metas[row_idx, -1 - col_idx]\n                if isinstance(col_idx, DiscreteVariable) and var is not col_idx:\n                    val = col_idx.get_mapper_from(var)(val)\n                return Value(var, val)\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            if isinstance(col_idx, DiscreteVariable) \\\n                    and self.domain[col_idx] != col_idx:\n                values = self.domain[col_idx].get_mapper_from(col_idx)(values)\n            for val, col_idx in zip(values, col_idx):\n                if not isinstance(val, Integral):\n                    val = self.domain[col_idx].to_val(val)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = val\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = val\n                else:\n                    self.metas[row_idx, -1 - col_idx] = val\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    @classmethod\n    def concatenate(cls, tables, axis=0):\n        \"\"\"Concatenate tables into a new table\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if axis == 1:\n            raise ValueError(\"concatenate no longer supports axis 1\")\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        domain = tables[0].domain\n        if any(table.domain != domain for table in tables):\n            raise ValueError('concatenated tables must have the same domain')\n\n        conc = cls.from_numpy(\n            domain,\n            vstack(collect(\"X\")),\n            merge1d(collect(\"Y\")),\n            vstack(collect(\"metas\")),\n            merge1d(collect(\"W\"))\n        )\n        conc.ids = np.hstack([t.ids for t in tables])\n        names = [table.name for table in tables if table.name != \"untitled\"]\n        if names:\n            conc.name = names[0]\n        # TODO: Add attributes = {} to __init__\n        conc.attributes = getattr(conc, \"attributes\", {})\n        for table in reversed(tables):\n            conc.attributes.update(table.attributes)\n        return conc\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if isinstance(index, Integral):\n            col_index = index\n        else:\n            col_index = self.domain.index(index)\n        if col_index >= 0:\n            if col_index < self.X.shape[1]:\n                col = rx(self.X[:, col_index])\n            else:\n                col = rx(self._Y[:, col_index - self.X.shape[1]])\n        else:\n            col = rx(self.metas[:, -1 - col_index])\n\n        if isinstance(index, DiscreteVariable) \\\n                and index.values != self.domain[col_index].values:\n            col = index.get_mapper_from(self.domain[col_index])(col[0]), col[1]\n            col[0].flags.writeable = False\n        return col\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        # structure of function is obvious; pylint: disable=too-many-branches\n        def _sp_anynan(a):\n            return a.indptr[1:] != a[-1:] + a.shape[1]\n\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = _sp_anynan(self.X)\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove += _sp_anynan(self._Y)\n            else:\n                remove += bn.anynan(self._Y, axis=1)\n            if sp.issparse(self.metas):\n                remove += _sp_anynan(self._metas)\n            else:\n                for i, var in enumerate(self.domain.metas):\n                    col = self.metas[:, i].flatten()\n                    if var.is_primitive():\n                        remove += np.isnan(col.astype(float))\n                    else:\n                        remove += ~col.astype(bool)\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove += col == 0\n                elif self.domain[column].is_primitive():\n                    remove += bn.anynan([col.astype(float)], axis=0)\n                else:\n                    remove += col.astype(bool)\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, IsDefined, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        def get_col_indices():\n            cols = chain(self.domain.variables, self.domain.metas)\n            if isinstance(filter, IsDefined):\n                if filter.columns is not None:\n                    return list(filter.columns)\n                else:\n                    return list(cols)\n\n            if filter.column is not None:\n                return [filter.column]\n\n            if isinstance(filter, FilterDiscrete):\n                raise ValueError(\"Discrete filter can't be applied across rows\")\n            if isinstance(filter, FilterContinuous):\n                return [col for col in cols if col.is_continuous]\n            if isinstance(filter,\n                          (FilterString, FilterStringList, FilterRegex)):\n                return [col for col in cols if col.is_string]\n            raise TypeError(\"Invalid filter\")\n\n        def col_filter(col_idx):\n            col = self.get_column_view(col_idx)[0]\n            if isinstance(filter, IsDefined):\n                if self.domain[col_idx].is_primitive():\n                    return ~np.isnan(col.astype(float))\n                else:\n                    return col.astype(np.bool)\n            if isinstance(filter, FilterDiscrete):\n                return self._discrete_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterContinuous):\n                return self._continuous_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterString):\n                return self._string_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterStringList):\n                if not filter.case_sensitive:\n                    col = np.char.lower(np.array(col, dtype=str))\n                    vals = [val.lower() for val in filter.values]\n                else:\n                    vals = filter.values\n                return reduce(operator.add, (col == val for val in vals))\n            if isinstance(filter, FilterRegex):\n                return np.vectorize(filter)(col)\n            raise TypeError(\"Invalid filter\")\n\n        col_indices = get_col_indices()\n        if len(col_indices) == 1:\n            sel = col_filter(col_indices[0])\n        else:\n            sel = np.ones(len(self), dtype=bool)\n            for col_idx in col_indices:\n                sel *= col_filter(col_idx)\n\n        if isinstance(filter, IsDefined) and filter.negate:\n            sel = ~sel\n        return sel\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        with np.errstate(invalid=\"ignore\"):   # nan's are properly discarded\n            if filter.oper == filter.Equal:\n                return col == fmin\n            if filter.oper == filter.NotEqual:\n                return col != fmin\n            if filter.oper == filter.Less:\n                return col < fmin\n            if filter.oper == filter.LessEqual:\n                return col <= fmin\n            if filter.oper == filter.Greater:\n                return col > fmin\n            if filter.oper == filter.GreaterEqual:\n                return col >= fmin\n            if filter.oper == filter.Between:\n                return (col >= fmin) * (col <= fmax)\n            if filter.oper == filter.Outside:\n                return (col < fmin) + (col > fmax)\n\n            raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        # when we select a column in sparse matrix it is still two dimensional\n        # and sparse - since it is just a column we can afford to transform\n        # it to dense and make it 1D\n        if issparse(row_data):\n            row_data = row_data.toarray().ravel()\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans_cols, nans_rows, nans = contingency(\n                        arr, row_data, max_vals - 1, n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (\n                            conts[arr_i][:, :n_vals], nans_cols[arr_i],\n                            nans_rows[arr_i], nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n                W_ = None\n                if W is not None:\n                    W_ = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W_ is None else W_[rows]\n                        classes_ = row_data[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W_, row_data\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    contingencies[col_i] = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n\n        return contingencies\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\",\n                  meta_attr_name=\"Feature name\", feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :param feature_name: str - default feature name prefix\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        if feature_names_column:\n            names = [str(row[feature_names_column]) for row in table]\n            names = get_unique_names_duplicates(names)\n            attributes = [ContinuousVariable(name) for name in names]\n        else:\n            places = int(np.ceil(np.log10(n_cols))) if n_cols else 1\n            attributes = [ContinuousVariable(f\"{feature_name} {i:0{places}}\")\n                          for i in range(1, n_cols + 1)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None, shape_1=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    if shape_1 is None:\n        shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            if not (sp.isspmatrix_csr(array) or sp.isspmatrix_csc(array)):\n                array = array.tocsr()\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            array[np.isinf(array)] = np.nan\n            warnings.warn(\"Array contains infinity.\", RuntimeWarning)\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = DomainConversion(source.domain, target.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\n",
            "header": {
                "file": {
                    "path": "Orange/data/table.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "47f7668e5",
                "new_commit_hash": "f9deb6f98",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/data/table.py"
            },
            "plus_file": {
                "path": "b/Orange/data/table.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1751,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1751,
                            "length": 8
                        },
                        "section": "def _check_arrays(*arrays, dtype=None, shape_1=None):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                             % (ninstances(array), shape_1))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if sp.issparse(array):",
                                "type": "context"
                            },
                            {
                                "content": "            if not (sp.isspmatrix_csr(array) or sp.isspmatrix_csc(array)):",
                                "type": "added"
                            },
                            {
                                "content": "                array = array.tocsr()",
                                "type": "added"
                            },
                            {
                                "content": "            array.data = np.asarray(array.data)",
                                "type": "context"
                            },
                            {
                                "content": "            has_inf = _check_inf(array.data)",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/data/table.py",
                            "type": "function",
                            "name": "_check_arrays",
                            "content": "def _check_arrays(*arrays, dtype=None, shape_1=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    if shape_1 is None:\n        shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            if not (sp.isspmatrix_csr(array) or sp.isspmatrix_csc(array)):\n                array = array.tocsr()\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            array[np.isinf(array)] = np.nan\n            warnings.warn(\"Array contains infinity.\", RuntimeWarning)\n        checked.append(array)\n\n    return checked",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 1730,
                            "end_lineno": 1770,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import unittest\n\nimport numpy as np\n\nfrom Orange.data import (\n    ContinuousVariable, DiscreteVariable, StringVariable,\n    Domain, Table, IsDefined, FilterContinuous, Values, FilterString,\n    FilterDiscrete, FilterStringList, FilterRegex)\nfrom Orange.util import OrangeDeprecationWarning\n\n\nclass TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n\nclass TestTableFilters(unittest.TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            [ContinuousVariable(\"c1\"),\n             ContinuousVariable(\"c2\"),\n             DiscreteVariable(\"d1\", values=(\"a\", \"b\"))],\n            ContinuousVariable(\"y\"),\n            [ContinuousVariable(\"c3\"),\n             DiscreteVariable(\"d2\", values=(\"c\", \"d\")),\n             StringVariable(\"s1\"),\n             StringVariable(\"s2\")]\n        )\n        metas = np.array(\n            [0, 1, 0, 1, 1, np.nan, 1] +\n            [0, 0, 0, 0, np.nan, 1, 1] +\n            \"a  b  c  d  e     f    g\".split() +\n            list(\"ABCDEF\") + [\"\"], dtype=object).reshape(-1, 7).T\n        self.table = Table.from_numpy(\n            self.domain,\n            np.array(\n                [[0, 0, 0],\n                 [0, -1, 0],\n                 [np.nan, 1, 0],\n                 [1, 1, np.nan],\n                 [1, 1, 1],\n                 [1, 1, 1],\n                 [1, 1, 1]]),\n            np.array(\n                [0, 1, 0, 1, np.nan, 1, 1]),\n            metas\n        )\n\n    def test_row_filters_is_defined(self):\n        filtered = IsDefined()(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdg\"))\n\n        val_filter = Values([FilterString(None, FilterString.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdef\"))\n\n        val_filter = Values([IsDefined()])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([IsDefined(negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"])])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"], negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"c\"))\n\n    def test_row_filter_no_discrete(self):\n        val_filter = Values([FilterDiscrete(None, \"a\")])\n        self.assertRaises(ValueError, val_filter, self.table)\n\n    def test_row_filter_continuous(self):\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.GreaterEqual, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"adg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Greater, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"dg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Less, 1)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), [\"a\"])\n\n    def test_row_filter_string(self):\n        self.table.metas[:, -1] = self.table.metas[::-1, -2]\n        val_filter = Values([\n            FilterString(None, FilterString.Between, \"c\", \"e\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cde\"))\n\n    def test_row_stringlist(self):\n        val_filter = Values([\n            FilterStringList(None, list(\"bBdDe\"))])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n        val_filter = Values([\n            FilterStringList(None, list(\"bDe\"), case_sensitive=False)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bde\"))\n\n    def test_row_stringregex(self):\n        val_filter = Values([FilterRegex(None, \"[bBdDe]\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n    def test_is_defined(self):\n        val_filter = IsDefined(columns=[\"c3\"])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdeg\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "import unittest\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom Orange.data import (\n    ContinuousVariable, DiscreteVariable, StringVariable,\n    Domain, Table, IsDefined, FilterContinuous, Values, FilterString,\n    FilterDiscrete, FilterStringList, FilterRegex)\nfrom Orange.util import OrangeDeprecationWarning\n\n\nclass TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n\n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n\n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n\n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.lil_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.bsr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n\nclass TestTableFilters(unittest.TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            [ContinuousVariable(\"c1\"),\n             ContinuousVariable(\"c2\"),\n             DiscreteVariable(\"d1\", values=(\"a\", \"b\"))],\n            ContinuousVariable(\"y\"),\n            [ContinuousVariable(\"c3\"),\n             DiscreteVariable(\"d2\", values=(\"c\", \"d\")),\n             StringVariable(\"s1\"),\n             StringVariable(\"s2\")]\n        )\n        metas = np.array(\n            [0, 1, 0, 1, 1, np.nan, 1] +\n            [0, 0, 0, 0, np.nan, 1, 1] +\n            \"a  b  c  d  e     f    g\".split() +\n            list(\"ABCDEF\") + [\"\"], dtype=object).reshape(-1, 7).T\n        self.table = Table.from_numpy(\n            self.domain,\n            np.array(\n                [[0, 0, 0],\n                 [0, -1, 0],\n                 [np.nan, 1, 0],\n                 [1, 1, np.nan],\n                 [1, 1, 1],\n                 [1, 1, 1],\n                 [1, 1, 1]]),\n            np.array(\n                [0, 1, 0, 1, np.nan, 1, 1]),\n            metas\n        )\n\n    def test_row_filters_is_defined(self):\n        filtered = IsDefined()(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdg\"))\n\n        val_filter = Values([FilterString(None, FilterString.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdef\"))\n\n        val_filter = Values([IsDefined()])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([IsDefined(negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"])])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"], negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"c\"))\n\n    def test_row_filter_no_discrete(self):\n        val_filter = Values([FilterDiscrete(None, \"a\")])\n        self.assertRaises(ValueError, val_filter, self.table)\n\n    def test_row_filter_continuous(self):\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.GreaterEqual, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"adg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Greater, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"dg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Less, 1)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), [\"a\"])\n\n    def test_row_filter_string(self):\n        self.table.metas[:, -1] = self.table.metas[::-1, -2]\n        val_filter = Values([\n            FilterString(None, FilterString.Between, \"c\", \"e\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cde\"))\n\n    def test_row_stringlist(self):\n        val_filter = Values([\n            FilterStringList(None, list(\"bBdDe\"))])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n        val_filter = Values([\n            FilterStringList(None, list(\"bDe\"), case_sensitive=False)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bde\"))\n\n    def test_row_stringregex(self):\n        val_filter = Values([FilterRegex(None, \"[bBdDe]\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n    def test_is_defined(self):\n        val_filter = IsDefined(columns=[\"c3\"])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdeg\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/data/tests/test_table.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "37b40af10",
                "new_commit_hash": "4ed531453",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/data/tests/test_table.py"
            },
            "plus_file": {
                "path": "b/Orange/data/tests/test_table.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1,
                            "length": 7
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import unittest",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "import numpy as np",
                                "type": "context"
                            },
                            {
                                "content": "import scipy.sparse as sp",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.data import (",
                                "type": "context"
                            },
                            {
                                "content": "    ContinuousVariable, DiscreteVariable, StringVariable,",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/data/tests/test_table.py",
                            "type": "import",
                            "name": "scipy.sparse",
                            "content": "import scipy.sparse as sp",
                            "ast_type_str": "Import",
                            "start_lineno": 4,
                            "end_lineno": 4,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 85,
                            "length": 6
                        },
                        "new_range": {
                            "start": 86,
                            "length": 28
                        },
                        "section": "class TestTableInit(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertRaises(ValueError, func, dom, X, Y[:4])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_from_numpy_sparse(self):",
                                "type": "added"
                            },
                            {
                                "content": "        domain = Domain([ContinuousVariable(c) for c in \"abc\"])",
                                "type": "added"
                            },
                            {
                                "content": "        x = np.arange(12).reshape(4, 3)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, x, None, None)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(sp.issparse(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, sp.csr_matrix(x))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(sp.isspmatrix_csr(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, sp.csc_matrix(x))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(sp.isspmatrix_csc(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, sp.coo_matrix(x))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(sp.isspmatrix_csr(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, sp.lil_matrix(x))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(sp.isspmatrix_csr(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        t = Table.from_numpy(domain, sp.bsr_matrix(x))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(sp.isspmatrix_csr(t.X))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestTableFilters(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def setUp(self):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/data/tests/test_table.py",
                            "type": "class",
                            "name": "TestTableInit",
                            "content": "class TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n\n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n\n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n\n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.lil_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.bsr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 13,
                            "end_lineno": 109,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/data/tests/test_table.py",
                            "type": "method",
                            "name": "TestTableInit.test_from_numpy_sparse",
                            "content": "class TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n\n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n\n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n\n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.lil_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.bsr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 89,
                            "end_lineno": 109,
                            "parent": {
                                "file_name": "Orange/data/tests/test_table.py",
                                "type": "class",
                                "name": "TestTableInit",
                                "content": "class TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n\n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n\n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n\n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.lil_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.bsr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 13,
                                "end_lineno": 109,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "2317523ed2d75c647f2362e61e9d47fc6c0de86e^",
    "new_commit_hash": "2317523ed2d75c647f2362e61e9d47fc6c0de86e",
    "commit_message": "Table.numpy: Convert non-csr/csc matrices to csr",
    "commit_date": "2020-06-22T23:55:28+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "2317523ed2d75c647f2362e61e9d47fc6c0de86e",
    "test_file_codes": [
        "import unittest\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom Orange.data import (\n    ContinuousVariable, DiscreteVariable, StringVariable,\n    Domain, Table, IsDefined, FilterContinuous, Values, FilterString,\n    FilterDiscrete, FilterStringList, FilterRegex)\nfrom Orange.util import OrangeDeprecationWarning\n\n\nclass TestTableInit(unittest.TestCase):\n    def test_empty_table(self):\n        t = Table()\n        self.assertEqual(t.domain.attributes, ())\n        self.assertEqual(t.X.shape, (0, 0))\n        self.assertEqual(t.Y.shape, (0, 0))\n        self.assertEqual(t.W.shape, (0, 0))\n        self.assertEqual(t.metas.shape, (0, 0))\n        self.assertEqual(t.ids.shape, (0, ))\n        self.assertEqual(t.attributes, {})\n\n    def test_warnings(self):\n        domain = Domain([ContinuousVariable(\"x\")])\n        self.assertWarns(OrangeDeprecationWarning, Table, domain)\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, Table())\n        self.assertWarns(OrangeDeprecationWarning, Table, domain, [[12]])\n        self.assertWarns(OrangeDeprecationWarning, Table, np.zeros((5, 5)))\n\n    def test_invalid_call_with_kwargs(self):\n        self.assertRaises(TypeError, Table, Y=[])\n        self.assertRaises(TypeError, Table, \"iris\", 42)\n        self.assertRaises(TypeError, Table, Table(), 42)\n\n    def test_from_numpy(self):\n        X = np.arange(20).reshape(5, 4)\n        Y = np.arange(5) % 2\n        metas = np.array(list(\"abcde\")).reshape(5, 1)\n        W = np.arange(5) / 5\n        ids = np.arange(100, 105, dtype=np.int)\n        attributes = dict(a=5, b=\"foo\")\n\n        dom = Domain([ContinuousVariable(x) for x in \"abcd\"],\n                     DiscreteVariable(\"e\", values=(\"no\", \"yes\")),\n                     [StringVariable(\"s\")])\n\n        for func in (Table.from_numpy, Table):\n            table = func(dom, X, Y, metas, W, attributes, ids)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(attributes, table.attributes)\n            np.testing.assert_equal(ids, table.ids)\n\n            table = func(dom, X, Y, metas, W)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            np.testing.assert_equal(W, table.W)\n            self.assertEqual(ids.shape, (5, ))\n\n            table = func(dom, X, Y, metas)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            np.testing.assert_equal(metas, table.metas)\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes, dom.class_var), X, Y)\n            np.testing.assert_equal(X, table.X)\n            np.testing.assert_equal(Y, table.Y)\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            table = func(Domain(dom.attributes), X)\n            np.testing.assert_equal(X, table.X)\n            self.assertEqual(table.Y.shape, (5, 0))\n            self.assertEqual(table.metas.shape, (5, 0))\n            self.assertEqual(table.W.shape, (5, 0))\n            self.assertEqual(table.ids.shape, (5, ))\n\n            self.assertRaises(ValueError, func, dom, X, Y, metas, W[:4])\n            self.assertRaises(ValueError, func, dom, X, Y, metas[:4])\n            self.assertRaises(ValueError, func, dom, X, Y[:4])\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n\n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n\n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n\n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.lil_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n        t = Table.from_numpy(domain, sp.bsr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n\n\nclass TestTableFilters(unittest.TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            [ContinuousVariable(\"c1\"),\n             ContinuousVariable(\"c2\"),\n             DiscreteVariable(\"d1\", values=(\"a\", \"b\"))],\n            ContinuousVariable(\"y\"),\n            [ContinuousVariable(\"c3\"),\n             DiscreteVariable(\"d2\", values=(\"c\", \"d\")),\n             StringVariable(\"s1\"),\n             StringVariable(\"s2\")]\n        )\n        metas = np.array(\n            [0, 1, 0, 1, 1, np.nan, 1] +\n            [0, 0, 0, 0, np.nan, 1, 1] +\n            \"a  b  c  d  e     f    g\".split() +\n            list(\"ABCDEF\") + [\"\"], dtype=object).reshape(-1, 7).T\n        self.table = Table.from_numpy(\n            self.domain,\n            np.array(\n                [[0, 0, 0],\n                 [0, -1, 0],\n                 [np.nan, 1, 0],\n                 [1, 1, np.nan],\n                 [1, 1, 1],\n                 [1, 1, 1],\n                 [1, 1, 1]]),\n            np.array(\n                [0, 1, 0, 1, np.nan, 1, 1]),\n            metas\n        )\n\n    def test_row_filters_is_defined(self):\n        filtered = IsDefined()(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdg\"))\n\n        val_filter = Values([FilterString(None, FilterString.IsDefined)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdef\"))\n\n        val_filter = Values([IsDefined()])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"ab\"))\n\n        val_filter = Values([IsDefined(negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"])])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abdefg\"))\n\n        val_filter = Values([IsDefined([\"c1\"], negate=True)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"c\"))\n\n    def test_row_filter_no_discrete(self):\n        val_filter = Values([FilterDiscrete(None, \"a\")])\n        self.assertRaises(ValueError, val_filter, self.table)\n\n    def test_row_filter_continuous(self):\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.GreaterEqual, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"adg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Greater, 0)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"dg\"))\n\n        val_filter = Values([\n            FilterContinuous(None, FilterContinuous.Less, 1)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), [\"a\"])\n\n    def test_row_filter_string(self):\n        self.table.metas[:, -1] = self.table.metas[::-1, -2]\n        val_filter = Values([\n            FilterString(None, FilterString.Between, \"c\", \"e\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"cde\"))\n\n    def test_row_stringlist(self):\n        val_filter = Values([\n            FilterStringList(None, list(\"bBdDe\"))])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n        val_filter = Values([\n            FilterStringList(None, list(\"bDe\"), case_sensitive=False)])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bde\"))\n\n    def test_row_stringregex(self):\n        val_filter = Values([FilterRegex(None, \"[bBdDe]\")])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"bd\"))\n\n    def test_is_defined(self):\n        val_filter = IsDefined(columns=[\"c3\"])\n        filtered = val_filter(self.table)\n        self.assertEqual(list(filtered.metas[:, -2].flatten()), list(\"abcdeg\"))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\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.projection._som\" 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/tmpq9tbr5u3/tmp\ncreating /tmp/tmpq9tbr5u3/tmp/tmpq9tbr5u3\ncompile options: '-MMD -MF /tmp/tmpq9tbr5u3/file.c.d -c'\ncc: /tmp/tmpq9tbr5u3/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/tmpvs2q1mzj/tmp\ncreating /tmp/tmpvs2q1mzj/tmp/tmpvs2q1mzj\ncompile options: '-MMD -MF /tmp/tmpvs2q1mzj/file.c.d -c'\ncc: /tmp/tmpvs2q1mzj/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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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.projection._som' 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/projection\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/projection/_som.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/projection/_som.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/projection/_som.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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\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.projection._som\" 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 '*.js' under directory 'Orange/widgets'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching '*.html' 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/tmp_ihb1go7/tmp\ncreating /tmp/tmp_ihb1go7/tmp/tmp_ihb1go7\ncompile options: '-MMD -MF /tmp/tmp_ihb1go7/file.c.d -c'\ncc: /tmp/tmp_ihb1go7/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/tmp6jk1feou/tmp\ncreating /tmp/tmp6jk1feou/tmp/tmp6jk1feou\ncompile options: '-MMD -MF /tmp/tmp6jk1feou/file.c.d -c'\ncc: /tmp/tmp6jk1feou/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.27.0.dev0+2317523 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e\nProcessing dependencies for Orange3==3.27.0.dev0+2317523\nSearching for XlsxWriter==3.2.0\nBest match: XlsxWriter 3.2.0\nAdding XlsxWriter 3.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for PyYAML==6.0.1\nBest match: PyYAML 6.0.1\nAdding PyYAML 6.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for pandas==1.3.5\nBest match: pandas 1.3.5\nAdding pandas 1.3.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.22.0\nBest match: orange-widget-base 4.22.0\nAdding orange-widget-base 4.22.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for orange-canvas-core==0.1.35\nBest match: orange-canvas-core 0.1.35\nAdding orange-canvas-core 0.1.35 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for openpyxl==3.1.3\nBest match: openpyxl 3.1.3\nAdding openpyxl 3.1.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for openTSNE==1.0.1\nBest match: openTSNE 1.0.1\nAdding openTSNE 1.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for httpx==0.24.1\nBest match: httpx 0.24.1\nAdding httpx 0.24.1 to easy-install.pth file\nInstalling httpx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for baycomp==1.0.3\nBest match: baycomp 1.0.3\nAdding baycomp 1.0.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for pytz==2024.2\nBest match: pytz 2024.2\nAdding pytz 2024.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for requests-cache==1.1.1\nBest match: requests-cache 1.1.1\nAdding requests-cache 1.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for qasync==0.25.0\nBest match: qasync 0.25.0\nAdding qasync 0.25.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for dictdiffer==0.9.0\nBest match: dictdiffer 0.9.0\nAdding dictdiffer 0.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for commonmark==0.9.1\nBest match: commonmark 0.9.1\nAdding commonmark 0.9.1 to easy-install.pth file\nInstalling cmark script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for et-xmlfile==1.1.0\nBest match: et-xmlfile 1.1.0\nAdding et-xmlfile 1.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for sniffio==1.3.1\nBest match: sniffio 1.3.1\nAdding sniffio 1.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for httpcore==0.17.3\nBest match: httpcore 0.17.3\nAdding httpcore 0.17.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for attrs==24.2.0\nBest match: attrs 24.2.0\nAdding attrs 24.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for url-normalize==1.4.3\nBest match: url-normalize 1.4.3\nAdding url-normalize 1.4.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for cattrs==23.1.2\nBest match: cattrs 23.1.2\nAdding cattrs 23.1.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for platformdirs==4.0.0\nBest match: platformdirs 4.0.0\nAdding platformdirs 4.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for anyio==3.7.1\nBest match: anyio 3.7.1\nAdding anyio 3.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for h11==0.14.0\nBest match: h11 0.14.0\nAdding h11 0.14.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nSearching for exceptiongroup==1.2.2\nBest match: exceptiongroup 1.2.2\nAdding exceptiongroup 1.2.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.27.0.dev0+2317523\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 44ms\nPrepared 18 packages in 5ms\nInstalled 18 packages in 89ms\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 54 packages in 350ms\nInstalled 47 packages in 661ms\n + anyio==3.7.1\n + baycomp==1.0.3\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 + cycler==0.11.0\n + et-xmlfile==1.1.0\n + fonttools==4.38.0\n + h11==0.14.0\n + httpcore==0.17.3\n + httpx==0.24.1\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 + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + more-itertools==9.1.0\n + networkx==2.6.3\n + openpyxl==3.1.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pillow==9.5.0\n + pip==24.0\n + pycparser==2.21\n + pyparsing==3.1.4\n + python-dateutil==2.9.0.post0\n + python-louvain==0.16\n + pytz==2024.2\n + pyyaml==6.0.1\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 + six==1.17.0\n + sniffio==1.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 34 packages in 193ms\nInstalled 13 packages in 373ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.22.0\n + platformdirs==4.0.0\n + pyqtgraph==0.12.4\n + qasync==0.25.0\n + requests-cache==1.1.1\n + url-normalize==1.4.3\nResolved 2 packages in 3ms\nInstalled 2 packages in 40ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nAudited 1 package in 30ms\nAudited 2 packages in 2ms\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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:627:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/projection/_som.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_5update_hex’:\nOrange/projection/_som.c:3655:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3655 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3654:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3654 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_7get_winners_sparse’:\nOrange/projection/_som.c:4547:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4547 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_39, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4114:7: note: ‘__pyx_v_win_y’ was declared here\n 4114 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4536:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4536 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4113:7: note: ‘__pyx_v_win_x’ was declared here\n 4113 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_8update_sparse.constprop’:\nOrange/projection/_som.c:4746:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4746 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4745:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4745 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_3update’:\nOrange/projection/_som.c:3141:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3141 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_1get_winners’:\nOrange/projection/_som.c:2964:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2964 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_28, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2665:7: note: ‘__pyx_v_win_y’ was declared here\n 2665 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:2953:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2953 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2664:7: note: ‘__pyx_v_win_x’ was declared here\n 2664 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_10update_sparse_hex.constprop’:\nOrange/projection/_som.c:5515:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5515 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:5514:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5514 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e/.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_2317523ed2d75c647f2362e61e9d47fc6c0de86e\nplugins: anyio-3.7.1\ncollected 12 items\n\nr2e_tests/test_1.py ............                                         [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestTableInit::test_empty_table\nPASSED r2e_tests/test_1.py::TestTableInit::test_from_numpy\nPASSED r2e_tests/test_1.py::TestTableInit::test_from_numpy_sparse\nPASSED r2e_tests/test_1.py::TestTableInit::test_invalid_call_with_kwargs\nPASSED r2e_tests/test_1.py::TestTableInit::test_warnings\nPASSED r2e_tests/test_1.py::TestTableFilters::test_is_defined\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_continuous\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_no_discrete\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_string\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filters_is_defined\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_stringlist\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_stringregex\n============================== 12 passed in 2.06s ==============================\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_2317523ed2d75c647f2362e61e9d47fc6c0de86e\nplugins: anyio-3.7.1\ncollected 12 items\n\nr2e_tests/test_1.py ..F.........                                         [100%]\n\n=================================== FAILURES ===================================\n_____________________ TestTableInit.test_from_numpy_sparse _____________________\n\nself = <r2e_tests.test_1.TestTableInit testMethod=test_from_numpy_sparse>\n\n    def test_from_numpy_sparse(self):\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        x = np.arange(12).reshape(4, 3)\n    \n        t = Table.from_numpy(domain, x, None, None)\n        self.assertFalse(sp.issparse(t.X))\n    \n        t = Table.from_numpy(domain, sp.csr_matrix(x))\n        self.assertTrue(sp.isspmatrix_csr(t.X))\n    \n        t = Table.from_numpy(domain, sp.csc_matrix(x))\n        self.assertTrue(sp.isspmatrix_csc(t.X))\n    \n        t = Table.from_numpy(domain, sp.coo_matrix(x))\n>       self.assertTrue(sp.isspmatrix_csr(t.X))\nE       AssertionError: False is not true\n\nr2e_tests/test_1.py:103: AssertionError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestTableInit::test_empty_table\nPASSED r2e_tests/test_1.py::TestTableInit::test_from_numpy\nPASSED r2e_tests/test_1.py::TestTableInit::test_invalid_call_with_kwargs\nPASSED r2e_tests/test_1.py::TestTableInit::test_warnings\nPASSED r2e_tests/test_1.py::TestTableFilters::test_is_defined\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_continuous\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_no_discrete\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filter_string\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_filters_is_defined\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_stringlist\nPASSED r2e_tests/test_1.py::TestTableFilters::test_row_stringregex\nFAILED r2e_tests/test_1.py::TestTableInit::test_from_numpy_sparse - Assertion...\n========================= 1 failed, 11 passed in 2.35s =========================\n",
    "old_commit_res_stderr": ""
}
Orange/data/table.py Orange/data/tests/test_table.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `Table.from_numpy` Fails to Properly Handle Non-CSR/CSC Sparse Matrices

**Description:**
When creating a `Table` from a non-CSR/CSC sparse matrix using `Table.from_numpy`, the resulting table does not maintain the expected sparse matrix format. Specifically, passing COO, LIL, or BSR sparse matrices does not convert them to CSR as intended, leading to inconsistencies in how the data is stored and accessed.

**Example Code:**
```python
import numpy as np
import scipy.sparse as sp
from Orange.data import Domain, ContinuousVariable, Table

domain = Domain([ContinuousVariable(c) for c in "abc"])
x = np.arange(12).reshape(4, 3)

# Attempting to create a table from a COO matrix
t = Table.from_numpy(domain, sp.coo_matrix(x))
print(sp.isspmatrix_csr(t.X))  # Expected: True
```

**Expected Behavior:**
When a non-CSR/CSC sparse matrix (like COO, LIL, or BSR) is passed to `Table.from_numpy`, it should automatically convert the matrix to CSR format. The check `sp.isspmatrix_csr(t.X)` should return `True`, ensuring consistent sparse matrix representation within the `Table`.

**Actual Behavior:**
The table retains the original sparse matrix format (e.g., COO), causing `sp.isspmatrix_csr(t.X)` to return `False`. This leads to potential issues in downstream processing where CSR format is assumed.

[/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/data/table.py
import operator
import os
import threading
import warnings
import weakref
import zlib
from collections import Iterable, Sequence, Sized
from functools import reduce
from itertools import chain
from numbers import Real, Integral
from threading import Lock

import bottleneck as bn
import numpy as np
from Orange.misc.collections import frozendict
from Orange.util import OrangeDeprecationWarning
from scipy import sparse as sp
from scipy.sparse import issparse, csc_matrix

import Orange.data  # import for io.py
from Orange.data import (
    _contingency, _valuecount,
    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,
    ContinuousVariable, DiscreteVariable, MISSING_VALUES,
    DomainConversion)
from Orange.data.util import SharedComputeValue, \
    assure_array_dense, assure_array_sparse, \
    assure_column_dense, assure_column_sparse, get_unique_names_duplicates
from Orange.statistics.util import bincount, countnans, contingency, \
    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \
    sparse_implicit_zero_weights

__all__ = ["dataset_dirs", "get_sample_datasets_dir", "RowInstance", "Table"]


def get_sample_datasets_dir():
    orange_data_table = os.path.dirname(__file__)
    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')
    return os.path.realpath(dataset_dir)


dataset_dirs = ['', get_sample_datasets_dir()]


class _ThreadLocal(threading.local):
    def __init__(self):
        super().__init__()
        # Domain conversion cache used in Table.from_table. It is defined
        # here instead of as a class variable of a Table so that caching also works
        # with descendants of Table.
        self.conversion_cache = None


_thread_local = _ThreadLocal()


class DomainTransformationError(Exception):
    pass


class RowInstance(Instance):
    sparse_x = None
    sparse_y = None
    sparse_metas = None
    _weight = None

    def __init__(self, table, row_index):
        """
        Construct a data instance representing the given row of the table.
        """
        self.table = table
        self._domain = table.domain
        self.row_index = row_index
        self.id = table.ids[row_index]
        self._x = table.X[row_index]
        if sp.issparse(self._x):
            self.sparse_x = sp.csr_matrix(self._x)
            self._x = np.asarray(self._x.todense())[0]
        self._y = table._Y[row_index]
        if sp.issparse(self._y):
            self.sparse_y = sp.csr_matrix(self._y)
            self._y = np.asarray(self._y.todense())[0]
        self._metas = table.metas[row_index]
        if sp.issparse(self._metas):
            self.sparse_metas = sp.csr_matrix(self._metas)
            self._metas = np.asarray(self._metas.todense())[0]

    @property
    def weight(self):
        if not self.table.has_weights():
            return 1
        return self.table.W[self.row_index]

    @weight.setter
    def weight(self, weight):
        if not self.table.has_weights():
            self.table.set_weights()
        self.table.W[self.row_index] = weight

    def set_class(self, value):
        self._check_single_class()
        if not isinstance(value, Real):
            value = self.table.domain.class_var.to_val(value)
        self._y[0] = value
        if self.sparse_y:
            self.table._Y[self.row_index, 0] = value

    def __setitem__(self, key, value):
        if not isinstance(key, Integral):
            key = self._domain.index(key)
        if isinstance(value, str):
            var = self._domain[key]
            value = var.to_val(value)
        if key >= 0:
            if not isinstance(value, Real):
                raise TypeError("Expected primitive value, got '%s'" %
                                type(value).__name__)
            if key < len(self._x):
                self._x[key] = value
                if self.sparse_x is not None:
                    self.table.X[self.row_index, key] = value
            else:
                self._y[key - len(self._x)] = value
                if self.sparse_y is not None:
                    self.table._Y[self.row_index, key - len(self._x)] = value
        else:
            self._metas[-1 - key] = value
            if self.sparse_metas:
                self.table.metas[self.row_index, -1 - key] = value

    def _str(self, limit):
        def sp_values(matrix, variables):
            if not sp.issparse(matrix):
                if matrix.ndim == 1:
                    matrix = matrix[:, np.newaxis]
                return Instance.str_values(matrix[row], variables, limit)

            row_entries, idx = [], 0
            while idx < len(variables):
                # Make sure to stop printing variables if we limit the output
                if limit and len(row_entries) >= 5:
                    break

                var = variables[idx]
                if var.is_discrete or matrix[row, idx]:
                    row_entries.append("%s=%s" % (var.name, var.str_val(matrix[row, idx])))

                idx += 1

            s = ", ".join(row_entries)

            if limit and idx < len(variables):
                s += ", ..."

            return s

        table = self.table
        domain = table.domain
        row = self.row_index
        s = "[" + sp_values(table.X, domain.attributes)
        if domain.class_vars:
            s += " | " + sp_values(table.Y, domain.class_vars)
        s += "]"
        if self._domain.metas:
            s += " {" + sp_values(table.metas, domain.metas) + "}"
        return s

    def __str__(self):
        return self._str(False)

    def __repr__(self):
        return self._str(True)


class Columns:
    def __init__(self, domain):
        for v in chain(domain.variables, domain.metas):
            setattr(self, v.name.replace(" ", "_"), v)


# noinspection PyPep8Naming
class Table(Sequence, Storage):
    __file__ = None
    name = "untitled"

    domain = Domain([])
    X = _Y = metas = W = np.zeros((0, 0))
    X.setflags(write=False)
    ids = np.zeros(0)
    ids.setflags(write=False)
    attributes = frozendict()

    @property
    def columns(self):
        """
        A class whose attributes contain attribute descriptors for columns.
        For a table `table`, setting `c = table.columns` will allow accessing
        the table's variables with, for instance `c.gender`, `c.age` ets.
        Spaces are replaced with underscores.
        """
        return Columns(self.domain)

    _next_instance_id = 0
    _next_instance_lock = Lock()

    @property
    def Y(self):
        if self._Y.shape[1] == 1:
            return self._Y[:, 0]
        return self._Y

    @Y.setter
    def Y(self, value):
        if len(value.shape) == 1:
            value = value[:, None]
        if sp.issparse(value) and len(self) != value.shape[0]:
            value = value.T
        if sp.issparse(value):
            value = value.toarray()
        self._Y = value

    def __new__(cls, *args, **kwargs):
        def warn_deprecated(method):
            warnings.warn("Direct calls to Table's constructor are deprecated "
                          "and will be removed. Replace this call with "
                          f"Table.{method}", OrangeDeprecationWarning,
                          stacklevel=3)

        if not args:
            if not kwargs:
                return super().__new__(cls)
            else:
                raise TypeError("Table() must not be called directly")

        if isinstance(args[0], str):
            if len(args) > 1:
                raise TypeError("Table(name: str) expects just one argument")
            if args[0].startswith('https://') or args[0].startswith('http://'):
                return cls.from_url(args[0], **kwargs)
            else:
                return cls.from_file(args[0], **kwargs)

        elif isinstance(args[0], Table):
            if len(args) > 1:
                raise TypeError("Table(table: Table) expects just one argument")
            return cls.from_table(args[0].domain, args[0], **kwargs)
        elif isinstance(args[0], Domain):
            domain, args = args[0], args[1:]
            if not args:
                warn_deprecated("from_domain")
                return cls.from_domain(domain, **kwargs)
            if isinstance(args[0], Table):
                warn_deprecated("from_table")
                return cls.from_table(domain, *args, **kwargs)
            elif isinstance(args[0], list):
                warn_deprecated("from_list")
                return cls.from_list(domain, *args, **kwargs)
        else:
            warnings.warn("Omitting domain in a call to Table(X, Y, metas), is "
                          "deprecated and will be removed. "
                          "Call Table.from_numpy(None, X, Y, metas) instead.",
                          OrangeDeprecationWarning, stacklevel=2)
            domain = None

        return cls.from_numpy(domain, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        # So subclasses can expect to call super without breakage; noop
        pass

    @classmethod
    def from_domain(cls, domain, n_rows=0, weights=False):
        """
        Construct a new `Table` with the given number of rows for the given
        domain. The optional vector of weights is initialized to 1's.

        :param domain: domain for the `Table`
        :type domain: Orange.data.Domain
        :param n_rows: number of rows in the new table
        :type n_rows: int
        :param weights: indicates whether to construct a vector of weights
        :type weights: bool
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = domain
        self.n_rows = n_rows
        self.X = np.zeros((n_rows, len(domain.attributes)))
        self.Y = np.zeros((n_rows, len(domain.class_vars)))
        if weights:
            self.W = np.ones(n_rows)
        else:
            self.W = np.empty((n_rows, 0))
        self.metas = np.empty((n_rows, len(self.domain.metas)), object)
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_table(cls, domain, source, row_indices=...):
        """
        Create a new table from selected columns and/or rows of an existing
        one. The columns are chosen using a domain. The domain may also include
        variables that do not appear in the source table; they are computed
        from source variables if possible.

        The resulting data may be a view or a copy of the existing data.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param source: the source table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """

        def valid_refs(weakrefs):
            for r in weakrefs:
                if r() is None:
                    return False
            return True

        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64,
                        is_sparse=False, variables=[]):
            if not len(src_cols):
                if is_sparse:
                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)
                else:
                    return np.zeros((n_rows, 0), dtype=source.X.dtype)

            # match density for subarrays
            match_density = assure_array_sparse if is_sparse else assure_array_dense
            n_src_attrs = len(source.domain.attributes)
            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(source.X, row_indices, src_cols))
            if all(isinstance(x, Integral) and x < 0 for x in src_cols):
                arr = match_density(_subarray(source.metas, row_indices,
                                              [-1 - x for x in src_cols]))
                if arr.dtype != dtype:
                    return arr.astype(dtype)
                return arr
            if all(isinstance(x, Integral) and x >= n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(
                    source._Y, row_indices,
                    [x - n_src_attrs for x in src_cols]))

            # initialize arrays & set `match_density` for columns
            # F-order enables faster writing to the array while accessing and
            # matrix operations work with same speed (e.g. dot)
            a = None if is_sparse else np.zeros(
                (n_rows, len(src_cols)), order="F", dtype=dtype)
            data = []
            sp_col = []
            sp_row = []
            match_density = (
                assure_column_sparse if is_sparse else assure_column_dense
            )

            # converting to csc before instead of each column is faster
            # do not convert if not required
            if any([isinstance(x, int) for x in src_cols]):
                X = csc_matrix(source.X) if is_sparse else source.X
                Y = csc_matrix(source._Y) if is_sparse else source._Y

            shared_cache = _thread_local.conversion_cache
            for i, col in enumerate(src_cols):
                if col is None:
                    col_array = match_density(
                        np.full((n_rows, 1), variables[i].Unknown)
                    )
                elif not isinstance(col, Integral):
                    if isinstance(col, SharedComputeValue):
                        shared, weakrefs = shared_cache.get(
                            (id(col.compute_shared), id(source)),
                            (None, None)
                        )
                        if shared is None or not valid_refs(weakrefs):
                            shared, _ = shared_cache[(id(col.compute_shared), id(source))] = \
                                col.compute_shared(source), \
                                (weakref.ref(col.compute_shared), weakref.ref(source))

                        if row_indices is not ...:
                            col_array = match_density(
                                col(source, shared_data=shared)[row_indices])
                        else:
                            col_array = match_density(
                                col(source, shared_data=shared))
                    else:
                        if row_indices is not ...:
                            col_array = match_density(col(source)[row_indices])
                        else:
                            col_array = match_density(col(source))
                elif col < 0:
                    col_array = match_density(
                        source.metas[row_indices, -1 - col]
                    )
                elif col < n_src_attrs:
                    col_array = match_density(X[row_indices, col])
                else:
                    col_array = match_density(
                        Y[row_indices, col - n_src_attrs]
                    )

                if is_sparse:
                    # col_array should be coo matrix
                    data.append(col_array.data)
                    sp_col.append(np.full(len(col_array.data), i))
                    sp_row.append(col_array.indices)  # row indices should be same
                else:
                    a[:, i] = col_array

            if is_sparse:
                # creating csr directly would need plenty of manual work which
                # would probably slow down the process - conversion coo to csr
                # is fast
                a = sp.coo_matrix(
                    (np.hstack(data), (np.hstack(sp_row), np.hstack(sp_col))),
                    shape=(n_rows, len(src_cols)),
                    dtype=dtype
                )
                a = a.tocsr()

            return a

        new_cache = _thread_local.conversion_cache is None
        try:
            if new_cache:
                _thread_local.conversion_cache = {}
            else:
                cached, weakrefs = \
                    _thread_local.conversion_cache.get((id(domain), id(source)), (None, None))
                if cached and valid_refs(weakrefs):
                    return cached
            if domain is source.domain:
                table = cls.from_table_rows(source, row_indices)
                # assure resulting domain is the instance passed on input
                table.domain = domain
                # since sparse flags are not considered when checking for
                # domain equality, fix manually.
                table = assure_domain_conversion_sparsity(table, source)
                return table

            if isinstance(row_indices, slice):
                start, stop, stride = row_indices.indices(source.X.shape[0])
                n_rows = (stop - start) // stride
                if n_rows < 0:
                    n_rows = 0
            elif row_indices is ...:
                n_rows = len(source)
            else:
                n_rows = len(row_indices)

            self = cls()
            self.domain = domain
            conversion = DomainConversion(source.domain, domain)
            self.X = get_columns(row_indices, conversion.attributes, n_rows,
                                 is_sparse=conversion.sparse_X,
                                 variables=domain.attributes)
            if self.X.ndim == 1:
                self.X = self.X.reshape(-1, len(self.domain.attributes))

            self.Y = get_columns(row_indices, conversion.class_vars, n_rows,
                                 is_sparse=conversion.sparse_Y,
                                 variables=domain.class_vars)

            dtype = np.float64
            if any(isinstance(var, StringVariable) for var in domain.metas):
                dtype = np.object
            self.metas = get_columns(row_indices, conversion.metas,
                                     n_rows, dtype,
                                     is_sparse=conversion.sparse_metas,
                                     variables=domain.metas)
            if self.metas.ndim == 1:
                self.metas = self.metas.reshape(-1, len(self.domain.metas))
            if source.has_weights():
                self.W = source.W[row_indices]
            else:
                self.W = np.empty((n_rows, 0))
            self.name = getattr(source, 'name', '')
            if hasattr(source, 'ids'):
                self.ids = source.ids[row_indices]
            else:
                cls._init_ids(self)
            self.attributes = getattr(source, 'attributes', {})
            _thread_local.conversion_cache[(id(domain), id(source))] = \
                self, (weakref.ref(domain), weakref.ref(source))
            return self
        finally:
            if new_cache:
                _thread_local.conversion_cache = None

    def transform(self, domain):
        """
        Construct a table with a different domain.

        The new table keeps the row ids and other information. If the table
        is a subclass of :obj:`Table`, the resulting table will be of the same
        type.

        In a typical scenario, an existing table is augmented with a new
        column by ::

            domain = Domain(old_domain.attributes + [new_attribute],
                            old_domain.class_vars,
                            old_domain.metas)
            table = data.transform(domain)
            table[:, new_attribute] = new_column

        Args:
            domain (Domain): new domain

        Returns:
            A new table
        """
        return type(self).from_table(domain, self)

    @classmethod
    def from_table_rows(cls, source, row_indices):
        """
        Construct a new table by selecting rows from the source table.

        :param source: an existing table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = source.domain
        self.X = source.X[row_indices]
        if self.X.ndim == 1:
            self.X = self.X.reshape(-1, len(self.domain.attributes))
        self.Y = source._Y[row_indices]
        self.metas = source.metas[row_indices]
        if self.metas.ndim == 1:
            self.metas = self.metas.reshape(-1, len(self.domain.metas))
        self.W = source.W[row_indices]
        self.name = getattr(source, 'name', '')
        self.ids = np.array(source.ids[row_indices])
        self.attributes = getattr(source, 'attributes', {})
        return self

    @classmethod
    def from_numpy(cls, domain, X, Y=None, metas=None, W=None,
                   attributes=None, ids=None):
        """
        Construct a table from numpy arrays with the given domain. The number
        of variables in the domain must match the number of columns in the
        corresponding arrays. All arrays must have the same number of rows.
        Arrays may be of different numpy types, and may be dense or sparse.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param X: array with attribute values
        :type X: np.array
        :param Y: array with class values
        :type Y: np.array
        :param metas: array with meta attributes
        :type metas: np.array
        :param W: array with weights
        :type W: np.array
        :return:
        """
        X, Y, W = _check_arrays(X, Y, W, dtype='float64')
        metas, = _check_arrays(metas, dtype=object, shape_1=X.shape[0])
        ids, = _check_arrays(ids, dtype=int, shape_1=X.shape[0])

        if Y is not None and Y.ndim == 1:
            Y = Y.reshape(Y.shape[0], 1)
        if domain is None:
            domain = Domain.from_numpy(X, Y, metas)

        if Y is None:
            if sp.issparse(X):
                Y = np.empty((X.shape[0], 0), dtype=np.float64)
            else:
                Y = X[:, len(domain.attributes):]
                X = X[:, :len(domain.attributes)]
        if metas is None:
            metas = np.empty((X.shape[0], 0), object)
        if W is None or W.size == 0:
            W = np.empty((X.shape[0], 0))
        else:
            W = W.reshape(W.size)

        if X.shape[1] != len(domain.attributes):
            raise ValueError(
                "Invalid number of variable columns ({} != {})".format(
                    X.shape[1], len(domain.attributes))
            )
        if Y.shape[1] != len(domain.class_vars):
            raise ValueError(
                "Invalid number of class columns ({} != {})".format(
                    Y.shape[1], len(domain.class_vars))
            )
        if metas.shape[1] != len(domain.metas):
            raise ValueError(
                "Invalid number of meta attribute columns ({} != {})".format(
                    metas.shape[1], len(domain.metas))
            )
        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:
            raise ValueError(
                "Parts of data contain different numbers of rows.")

        self = cls()
        self.domain = domain
        self.X = X
        self.Y = Y
        self.metas = metas
        self.W = W
        self.n_rows = self.X.shape[0]
        if ids is None:
            cls._init_ids(self)
        else:
            self.ids = ids
        self.attributes = {} if attributes is None else attributes
        return self

    @classmethod
    def from_list(cls, domain, rows, weights=None):
        if weights is not None and len(rows) != len(weights):
            raise ValueError("mismatching number of instances and weights")
        self = cls.from_domain(domain, len(rows), weights is not None)
        attrs, classes = domain.attributes, domain.class_vars
        metas = domain.metas
        nattrs, ncls = len(domain.attributes), len(domain.class_vars)
        for i, row in enumerate(rows):
            if isinstance(row, Instance):
                row = row.list
            for j, (var, val) in enumerate(zip(attrs, row)):
                self.X[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):
                self._Y[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):
                self.metas[i, j] = var.to_val(val)
        if weights is not None:
            self.W = np.array(weights)
        self.attributes = {}
        return self

    @classmethod
    def _init_ids(cls, obj):
        with cls._next_instance_lock:
            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))
            cls._next_instance_id += obj.X.shape[0]

    @classmethod
    def new_id(cls):
        with cls._next_instance_lock:
            id = cls._next_instance_id
            cls._next_instance_id += 1
            return id

    def save(self, filename):
        """
        Save a data table to a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        """
        ext = os.path.splitext(filename)[1]
        from Orange.data.io import FileFormat
        writer = FileFormat.writers.get(ext)
        if not writer:
            desc = FileFormat.names.get(ext)
            if desc:
                raise IOError(
                    "Writing of {}s is not supported".format(desc.lower()))
            else:
                raise IOError("Unknown file name extension.")
        writer.write_file(filename, self)

    @classmethod
    def from_file(cls, filename, sheet=None):
        """
        Read a data table from a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        :param sheet: Sheet in a file (optional)
        :type sheet: str
        :return: a new data table
        :rtype: Orange.data.Table
        """
        from Orange.data.io import FileFormat

        absolute_filename = FileFormat.locate(filename, dataset_dirs)
        reader = FileFormat.get_reader(absolute_filename)
        reader.select_sheet(sheet)
        data = reader.read()

        # Readers return plain table. Make sure to cast it to appropriate
        # (subclass) type
        if cls != data.__class__:
            data = cls(data)

        # no need to call _init_ids as fuctions from .io already
        # construct a table with .ids

        data.__file__ = absolute_filename
        return data

    @classmethod
    def from_url(cls, url):
        from Orange.data.io import UrlReader
        reader = UrlReader(url)
        data = reader.read()
        if cls != data.__class__:
            data = cls(data)
        return data

    # Helper function for __setitem__:
    # Set the row of table data matrices
    # noinspection PyProtectedMember
    def _set_row(self, example, row):
        domain = self.domain
        if isinstance(example, Instance):
            if example.domain == domain:
                if isinstance(example, RowInstance):
                    self.X[row] = example._x
                    self._Y[row] = example._y
                else:
                    self.X[row] = example._x
                    self._Y[row] = example._y
                self.metas[row] = example._metas
                return

            self.X[row], self._Y[row], self.metas[row] = \
                self.domain.convert(example)
            try:
                self.ids[row] = example.id
            except:
                with type(self)._next_instance_lock:
                    self.ids[row] = type(self)._next_instance_id
                    type(self)._next_instance_id += 1

        else:
            self.X[row] = [var.to_val(val)
                           for var, val in zip(domain.attributes, example)]
            self._Y[row] = [var.to_val(val)
                            for var, val in
                            zip(domain.class_vars,
                                example[len(domain.attributes):])]
            self.metas[row] = np.array([var.Unknown for var in domain.metas],
                                       dtype=object)

    def _check_all_dense(self):
        return all(x in (Storage.DENSE, Storage.MISSING)
                   for x in (self.X_density(), self.Y_density(),
                             self.metas_density()))

    def __getitem__(self, key):
        if isinstance(key, Integral):
            return RowInstance(self, key)
        if not isinstance(key, tuple):
            return self.from_table_rows(self, key)

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")

        row_idx, col_idx = key
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, (str, Integral, Variable)):
                col_idx = self.domain.index(col_idx)
                var = self.domain[col_idx]
                if 0 <= col_idx < len(self.domain.attributes):
                    val = self.X[row_idx, col_idx]
                elif col_idx >= len(self.domain.attributes):
                    val = self._Y[row_idx,
                                  col_idx - len(self.domain.attributes)]
                else:
                    val = self.metas[row_idx, -1 - col_idx]
                if isinstance(col_idx, DiscreteVariable) and var is not col_idx:
                    val = col_idx.get_mapper_from(var)(val)
                return Value(var, val)
            else:
                row_idx = [row_idx]

        # multiple rows OR single row but multiple columns:
        # construct a new table
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if attributes is not None:
            n_attrs = len(self.domain.attributes)
            r_attrs = [attributes[i]
                       for i, col in enumerate(col_indices)
                       if 0 <= col < n_attrs]
            r_classes = [attributes[i]
                         for i, col in enumerate(col_indices)
                         if col >= n_attrs]
            r_metas = [attributes[i]
                       for i, col in enumerate(col_indices) if col < 0]
            domain = Domain(r_attrs, r_classes, r_metas)
        else:
            domain = self.domain
        return self.from_table(domain, self, row_idx)

    def __setitem__(self, key, value):
        if not isinstance(key, tuple):
            if isinstance(value, Real):
                self.X[key, :] = value
                return
            self._set_row(value, key)
            return

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")
        row_idx, col_idx = key

        # single row
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, slice):
                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))
            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):
                col_idx = list(col_idx)
            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):
                if isinstance(value, (Sequence, np.ndarray)):
                    values = value
                elif isinstance(value, Iterable):
                    values = list(value)
                else:
                    raise TypeError("Setting multiple values requires a "
                                    "sequence or numpy array")
                if len(values) != len(col_idx):
                    raise ValueError("Invalid number of values")
            else:
                col_idx, values = [col_idx], [value]
            if isinstance(col_idx, DiscreteVariable) \
                    and self.domain[col_idx] != col_idx:
                values = self.domain[col_idx].get_mapper_from(col_idx)(values)
            for val, col_idx in zip(values, col_idx):
                if not isinstance(val, Integral):
                    val = self.domain[col_idx].to_val(val)
                if not isinstance(col_idx, Integral):
                    col_idx = self.domain.index(col_idx)
                if col_idx >= 0:
                    if col_idx < self.X.shape[1]:
                        self.X[row_idx, col_idx] = val
                    else:
                        self._Y[row_idx, col_idx - self.X.shape[1]] = val
                else:
                    self.metas[row_idx, -1 - col_idx] = val

        # multiple rows, multiple columns
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if col_indices is ...:
            col_indices = range(len(self.domain))
        n_attrs = self.X.shape[1]
        if isinstance(value, str):
            if not attributes:
                attributes = self.domain.attributes
            for var, col in zip(attributes, col_indices):
                if 0 <= col < n_attrs:
                    self.X[row_idx, col] = var.to_val(value)
                elif col >= n_attrs:
                    self._Y[row_idx, col - n_attrs] = var.to_val(value)
                else:
                    self.metas[row_idx, -1 - col] = var.to_val(value)
        else:
            attr_cols = np.fromiter(
                (col for col in col_indices if 0 <= col < n_attrs), int)
            class_cols = np.fromiter(
                (col - n_attrs for col in col_indices if col >= n_attrs), int)
            meta_cols = np.fromiter(
                (-1 - col for col in col_indices if col < 0), int)
            if value is None:
                value = Unknown

            if not isinstance(value, (Real, np.ndarray)) and \
                    (len(attr_cols) or len(class_cols)):
                raise TypeError(
                    "Ordinary attributes can only have primitive values")
            if len(attr_cols):
                self.X[row_idx, attr_cols] = value
            if len(class_cols):
                self._Y[row_idx, class_cols] = value
            if len(meta_cols):
                self.metas[row_idx, meta_cols] = value

    def __len__(self):
        return self.X.shape[0]

    def __str__(self):
        return "[" + ",\n ".join(str(ex) for ex in self) + "]"

    def __repr__(self):
        head = 5
        if self.is_sparse():
            head = min(self.X.shape[0], head)
        s = "[" + ",\n ".join(repr(ex) for ex in self[:head])
        if len(self) > head:
            s += ",\n ..."
        s += "\n]"
        return s

    @classmethod
    def concatenate(cls, tables, axis=0):
        """Concatenate tables into a new table"""
        def vstack(arrs):
            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)

        def merge1d(arrs):
            arrs = list(arrs)
            ydims = {arr.ndim for arr in arrs}
            if ydims == {1}:
                return np.hstack(arrs)
            else:
                return vstack([
                    arr if arr.ndim == 2 else np.atleast_2d(arr).T
                    for arr in arrs
                ])

        def collect(attr):
            return [getattr(arr, attr) for arr in tables]

        if axis == 1:
            raise ValueError("concatenate no longer supports axis 1")
        if not tables:
            raise ValueError('need at least one table to concatenate')
        if len(tables) == 1:
            return tables[0].copy()
        domain = tables[0].domain
        if any(table.domain != domain for table in tables):
            raise ValueError('concatenated tables must have the same domain')

        conc = cls.from_numpy(
            domain,
            vstack(collect("X")),
            merge1d(collect("Y")),
            vstack(collect("metas")),
            merge1d(collect("W"))
        )
        conc.ids = np.hstack([t.ids for t in tables])
        names = [table.name for table in tables if table.name != "untitled"]
        if names:
            conc.name = names[0]
        # TODO: Add attributes = {} to __init__
        conc.attributes = getattr(conc, "attributes", {})
        for table in reversed(tables):
            conc.attributes.update(table.attributes)
        return conc

    def is_view(self):
        """
        Return `True` if all arrays represent a view referring to another table
        """
        return ((not self.X.shape[-1] or self.X.base is not None) and
                (not self._Y.shape[-1] or self._Y.base is not None) and
                (not self.metas.shape[-1] or self.metas.base is not None) and
                (not self._weights.shape[-1] or self.W.base is not None))

    def is_copy(self):
        """
        Return `True` if the table owns its data
        """
        return ((not self.X.shape[-1] or self.X.base is None) and
                (self._Y.base is None) and
                (self.metas.base is None) and
                (self.W.base is None))

    def is_sparse(self):
        """
        Return `True` if the table stores data in sparse format
        """
        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])

    def ensure_copy(self):
        """
        Ensure that the table owns its data; copy arrays when necessary.
        """
        def is_view(x):
            # Sparse matrices don't have views like numpy arrays. Since indexing on
            # them creates copies in constructor we can skip this check here.
            return not sp.issparse(x) and x.base is not None

        if is_view(self.X):
            self.X = self.X.copy()
        if is_view(self._Y):
            self._Y = self._Y.copy()
        if is_view(self.metas):
            self.metas = self.metas.copy()
        if is_view(self.W):
            self.W = self.W.copy()

    def copy(self):
        """
        Return a copy of the table
        """
        t = self.__class__(self)
        t.ensure_copy()
        return t

    @staticmethod
    def __determine_density(data):
        if data is None:
            return Storage.Missing
        if data is not None and sp.issparse(data):
            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE
        else:
            return Storage.DENSE

    def X_density(self):
        if not hasattr(self, "_X_density"):
            self._X_density = self.__determine_density(self.X)
        return self._X_density

    def Y_density(self):
        if not hasattr(self, "_Y_density"):
            self._Y_density = self.__determine_density(self._Y)
        return self._Y_density

    def metas_density(self):
        if not hasattr(self, "_metas_density"):
            self._metas_density = self.__determine_density(self.metas)
        return self._metas_density

    def set_weights(self, weight=1):
        """
        Set weights of data instances; create a vector of weights if necessary.
        """
        if not self.W.shape[-1]:
            self.W = np.empty(len(self))
        self.W[:] = weight

    def has_weights(self):
        """Return `True` if the data instances are weighed. """
        return self.W.shape[-1] != 0

    def total_weight(self):
        """
        Return the total weight of instances in the table, or their number if
        they are unweighted.
        """
        if self.W.shape[-1]:
            return sum(self.W)
        return len(self)

    def has_missing(self):
        """Return `True` if there are any missing attribute or class values."""
        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X
        return missing_x or bn.anynan(self._Y)

    def has_missing_attribute(self):
        """Return `True` if there are any missing attribute values."""
        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X

    def has_missing_class(self):
        """Return `True` if there are any missing class values."""
        return bn.anynan(self._Y)

    def get_nan_frequency_attribute(self):
        if self.X.size == 0:
            return 0
        return np.isnan(self.X).sum() / self.X.size

    def get_nan_frequency_class(self):
        if self.Y.size == 0:
            return 0
        return np.isnan(self._Y).sum() / self._Y.size

    def checksum(self, include_metas=True):
        # TODO: zlib.adler32 does not work for numpy arrays with dtype object
        # (after pickling and unpickling such arrays, checksum changes)
        # Why, and should we fix it or remove it?
        """Return a checksum over X, Y, metas and W."""
        cs = zlib.adler32(np.ascontiguousarray(self.X))
        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)
        if include_metas:
            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)
        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)
        return cs

    def shuffle(self):
        """Randomly shuffle the rows of the table."""
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be shuffled")
        ind = np.arange(self.X.shape[0])
        np.random.shuffle(ind)
        self.X = self.X[ind]
        self._Y = self._Y[ind]
        self.metas = self.metas[ind]
        self.W = self.W[ind]

    def get_column_view(self, index):
        """
        Return a vector - as a view, not a copy - with a column of the table,
        and a bool flag telling whether this column is sparse. Note that
        vertical slicing of sparse matrices is inefficient.

        :param index: the index of the column
        :type index: int, str or Orange.data.Variable
        :return: (one-dimensional numpy array, sparse)
        """

        def rx(M):
            if sp.issparse(M):
                return np.asarray(M.todense())[:, 0], True
            else:
                return M, False

        if isinstance(index, Integral):
            col_index = index
        else:
            col_index = self.domain.index(index)
        if col_index >= 0:
            if col_index < self.X.shape[1]:
                col = rx(self.X[:, col_index])
            else:
                col = rx(self._Y[:, col_index - self.X.shape[1]])
        else:
            col = rx(self.metas[:, -1 - col_index])

        if isinstance(index, DiscreteVariable) \
                and index.values != self.domain[col_index].values:
            col = index.get_mapper_from(self.domain[col_index])(col[0]), col[1]
            col[0].flags.writeable = False
        return col

    def _filter_is_defined(self, columns=None, negate=False):
        # structure of function is obvious; pylint: disable=too-many-branches
        def _sp_anynan(a):
            return a.indptr[1:] != a[-1:] + a.shape[1]

        if columns is None:
            if sp.issparse(self.X):
                remove = _sp_anynan(self.X)
            else:
                remove = bn.anynan(self.X, axis=1)
            if sp.issparse(self._Y):
                remove += _sp_anynan(self._Y)
            else:
                remove += bn.anynan(self._Y, axis=1)
            if sp.issparse(self.metas):
                remove += _sp_anynan(self._metas)
            else:
                for i, var in enumerate(self.domain.metas):
                    col = self.metas[:, i].flatten()
                    if var.is_primitive():
                        remove += np.isnan(col.astype(float))
                    else:
                        remove += ~col.astype(bool)
        else:
            remove = np.zeros(len(self), dtype=bool)
            for column in columns:
                col, sparse = self.get_column_view(column)
                if sparse:
                    remove += col == 0
                elif self.domain[column].is_primitive():
                    remove += bn.anynan([col.astype(float)], axis=0)
                else:
                    remove += col.astype(bool)
        retain = remove if negate else np.logical_not(remove)
        return self.from_table_rows(self, retain)

    def _filter_has_class(self, negate=False):
        if sp.issparse(self._Y):
            if negate:
                retain = (self._Y.indptr[1:] !=
                          self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                retain = (self._Y.indptr[1:] ==
                          self._Y.indptr[-1:] + self._Y.shape[1])
        else:
            retain = bn.anynan(self._Y, axis=1)
            if not negate:
                retain = np.logical_not(retain)
        return self.from_table_rows(self, retain)

    def _filter_same_value(self, column, value, negate=False):
        if not isinstance(value, Real):
            value = self.domain[column].to_val(value)
        sel = self.get_column_view(column)[0] == value
        if negate:
            sel = np.logical_not(sel)
        return self.from_table_rows(self, sel)

    def _filter_values(self, filter):
        selection = self._values_filter_to_indicator(filter)
        return self.from_table(self.domain, self, selection)

    def _values_filter_to_indicator(self, filter):
        """Return selection of rows matching the filter conditions

        Handles conjunction/disjunction and negate modifiers

        Parameters
        ----------
        filter: Values object containing the conditions

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import Values

        if isinstance(filter, Values):
            conditions = filter.conditions
            conjunction = filter.conjunction
        else:
            conditions = [filter]
            conjunction = True
        if conjunction:
            sel = np.ones(len(self), dtype=bool)
        else:
            sel = np.zeros(len(self), dtype=bool)

        for f in conditions:
            selection = self._filter_to_indicator(f)

            if conjunction:
                sel *= selection
            else:
                sel += selection

        if filter.negate:
            sel = ~sel
        return sel

    def _filter_to_indicator(self, filter):
        """Return selection of rows that match the condition.

        Parameters
        ----------
        filter: ValueFilter describing the condition

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import (
            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,
            FilterStringList, IsDefined, Values
        )
        if isinstance(filter, Values):
            return self._values_filter_to_indicator(filter)

        def get_col_indices():
            cols = chain(self.domain.variables, self.domain.metas)
            if isinstance(filter, IsDefined):
                if filter.columns is not None:
                    return list(filter.columns)
                else:
                    return list(cols)

            if filter.column is not None:
                return [filter.column]

            if isinstance(filter, FilterDiscrete):
                raise ValueError("Discrete filter can't be applied across rows")
            if isinstance(filter, FilterContinuous):
                return [col for col in cols if col.is_continuous]
            if isinstance(filter,
                          (FilterString, FilterStringList, FilterRegex)):
                return [col for col in cols if col.is_string]
            raise TypeError("Invalid filter")

        def col_filter(col_idx):
            col = self.get_column_view(col_idx)[0]
            if isinstance(filter, IsDefined):
                if self.domain[col_idx].is_primitive():
                    return ~np.isnan(col.astype(float))
                else:
                    return col.astype(np.bool)
            if isinstance(filter, FilterDiscrete):
                return self._discrete_filter_to_indicator(filter, col)
            if isinstance(filter, FilterContinuous):
                return self._continuous_filter_to_indicator(filter, col)
            if isinstance(filter, FilterString):
                return self._string_filter_to_indicator(filter, col)
            if isinstance(filter, FilterStringList):
                if not filter.case_sensitive:
                    col = np.char.lower(np.array(col, dtype=str))
                    vals = [val.lower() for val in filter.values]
                else:
                    vals = filter.values
                return reduce(operator.add, (col == val for val in vals))
            if isinstance(filter, FilterRegex):
                return np.vectorize(filter)(col)
            raise TypeError("Invalid filter")

        col_indices = get_col_indices()
        if len(col_indices) == 1:
            sel = col_filter(col_indices[0])
        else:
            sel = np.ones(len(self), dtype=bool)
            for col_idx in col_indices:
                sel *= col_filter(col_idx)

        if isinstance(filter, IsDefined) and filter.negate:
            sel = ~sel
        return sel

    def _discrete_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given discrete filter.

        Parameters
        ----------
        filter: FilterDiscrete
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.values is None:  # <- is defined filter
            col = col.astype(float)
            return ~np.isnan(col)

        sel = np.zeros(len(self), dtype=bool)
        for val in filter.values:
            if not isinstance(val, Real):
                val = self.domain[filter.column].to_val(val)
            sel += (col == val)
        return sel

    def _continuous_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given continuous filter.

        Parameters
        ----------
        filter: FilterContinuous
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            col = col.astype(float)
            return ~np.isnan(col)

        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)

    def _string_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given string filter.

        Parameters
        ----------
        filter: FilterString
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            return col.astype(bool)

        col = col.astype(str)
        fmin = filter.min or ""
        fmax = filter.max or ""

        if not filter.case_sensitive:
            # convert all to lower case
            col = np.char.lower(col)
            fmin = fmin.lower()
            fmax = fmax.lower()

        if filter.oper == filter.Contains:
            return np.fromiter((fmin in e for e in col),
                               dtype=bool)
        if filter.oper == filter.StartsWith:
            return np.fromiter((e.startswith(fmin) for e in col),
                               dtype=bool)
        if filter.oper == filter.EndsWith:
            return np.fromiter((e.endswith(fmin) for e in col),
                               dtype=bool)

        return self._range_filter_to_indicator(filter, col, fmin, fmax)

    @staticmethod
    def _range_filter_to_indicator(filter, col, fmin, fmax):
        with np.errstate(invalid="ignore"):   # nan's are properly discarded
            if filter.oper == filter.Equal:
                return col == fmin
            if filter.oper == filter.NotEqual:
                return col != fmin
            if filter.oper == filter.Less:
                return col < fmin
            if filter.oper == filter.LessEqual:
                return col <= fmin
            if filter.oper == filter.Greater:
                return col > fmin
            if filter.oper == filter.GreaterEqual:
                return col >= fmin
            if filter.oper == filter.Between:
                return (col >= fmin) * (col <= fmax)
            if filter.oper == filter.Outside:
                return (col < fmin) + (col > fmax)

            raise TypeError("Invalid operator")

    def _compute_basic_stats(self, columns=None,
                             include_metas=False, compute_variance=False):
        if compute_variance:
            raise NotImplementedError("computation of variance is "
                                      "not implemented yet")
        W = self.W if self.has_weights() else None
        rr = []
        stats = []
        if not columns:
            if self.domain.attributes:
                rr.append(fast_stats(self.X, W))
            if self.domain.class_vars:
                rr.append(fast_stats(self._Y, W))
            if include_metas and self.domain.metas:
                rr.append(fast_stats(self.metas, W))
            if len(rr):
                stats = np.vstack(tuple(rr))
        else:
            nattrs = len(self.domain.attributes)
            for column in columns:
                c = self.domain.index(column)
                if 0 <= c < nattrs:
                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])
                elif c >= nattrs:
                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])
                else:
                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])
                stats.append(S[0])
        return stats

    def _compute_distributions(self, columns=None):
        if columns is None:
            columns = range(len(self.domain.variables))
        else:
            columns = [self.domain.index(var) for var in columns]

        distributions = []
        if sp.issparse(self.X):
            self.X = self.X.tocsc()

        W = self.W.ravel() if self.has_weights() else None

        for col in columns:
            variable = self.domain[col]

            # Select the correct data column from X, Y or metas
            if 0 <= col < self.X.shape[1]:
                x = self.X[:, col]
            elif col < 0:
                x = self.metas[:, col * (-1) - 1]
                if np.issubdtype(x.dtype, np.dtype(object)):
                    x = x.astype(float)
            else:
                x = self._Y[:, col - self.X.shape[1]]

            if variable.is_discrete:
                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)
            elif not x.shape[0]:
                dist, unknowns = np.zeros((2, 0)), 0
            else:
                if W is not None:
                    if sp.issparse(x):
                        arg_sort = np.argsort(x.data)
                        ranks = x.indices[arg_sort]
                        vals = np.vstack((x.data[arg_sort], W[ranks]))
                    else:
                        ranks = np.argsort(x)
                        vals = np.vstack((x[ranks], W[ranks]))
                else:
                    x_values = x.data if sp.issparse(x) else x
                    vals = np.ones((2, x_values.shape[0]))
                    vals[0, :] = x_values
                    vals[0, :].sort()

                dist = np.array(_valuecount.valuecount(vals))
                # If sparse, then 0s will not be counted with `valuecount`, so
                # we have to add them to the result manually.
                if sp.issparse(x) and sparse_has_implicit_zeros(x):
                    if W is not None:
                        zero_weights = sparse_implicit_zero_weights(x, W).sum()
                    else:
                        zero_weights = sparse_count_implicit_zeros(x)
                    zero_vec = [0, zero_weights]
                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)
                # Since `countnans` assumes vector shape to be (1, n) and `x`
                # shape is (n, 1), we pass the transpose
                unknowns = countnans(x.T, W)
            distributions.append((dist, unknowns))

        return distributions

    def _compute_contingency(self, col_vars=None, row_var=None):
        n_atts = self.X.shape[1]

        if col_vars is None:
            col_vars = range(len(self.domain.variables))
        else:
            col_vars = [self.domain.index(var) for var in col_vars]
        if row_var is None:
            row_var = self.domain.class_var
            if row_var is None:
                raise ValueError("No row variable")

        row_desc = self.domain[row_var]
        if not row_desc.is_discrete:
            raise TypeError("Row variable must be discrete")
        row_indi = self.domain.index(row_var)
        n_rows = len(row_desc.values)
        if 0 <= row_indi < n_atts:
            row_data = self.X[:, row_indi]
        elif row_indi < 0:
            row_data = self.metas[:, -1 - row_indi]
        else:
            row_data = self._Y[:, row_indi - n_atts]

        W = self.W if self.has_weights() else None

        col_desc = [self.domain[var] for var in col_vars]
        col_indi = [self.domain.index(var) for var in col_vars]

        if any(not (var.is_discrete or var.is_continuous)
               for var in col_desc):
            raise ValueError("contingency can be computed only for discrete "
                             "and continuous values")

        # when we select a column in sparse matrix it is still two dimensional
        # and sparse - since it is just a column we can afford to transform
        # it to dense and make it 1D
        if issparse(row_data):
            row_data = row_data.toarray().ravel()
        if row_data.dtype.kind != "f": #meta attributes can be stored as type object
            row_data = row_data.astype(float)

        contingencies = [None] * len(col_desc)
        for arr, f_cond, f_ind in (
                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),
                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),
                (self.metas, lambda i: i < 0, lambda i: -1 - i)):

            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]

            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]
            disc_vars = [v for v in vars if v[2].is_discrete]
            if disc_vars:
                if sp.issparse(arr):
                    max_vals = max(len(v[2].values) for v in disc_vars)
                    disc_indi = {i for _, i, _ in disc_vars}
                    mask = [i in disc_indi for i in range(arr.shape[1])]
                    conts, nans_cols, nans_rows, nans = contingency(
                        arr, row_data, max_vals - 1, n_rows - 1, W, mask)
                    for col_i, arr_i, var in disc_vars:
                        n_vals = len(var.values)
                        contingencies[col_i] = (
                            conts[arr_i][:, :n_vals], nans_cols[arr_i],
                            nans_rows[arr_i], nans[arr_i])
                else:
                    for col_i, arr_i, var in disc_vars:
                        contingencies[col_i] = contingency(
                            arr[:, arr_i].astype(float),
                            row_data, len(var.values) - 1, n_rows - 1, W)

            cont_vars = [v for v in vars if v[2].is_continuous]
            if cont_vars:
                W_ = None
                if W is not None:
                    W_ = W.astype(dtype=np.float64)
                if sp.issparse(arr):
                    arr = sp.csc_matrix(arr)

                for col_i, arr_i, _ in cont_vars:
                    if sp.issparse(arr):
                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        W_ = None if W_ is None else W_[rows]
                        classes_ = row_data[rows]
                    else:
                        col_data, W_, classes_ = arr[:, arr_i], W_, row_data

                    col_data = col_data.astype(dtype=np.float64)
                    contingencies[col_i] = _contingency.contingency_floatarray(
                        col_data, classes_, n_rows, W_)

        return contingencies

    @classmethod
    def transpose(cls, table, feature_names_column="",
                  meta_attr_name="Feature name", feature_name="Feature"):
        """
        Transpose the table.

        :param table: Table - table to transpose
        :param feature_names_column: str - name of (String) meta attribute to
            use for feature names
        :param meta_attr_name: str - name of new meta attribute into which
            feature names are mapped
        :param feature_name: str - default feature name prefix
        :return: Table - transposed table
        """

        self = cls()
        n_cols, self.n_rows = table.X.shape
        old_domain = table.attributes.get("old_domain")

        # attributes
        # - classes and metas to attributes of attributes
        # - arbitrary meta column to feature names
        self.X = table.X.T
        if feature_names_column:
            names = [str(row[feature_names_column]) for row in table]
            names = get_unique_names_duplicates(names)
            attributes = [ContinuousVariable(name) for name in names]
        else:
            places = int(np.ceil(np.log10(n_cols))) if n_cols else 1
            attributes = [ContinuousVariable(f"{feature_name} {i:0{places}}")
                          for i in range(1, n_cols + 1)]
        if old_domain is not None and feature_names_column:
            for i, _ in enumerate(attributes):
                if attributes[i].name in old_domain:
                    var = old_domain[attributes[i].name]
                    attr = ContinuousVariable(var.name) if var.is_continuous \
                        else DiscreteVariable(var.name, var.values)
                    attr.attributes = var.attributes.copy()
                    attributes[i] = attr

        def set_attributes_of_attributes(_vars, _table):
            for i, variable in enumerate(_vars):
                if variable.name == feature_names_column:
                    continue
                for j, row in enumerate(_table):
                    value = variable.repr_val(row) if np.isscalar(row) \
                        else row[i] if isinstance(row[i], str) \
                        else variable.repr_val(row[i])

                    if value not in MISSING_VALUES:
                        attributes[j].attributes[variable.name] = value

        set_attributes_of_attributes(table.domain.class_vars, table.Y)
        set_attributes_of_attributes(table.domain.metas, table.metas)

        # weights
        self.W = np.empty((self.n_rows, 0))

        def get_table_from_attributes_of_attributes(_vars, _dtype=float):
            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)
            for i, _attr in enumerate(table.domain.attributes):
                for j, _var in enumerate(_vars):
                    val = str(_attr.attributes.get(_var.name, ""))
                    if not _var.is_string:
                        val = np.nan if val in MISSING_VALUES else \
                            _var.values.index(val) if \
                                _var.is_discrete else float(val)
                    T[i, j] = val
            return T

        # class_vars - attributes of attributes to class - from old domain
        class_vars = []
        if old_domain is not None:
            class_vars = old_domain.class_vars
        self.Y = get_table_from_attributes_of_attributes(class_vars)

        # metas
        # - feature names and attributes of attributes to metas
        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []
        if meta_attr_name not in [m.name for m in table.domain.metas] and \
                table.domain.attributes:
            self.metas = np.array([[a.name] for a in table.domain.attributes],
                                  dtype=object)
            metas.append(StringVariable(meta_attr_name))

        names = chain.from_iterable(list(attr.attributes)
                                    for attr in table.domain.attributes)
        names = sorted(set(names) - {var.name for var in class_vars})

        def guessed_var(i, var_name):
            orig_vals = M[:, i]
            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)
            values, variable = Orange.data.io.sanitize_variable(
                val_map, vals, orig_vals, var_type, {}, name=var_name)
            M[:, i] = values
            return variable

        _metas = [StringVariable(n) for n in names]
        if old_domain is not None:
            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]
        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)
        if old_domain is None:
            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]
        if _metas:
            self.metas = np.hstack((self.metas, M))
            metas.extend(_metas)

        self.domain = Domain(attributes, class_vars, metas)
        cls._init_ids(self)
        self.attributes = table.attributes.copy()
        self.attributes["old_domain"] = table.domain
        return self

    def to_sparse(self, sparse_attributes=True, sparse_class=False,
                  sparse_metas=False):
        def sparsify(features):
            for f in features:
                f.sparse = True

        new_domain = self.domain.copy()

        if sparse_attributes:
            sparsify(new_domain.attributes)
        if sparse_class:
            sparsify(new_domain.class_vars)
        if sparse_metas:
            sparsify(new_domain.metas)
        return self.transform(new_domain)

    def to_dense(self, dense_attributes=True, dense_class=True,
                 dense_metas=True):
        def densify(features):
            for f in features:
                f.sparse = False

        new_domain = self.domain.copy()

        if dense_attributes:
            densify(new_domain.attributes)
        if dense_class:
            densify(new_domain.class_vars)
        if dense_metas:
            densify(new_domain.metas)
        t = self.transform(new_domain)
        t.ids = self.ids    # preserve indices
        return t


def _check_arrays(*arrays, dtype=None, shape_1=None):
    checked = []
    if not len(arrays):
        return checked

    def ninstances(array):
        if hasattr(array, "shape"):
            return array.shape[0]
        else:
            return len(array) if array is not None else 0

    if shape_1 is None:
        shape_1 = ninstances(arrays[0])

    for array in arrays:
        if array is None:
            checked.append(array)
            continue

        if ninstances(array) != shape_1:
            raise ValueError("Leading dimension mismatch (%d != %d)"
                             % (ninstances(array), shape_1))

        if sp.issparse(array):
            array.data = np.asarray(array.data)
            has_inf = _check_inf(array.data)
        else:
            if dtype is not None:
                array = np.asarray(array, dtype=dtype)
            else:
                array = np.asarray(array)
            has_inf = _check_inf(array)

        if has_inf:
            array[np.isinf(array)] = np.nan
            warnings.warn("Array contains infinity.", RuntimeWarning)
        checked.append(array)

    return checked


def _check_inf(array):
    return array.dtype.char in np.typecodes['AllFloat'] and \
           np.isinf(array.data).any()


def _subarray(arr, rows, cols):
    rows = _optimize_indices(rows, arr.shape[0])
    cols = _optimize_indices(cols, arr.shape[1])
    return arr[_rxc_ix(rows, cols)]


def _optimize_indices(indices, maxlen):
    """
    Convert integer indices to slice if possible. It only converts increasing
    integer ranges with positive steps and valid starts and ends.
    Only convert valid ends so that invalid ranges will still raise
    an exception.

    Allows numpy to reuse the data array, because it defaults to copying
    if given indices.

    Parameters
    ----------
    indices : 1D sequence, slice or Ellipsis
    """
    if isinstance(indices, slice):
        return indices

    if indices is ...:
        return slice(None, None, 1)

    if len(indices) >= 1:
        indices = np.asarray(indices)
        if indices.dtype != np.bool:
            begin = indices[0]
            end = indices[-1]
            steps = np.diff(indices) if len(indices) > 1 else np.array([1])
            step = steps[0]

            # continuous ranges with constant step and valid start and stop index can be slices
            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:
                return slice(begin, end + step, step)

    return indices


def _rxc_ix(rows, cols):
    """
    Construct an index object to index the `rows` x `cols` cross product.

    Rows and columns can be a 1d bool or int sequence, or a slice.
    The later is a convenience and is interpreted the same
    as `slice(None, None, -1)`

    Parameters
    ----------
    rows : 1D sequence, slice
        Row indices.
    cols : 1D sequence, slice
        Column indices.

    See Also
    --------
    numpy.ix_

    Examples
    --------
    >>> import numpy as np
    >>> a = np.arange(10).reshape(2, 5)
    >>> a[_rxc_ix([0, 1], [3, 4])]
    array([[3, 4],
           [8, 9]])
    >>> a[_rxc_ix([False, True], slice(None, None, 1))]
    array([[5, 6, 7, 8, 9]])

    """
    isslice = (isinstance(rows, slice), isinstance(cols, slice))
    if isslice == (True, True):
        return rows, cols
    elif isslice == (True, False):
        return rows, np.asarray(np.ix_(cols), int).ravel()
    elif isslice == (False, True):
        return np.asarray(np.ix_(rows), int).ravel(), cols
    else:
        r, c = np.ix_(rows, cols)
        return np.asarray(r, int), np.asarray(c, int)


def assure_domain_conversion_sparsity(target, source):
    """
    Assure that the table obeys the domain conversion's suggestions about sparsity.

    Args:
        target (Table): the target table.
        source (Table): the source table.

    Returns:
        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion
            for transformation from source to the target domain.
    """
    conversion = DomainConversion(source.domain, target.domain)
    match_density = [assure_array_dense, assure_array_sparse]
    target.X = match_density[conversion.sparse_X](target.X)
    target.Y = match_density[conversion.sparse_Y](target.Y)
    target.metas = match_density[conversion.sparse_metas](target.metas)
    return target

```
--- 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:** `Table.from_numpy` Fails to Properly Handle Non-CSR/CSC Sparse Matrices

**Description:**
When creating a `Table` from a non-CSR/CSC sparse matrix using `Table.from_numpy`, the resulting table does not maintain the expected sparse matrix format. Specifically, passing COO, LIL, or BSR sparse matrices does not convert them to CSR as intended, leading to inconsistencies in how the data is stored and accessed.

**Example Code:**
```python
import numpy as np
import scipy.sparse as sp
from Orange.data import Domain, ContinuousVariable, Table

domain = Domain([ContinuousVariable(c) for c in "abc"])
x = np.arange(12).reshape(4, 3)

# Attempting to create a table from a COO matrix
t = Table.from_numpy(domain, sp.coo_matrix(x))
print(sp.isspmatrix_csr(t.X))  # Expected: True
```

**Expected Behavior:**
When a non-CSR/CSC sparse matrix (like COO, LIL, or BSR) is passed to `Table.from_numpy`, it should automatically convert the matrix to CSR format. The check `sp.isspmatrix_csr(t.X)` should return `True`, ensuring consistent sparse matrix representation within the `Table`.

**Actual Behavior:**
The table retains the original sparse matrix format (e.g., COO), causing `sp.isspmatrix_csr(t.X)` to return `False`. This leads to potential issues in downstream processing where CSR format is assumed.

[/ISSUE]
{
    "TestTableInit.test_empty_table": "PASSED",
    "TestTableInit.test_from_numpy": "PASSED",
    "TestTableInit.test_from_numpy_sparse": "PASSED",
    "TestTableInit.test_invalid_call_with_kwargs": "PASSED",
    "TestTableInit.test_warnings": "PASSED",
    "TestTableFilters.test_is_defined": "PASSED",
    "TestTableFilters.test_row_filter_continuous": "PASSED",
    "TestTableFilters.test_row_filter_no_discrete": "PASSED",
    "TestTableFilters.test_row_filter_string": "PASSED",
    "TestTableFilters.test_row_filters_is_defined": "PASSED",
    "TestTableFilters.test_row_stringlist": "PASSED",
    "TestTableFilters.test_row_stringregex": "PASSED"
}
diff --git a/Orange/data/table.py b/Orange/data/table.py
index 47f7668e5..f9deb6f98 100644
--- a/Orange/data/table.py
+++ b/Orange/data/table.py
@@ -1751,6 +1751,8 @@ def _check_arrays(*arrays, dtype=None, shape_1=None):
                              % (ninstances(array), shape_1))
 
         if sp.issparse(array):
+            if not (sp.isspmatrix_csr(array) or sp.isspmatrix_csc(array)):
+                array = array.tocsr()
             array.data = np.asarray(array.data)
             has_inf = _check_inf(array.data)
         else:

{"Orange/data/table.py": "import operator\nimport os\nimport threading\nimport warnings\nimport weakref\nimport zlib\nfrom collections import Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock\n\nimport bottleneck as bn\nimport numpy as np\nfrom Orange.misc.collections import frozendict\nfrom Orange.util import OrangeDeprecationWarning\nfrom scipy import sparse as sp\nfrom scipy.sparse import issparse, csc_matrix\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES,\n    DomainConversion)\nfrom Orange.data.util import SharedComputeValue, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse, get_unique_names_duplicates\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\nclass _ThreadLocal(threading.local):\n    def __init__(self):\n        super().__init__()\n        # Domain conversion cache used in Table.from_table. It is defined\n        # here instead of as a class variable of a Table so that caching also works\n        # with descendants of Table.\n        self.conversion_cache = None\n\n\n_thread_local = _ThreadLocal()\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(Sequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    domain = Domain([])\n    X = _Y = metas = W = np.zeros((0, 0))\n    X.setflags(write=False)\n    ids = np.zeros(0)\n    ids.setflags(write=False)\n    attributes = frozendict()\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        if sp.issparse(value):\n            value = value.toarray()\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        def warn_deprecated(method):\n            warnings.warn(\"Direct calls to Table's constructor are deprecated \"\n                          \"and will be removed. Replace this call with \"\n                          f\"Table.{method}\", OrangeDeprecationWarning,\n                          stacklevel=3)\n\n        if not args:\n            if not kwargs:\n                return super().__new__(cls)\n            else:\n                raise TypeError(\"Table() must not be called directly\")\n\n        if isinstance(args[0], str):\n            if len(args) > 1:\n                raise TypeError(\"Table(name: str) expects just one argument\")\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0], **kwargs)\n\n        elif isinstance(args[0], Table):\n            if len(args) > 1:\n                raise TypeError(\"Table(table: Table) expects just one argument\")\n            return cls.from_table(args[0].domain, args[0], **kwargs)\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                warn_deprecated(\"from_domain\")\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                warn_deprecated(\"from_table\")\n                return cls.from_table(domain, *args, **kwargs)\n            elif isinstance(args[0], list):\n                warn_deprecated(\"from_list\")\n                return cls.from_list(domain, *args, **kwargs)\n        else:\n            warnings.warn(\"Omitting domain in a call to Table(X, Y, metas), is \"\n                          \"deprecated and will be removed. \"\n                          \"Call Table.from_numpy(None, X, Y, metas) instead.\",\n                          OrangeDeprecationWarning, stacklevel=2)\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        def valid_refs(weakrefs):\n            for r in weakrefs:\n                if r() is None:\n                    return False\n            return True\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64,\n                        is_sparse=False, variables=[]):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize arrays & set `match_density` for columns\n            # F-order enables faster writing to the array while accessing and\n            # matrix operations work with same speed (e.g. dot)\n            a = None if is_sparse else np.zeros(\n                (n_rows, len(src_cols)), order=\"F\", dtype=dtype)\n            data = []\n            sp_col = []\n            sp_row = []\n            match_density = (\n                assure_column_sparse if is_sparse else assure_column_dense\n            )\n\n            # converting to csc before instead of each column is faster\n            # do not convert if not required\n            if any([isinstance(x, int) for x in src_cols]):\n                X = csc_matrix(source.X) if is_sparse else source.X\n                Y = csc_matrix(source._Y) if is_sparse else source._Y\n\n            shared_cache = _thread_local.conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    col_array = match_density(\n                        np.full((n_rows, 1), variables[i].Unknown)\n                    )\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        shared, weakrefs = shared_cache.get(\n                            (id(col.compute_shared), id(source)),\n                            (None, None)\n                        )\n                        if shared is None or not valid_refs(weakrefs):\n                            shared, _ = shared_cache[(id(col.compute_shared), id(source))] = \\\n                                col.compute_shared(source), \\\n                                (weakref.ref(col.compute_shared), weakref.ref(source))\n\n                        if row_indices is not ...:\n                            col_array = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            col_array = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            col_array = match_density(col(source)[row_indices])\n                        else:\n                            col_array = match_density(col(source))\n                elif col < 0:\n                    col_array = match_density(\n                        source.metas[row_indices, -1 - col]\n                    )\n                elif col < n_src_attrs:\n                    col_array = match_density(X[row_indices, col])\n                else:\n                    col_array = match_density(\n                        Y[row_indices, col - n_src_attrs]\n                    )\n\n                if is_sparse:\n                    # col_array should be coo matrix\n                    data.append(col_array.data)\n                    sp_col.append(np.full(len(col_array.data), i))\n                    sp_row.append(col_array.indices)  # row indices should be same\n                else:\n                    a[:, i] = col_array\n\n            if is_sparse:\n                # creating csr directly would need plenty of manual work which\n                # would probably slow down the process - conversion coo to csr\n                # is fast\n                a = sp.coo_matrix(\n                    (np.hstack(data), (np.hstack(sp_row), np.hstack(sp_col))),\n                    shape=(n_rows, len(src_cols)),\n                    dtype=dtype\n                )\n                a = a.tocsr()\n\n            return a\n\n        new_cache = _thread_local.conversion_cache is None\n        try:\n            if new_cache:\n                _thread_local.conversion_cache = {}\n            else:\n                cached, weakrefs = \\\n                    _thread_local.conversion_cache.get((id(domain), id(source)), (None, None))\n                if cached and valid_refs(weakrefs):\n                    return cached\n            if domain is source.domain:\n                table = cls.from_table_rows(source, row_indices)\n                # assure resulting domain is the instance passed on input\n                table.domain = domain\n                # since sparse flags are not considered when checking for\n                # domain equality, fix manually.\n                table = assure_domain_conversion_sparsity(table, source)\n                return table\n\n            if isinstance(row_indices, slice):\n                start, stop, stride = row_indices.indices(source.X.shape[0])\n                n_rows = (stop - start) // stride\n                if n_rows < 0:\n                    n_rows = 0\n            elif row_indices is ...:\n                n_rows = len(source)\n            else:\n                n_rows = len(row_indices)\n\n            self = cls()\n            self.domain = domain\n            conversion = DomainConversion(source.domain, domain)\n            self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                 is_sparse=conversion.sparse_X,\n                                 variables=domain.attributes)\n            if self.X.ndim == 1:\n                self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n            self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                 is_sparse=conversion.sparse_Y,\n                                 variables=domain.class_vars)\n\n            dtype = np.float64\n            if any(isinstance(var, StringVariable) for var in domain.metas):\n                dtype = np.object\n            self.metas = get_columns(row_indices, conversion.metas,\n                                     n_rows, dtype,\n                                     is_sparse=conversion.sparse_metas,\n                                     variables=domain.metas)\n            if self.metas.ndim == 1:\n                self.metas = self.metas.reshape(-1, len(self.domain.metas))\n            if source.has_weights():\n                self.W = source.W[row_indices]\n            else:\n                self.W = np.empty((n_rows, 0))\n            self.name = getattr(source, 'name', '')\n            if hasattr(source, 'ids'):\n                self.ids = source.ids[row_indices]\n            else:\n                cls._init_ids(self)\n            self.attributes = getattr(source, 'attributes', {})\n            _thread_local.conversion_cache[(id(domain), id(source))] = \\\n                self, (weakref.ref(domain), weakref.ref(source))\n            return self\n        finally:\n            if new_cache:\n                _thread_local.conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None,\n                   attributes=None, ids=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object, shape_1=X.shape[0])\n        ids, = _check_arrays(ids, dtype=int, shape_1=X.shape[0])\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        if ids is None:\n            cls._init_ids(self)\n        else:\n            self.ids = ids\n        self.attributes = {} if attributes is None else attributes\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    val = self.X[row_idx, col_idx]\n                elif col_idx >= len(self.domain.attributes):\n                    val = self._Y[row_idx,\n                                  col_idx - len(self.domain.attributes)]\n                else:\n                    val = self.metas[row_idx, -1 - col_idx]\n                if isinstance(col_idx, DiscreteVariable) and var is not col_idx:\n                    val = col_idx.get_mapper_from(var)(val)\n                return Value(var, val)\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            if isinstance(col_idx, DiscreteVariable) \\\n                    and self.domain[col_idx] != col_idx:\n                values = self.domain[col_idx].get_mapper_from(col_idx)(values)\n            for val, col_idx in zip(values, col_idx):\n                if not isinstance(val, Integral):\n                    val = self.domain[col_idx].to_val(val)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = val\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = val\n                else:\n                    self.metas[row_idx, -1 - col_idx] = val\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    @classmethod\n    def concatenate(cls, tables, axis=0):\n        \"\"\"Concatenate tables into a new table\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if axis == 1:\n            raise ValueError(\"concatenate no longer supports axis 1\")\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        domain = tables[0].domain\n        if any(table.domain != domain for table in tables):\n            raise ValueError('concatenated tables must have the same domain')\n\n        conc = cls.from_numpy(\n            domain,\n            vstack(collect(\"X\")),\n            merge1d(collect(\"Y\")),\n            vstack(collect(\"metas\")),\n            merge1d(collect(\"W\"))\n        )\n        conc.ids = np.hstack([t.ids for t in tables])\n        names = [table.name for table in tables if table.name != \"untitled\"]\n        if names:\n            conc.name = names[0]\n        # TODO: Add attributes = {} to __init__\n        conc.attributes = getattr(conc, \"attributes\", {})\n        for table in reversed(tables):\n            conc.attributes.update(table.attributes)\n        return conc\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if isinstance(index, Integral):\n            col_index = index\n        else:\n            col_index = self.domain.index(index)\n        if col_index >= 0:\n            if col_index < self.X.shape[1]:\n                col = rx(self.X[:, col_index])\n            else:\n                col = rx(self._Y[:, col_index - self.X.shape[1]])\n        else:\n            col = rx(self.metas[:, -1 - col_index])\n\n        if isinstance(index, DiscreteVariable) \\\n                and index.values != self.domain[col_index].values:\n            col = index.get_mapper_from(self.domain[col_index])(col[0]), col[1]\n            col[0].flags.writeable = False\n        return col\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        # structure of function is obvious; pylint: disable=too-many-branches\n        def _sp_anynan(a):\n            return a.indptr[1:] != a[-1:] + a.shape[1]\n\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = _sp_anynan(self.X)\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove += _sp_anynan(self._Y)\n            else:\n                remove += bn.anynan(self._Y, axis=1)\n            if sp.issparse(self.metas):\n                remove += _sp_anynan(self._metas)\n            else:\n                for i, var in enumerate(self.domain.metas):\n                    col = self.metas[:, i].flatten()\n                    if var.is_primitive():\n                        remove += np.isnan(col.astype(float))\n                    else:\n                        remove += ~col.astype(bool)\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove += col == 0\n                elif self.domain[column].is_primitive():\n                    remove += bn.anynan([col.astype(float)], axis=0)\n                else:\n                    remove += col.astype(bool)\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, IsDefined, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        def get_col_indices():\n            cols = chain(self.domain.variables, self.domain.metas)\n            if isinstance(filter, IsDefined):\n                if filter.columns is not None:\n                    return list(filter.columns)\n                else:\n                    return list(cols)\n\n            if filter.column is not None:\n                return [filter.column]\n\n            if isinstance(filter, FilterDiscrete):\n                raise ValueError(\"Discrete filter can't be applied across rows\")\n            if isinstance(filter, FilterContinuous):\n                return [col for col in cols if col.is_continuous]\n            if isinstance(filter,\n                          (FilterString, FilterStringList, FilterRegex)):\n                return [col for col in cols if col.is_string]\n            raise TypeError(\"Invalid filter\")\n\n        def col_filter(col_idx):\n            col = self.get_column_view(col_idx)[0]\n            if isinstance(filter, IsDefined):\n                if self.domain[col_idx].is_primitive():\n                    return ~np.isnan(col.astype(float))\n                else:\n                    return col.astype(np.bool)\n            if isinstance(filter, FilterDiscrete):\n                return self._discrete_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterContinuous):\n                return self._continuous_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterString):\n                return self._string_filter_to_indicator(filter, col)\n            if isinstance(filter, FilterStringList):\n                if not filter.case_sensitive:\n                    col = np.char.lower(np.array(col, dtype=str))\n                    vals = [val.lower() for val in filter.values]\n                else:\n                    vals = filter.values\n                return reduce(operator.add, (col == val for val in vals))\n            if isinstance(filter, FilterRegex):\n                return np.vectorize(filter)(col)\n            raise TypeError(\"Invalid filter\")\n\n        col_indices = get_col_indices()\n        if len(col_indices) == 1:\n            sel = col_filter(col_indices[0])\n        else:\n            sel = np.ones(len(self), dtype=bool)\n            for col_idx in col_indices:\n                sel *= col_filter(col_idx)\n\n        if isinstance(filter, IsDefined) and filter.negate:\n            sel = ~sel\n        return sel\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        with np.errstate(invalid=\"ignore\"):   # nan's are properly discarded\n            if filter.oper == filter.Equal:\n                return col == fmin\n            if filter.oper == filter.NotEqual:\n                return col != fmin\n            if filter.oper == filter.Less:\n                return col < fmin\n            if filter.oper == filter.LessEqual:\n                return col <= fmin\n            if filter.oper == filter.Greater:\n                return col > fmin\n            if filter.oper == filter.GreaterEqual:\n                return col >= fmin\n            if filter.oper == filter.Between:\n                return (col >= fmin) * (col <= fmax)\n            if filter.oper == filter.Outside:\n                return (col < fmin) + (col > fmax)\n\n            raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        # when we select a column in sparse matrix it is still two dimensional\n        # and sparse - since it is just a column we can afford to transform\n        # it to dense and make it 1D\n        if issparse(row_data):\n            row_data = row_data.toarray().ravel()\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans_cols, nans_rows, nans = contingency(\n                        arr, row_data, max_vals - 1, n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (\n                            conts[arr_i][:, :n_vals], nans_cols[arr_i],\n                            nans_rows[arr_i], nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n                W_ = None\n                if W is not None:\n                    W_ = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W_ is None else W_[rows]\n                        classes_ = row_data[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W_, row_data\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    contingencies[col_i] = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n\n        return contingencies\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\",\n                  meta_attr_name=\"Feature name\", feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :param feature_name: str - default feature name prefix\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        if feature_names_column:\n            names = [str(row[feature_names_column]) for row in table]\n            names = get_unique_names_duplicates(names)\n            attributes = [ContinuousVariable(name) for name in names]\n        else:\n            places = int(np.ceil(np.log10(n_cols))) if n_cols else 1\n            attributes = [ContinuousVariable(f\"{feature_name} {i:0{places}}\")\n                          for i in range(1, n_cols + 1)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None, shape_1=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    if shape_1 is None:\n        shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            array[np.isinf(array)] = np.nan\n            warnings.warn(\"Array contains infinity.\", RuntimeWarning)\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = DomainConversion(source.domain, target.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\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:** `Table.from_numpy` Fails to Properly Handle Non-CSR/CSC Sparse Matrices

**Description:**
When creating a `Table` from a non-CSR/CSC sparse matrix using `Table.from_numpy`, the resulting table does not maintain the expected sparse matrix format. Specifically, passing COO, LIL, or BSR sparse matrices does not convert them to CSR as intended, leading to inconsistencies in how the data is stored and accessed.

**Example Code:**
```python
import numpy as np
import scipy.sparse as sp
from Orange.data import Domain, ContinuousVariable, Table

domain = Domain([ContinuousVariable(c) for c in "abc"])
x = np.arange(12).reshape(4, 3)

# Attempting to create a table from a COO matrix
t = Table.from_numpy(domain, sp.coo_matrix(x))
print(sp.isspmatrix_csr(t.X))  # Expected: True
```

**Expected Behavior:**
When a non-CSR/CSC sparse matrix (like COO, LIL, or BSR) is passed to `Table.from_numpy`, it should automatically convert the matrix to CSR format. The check `sp.isspmatrix_csr(t.X)` should return `True`, ensuring consistent sparse matrix representation within the `Table`.

**Actual Behavior:**
The table retains the original sparse matrix format (e.g., COO), causing `sp.isspmatrix_csr(t.X)` to return `False`. This leads to potential issues in downstream processing where CSR format is assumed.

[/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/data/table.py
import operator
import os
import threading
import warnings
import weakref
import zlib
from collections import Iterable, Sequence, Sized
from functools import reduce
from itertools import chain
from numbers import Real, Integral
from threading import Lock

import bottleneck as bn
import numpy as np
from Orange.misc.collections import frozendict
from Orange.util import OrangeDeprecationWarning
from scipy import sparse as sp
from scipy.sparse import issparse, csc_matrix

import Orange.data  # import for io.py
from Orange.data import (
    _contingency, _valuecount,
    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,
    ContinuousVariable, DiscreteVariable, MISSING_VALUES,
    DomainConversion)
from Orange.data.util import SharedComputeValue, \
    assure_array_dense, assure_array_sparse, \
    assure_column_dense, assure_column_sparse, get_unique_names_duplicates
from Orange.statistics.util import bincount, countnans, contingency, \
    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \
    sparse_implicit_zero_weights

__all__ = ["dataset_dirs", "get_sample_datasets_dir", "RowInstance", "Table"]


def get_sample_datasets_dir():
    orange_data_table = os.path.dirname(__file__)
    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')
    return os.path.realpath(dataset_dir)


dataset_dirs = ['', get_sample_datasets_dir()]


class _ThreadLocal(threading.local):
    def __init__(self):
        super().__init__()
        # Domain conversion cache used in Table.from_table. It is defined
        # here instead of as a class variable of a Table so that caching also works
        # with descendants of Table.
        self.conversion_cache = None


_thread_local = _ThreadLocal()


class DomainTransformationError(Exception):
    pass


class RowInstance(Instance):
    sparse_x = None
    sparse_y = None
    sparse_metas = None
    _weight = None

    def __init__(self, table, row_index):
        """
        Construct a data instance representing the given row of the table.
        """
        self.table = table
        self._domain = table.domain
        self.row_index = row_index
        self.id = table.ids[row_index]
        self._x = table.X[row_index]
        if sp.issparse(self._x):
            self.sparse_x = sp.csr_matrix(self._x)
            self._x = np.asarray(self._x.todense())[0]
        self._y = table._Y[row_index]
        if sp.issparse(self._y):
            self.sparse_y = sp.csr_matrix(self._y)
            self._y = np.asarray(self._y.todense())[0]
        self._metas = table.metas[row_index]
        if sp.issparse(self._metas):
            self.sparse_metas = sp.csr_matrix(self._metas)
            self._metas = np.asarray(self._metas.todense())[0]

    @property
    def weight(self):
        if not self.table.has_weights():
            return 1
        return self.table.W[self.row_index]

    @weight.setter
    def weight(self, weight):
        if not self.table.has_weights():
            self.table.set_weights()
        self.table.W[self.row_index] = weight

    def set_class(self, value):
        self._check_single_class()
        if not isinstance(value, Real):
            value = self.table.domain.class_var.to_val(value)
        self._y[0] = value
        if self.sparse_y:
            self.table._Y[self.row_index, 0] = value

    def __setitem__(self, key, value):
        if not isinstance(key, Integral):
            key = self._domain.index(key)
        if isinstance(value, str):
            var = self._domain[key]
            value = var.to_val(value)
        if key >= 0:
            if not isinstance(value, Real):
                raise TypeError("Expected primitive value, got '%s'" %
                                type(value).__name__)
            if key < len(self._x):
                self._x[key] = value
                if self.sparse_x is not None:
                    self.table.X[self.row_index, key] = value
            else:
                self._y[key - len(self._x)] = value
                if self.sparse_y is not None:
                    self.table._Y[self.row_index, key - len(self._x)] = value
        else:
            self._metas[-1 - key] = value
            if self.sparse_metas:
                self.table.metas[self.row_index, -1 - key] = value

    def _str(self, limit):
        def sp_values(matrix, variables):
            if not sp.issparse(matrix):
                if matrix.ndim == 1:
                    matrix = matrix[:, np.newaxis]
                return Instance.str_values(matrix[row], variables, limit)

            row_entries, idx = [], 0
            while idx < len(variables):
                # Make sure to stop printing variables if we limit the output
                if limit and len(row_entries) >= 5:
                    break

                var = variables[idx]
                if var.is_discrete or matrix[row, idx]:
                    row_entries.append("%s=%s" % (var.name, var.str_val(matrix[row, idx])))

                idx += 1

            s = ", ".join(row_entries)

            if limit and idx < len(variables):
                s += ", ..."

            return s

        table = self.table
        domain = table.domain
        row = self.row_index
        s = "[" + sp_values(table.X, domain.attributes)
        if domain.class_vars:
            s += " | " + sp_values(table.Y, domain.class_vars)
        s += "]"
        if self._domain.metas:
            s += " {" + sp_values(table.metas, domain.metas) + "}"
        return s

    def __str__(self):
        return self._str(False)

    def __repr__(self):
        return self._str(True)


class Columns:
    def __init__(self, domain):
        for v in chain(domain.variables, domain.metas):
            setattr(self, v.name.replace(" ", "_"), v)


# noinspection PyPep8Naming
class Table(Sequence, Storage):
    __file__ = None
    name = "untitled"

    domain = Domain([])
    X = _Y = metas = W = np.zeros((0, 0))
    X.setflags(write=False)
    ids = np.zeros(0)
    ids.setflags(write=False)
    attributes = frozendict()

    @property
    def columns(self):
        """
        A class whose attributes contain attribute descriptors for columns.
        For a table `table`, setting `c = table.columns` will allow accessing
        the table's variables with, for instance `c.gender`, `c.age` ets.
        Spaces are replaced with underscores.
        """
        return Columns(self.domain)

    _next_instance_id = 0
    _next_instance_lock = Lock()

    @property
    def Y(self):
        if self._Y.shape[1] == 1:
            return self._Y[:, 0]
        return self._Y

    @Y.setter
    def Y(self, value):
        if len(value.shape) == 1:
            value = value[:, None]
        if sp.issparse(value) and len(self) != value.shape[0]:
            value = value.T
        if sp.issparse(value):
            value = value.toarray()
        self._Y = value

    def __new__(cls, *args, **kwargs):
        def warn_deprecated(method):
            warnings.warn("Direct calls to Table's constructor are deprecated "
                          "and will be removed. Replace this call with "
                          f"Table.{method}", OrangeDeprecationWarning,
                          stacklevel=3)

        if not args:
            if not kwargs:
                return super().__new__(cls)
            else:
                raise TypeError("Table() must not be called directly")

        if isinstance(args[0], str):
            if len(args) > 1:
                raise TypeError("Table(name: str) expects just one argument")
            if args[0].startswith('https://') or args[0].startswith('http://'):
                return cls.from_url(args[0], **kwargs)
            else:
                return cls.from_file(args[0], **kwargs)

        elif isinstance(args[0], Table):
            if len(args) > 1:
                raise TypeError("Table(table: Table) expects just one argument")
            return cls.from_table(args[0].domain, args[0], **kwargs)
        elif isinstance(args[0], Domain):
            domain, args = args[0], args[1:]
            if not args:
                warn_deprecated("from_domain")
                return cls.from_domain(domain, **kwargs)
            if isinstance(args[0], Table):
                warn_deprecated("from_table")
                return cls.from_table(domain, *args, **kwargs)
            elif isinstance(args[0], list):
                warn_deprecated("from_list")
                return cls.from_list(domain, *args, **kwargs)
        else:
            warnings.warn("Omitting domain in a call to Table(X, Y, metas), is "
                          "deprecated and will be removed. "
                          "Call Table.from_numpy(None, X, Y, metas) instead.",
                          OrangeDeprecationWarning, stacklevel=2)
            domain = None

        return cls.from_numpy(domain, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        # So subclasses can expect to call super without breakage; noop
        pass

    @classmethod
    def from_domain(cls, domain, n_rows=0, weights=False):
        """
        Construct a new `Table` with the given number of rows for the given
        domain. The optional vector of weights is initialized to 1's.

        :param domain: domain for the `Table`
        :type domain: Orange.data.Domain
        :param n_rows: number of rows in the new table
        :type n_rows: int
        :param weights: indicates whether to construct a vector of weights
        :type weights: bool
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = domain
        self.n_rows = n_rows
        self.X = np.zeros((n_rows, len(domain.attributes)))
        self.Y = np.zeros((n_rows, len(domain.class_vars)))
        if weights:
            self.W = np.ones(n_rows)
        else:
            self.W = np.empty((n_rows, 0))
        self.metas = np.empty((n_rows, len(self.domain.metas)), object)
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_table(cls, domain, source, row_indices=...):
        """
        Create a new table from selected columns and/or rows of an existing
        one. The columns are chosen using a domain. The domain may also include
        variables that do not appear in the source table; they are computed
        from source variables if possible.

        The resulting data may be a view or a copy of the existing data.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param source: the source table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """

        def valid_refs(weakrefs):
            for r in weakrefs:
                if r() is None:
                    return False
            return True

        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64,
                        is_sparse=False, variables=[]):
            if not len(src_cols):
                if is_sparse:
                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)
                else:
                    return np.zeros((n_rows, 0), dtype=source.X.dtype)

            # match density for subarrays
            match_density = assure_array_sparse if is_sparse else assure_array_dense
            n_src_attrs = len(source.domain.attributes)
            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(source.X, row_indices, src_cols))
            if all(isinstance(x, Integral) and x < 0 for x in src_cols):
                arr = match_density(_subarray(source.metas, row_indices,
                                              [-1 - x for x in src_cols]))
                if arr.dtype != dtype:
                    return arr.astype(dtype)
                return arr
            if all(isinstance(x, Integral) and x >= n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(
                    source._Y, row_indices,
                    [x - n_src_attrs for x in src_cols]))

            # initialize arrays & set `match_density` for columns
            # F-order enables faster writing to the array while accessing and
            # matrix operations work with same speed (e.g. dot)
            a = None if is_sparse else np.zeros(
                (n_rows, len(src_cols)), order="F", dtype=dtype)
            data = []
            sp_col = []
            sp_row = []
            match_density = (
                assure_column_sparse if is_sparse else assure_column_dense
            )

            # converting to csc before instead of each column is faster
            # do not convert if not required
            if any([isinstance(x, int) for x in src_cols]):
                X = csc_matrix(source.X) if is_sparse else source.X
                Y = csc_matrix(source._Y) if is_sparse else source._Y

            shared_cache = _thread_local.conversion_cache
            for i, col in enumerate(src_cols):
                if col is None:
                    col_array = match_density(
                        np.full((n_rows, 1), variables[i].Unknown)
                    )
                elif not isinstance(col, Integral):
                    if isinstance(col, SharedComputeValue):
                        shared, weakrefs = shared_cache.get(
                            (id(col.compute_shared), id(source)),
                            (None, None)
                        )
                        if shared is None or not valid_refs(weakrefs):
                            shared, _ = shared_cache[(id(col.compute_shared), id(source))] = \
                                col.compute_shared(source), \
                                (weakref.ref(col.compute_shared), weakref.ref(source))

                        if row_indices is not ...:
                            col_array = match_density(
                                col(source, shared_data=shared)[row_indices])
                        else:
                            col_array = match_density(
                                col(source, shared_data=shared))
                    else:
                        if row_indices is not ...:
                            col_array = match_density(col(source)[row_indices])
                        else:
                            col_array = match_density(col(source))
                elif col < 0:
                    col_array = match_density(
                        source.metas[row_indices, -1 - col]
                    )
                elif col < n_src_attrs:
                    col_array = match_density(X[row_indices, col])
                else:
                    col_array = match_density(
                        Y[row_indices, col - n_src_attrs]
                    )

                if is_sparse:
                    # col_array should be coo matrix
                    data.append(col_array.data)
                    sp_col.append(np.full(len(col_array.data), i))
                    sp_row.append(col_array.indices)  # row indices should be same
                else:
                    a[:, i] = col_array

            if is_sparse:
                # creating csr directly would need plenty of manual work which
                # would probably slow down the process - conversion coo to csr
                # is fast
                a = sp.coo_matrix(
                    (np.hstack(data), (np.hstack(sp_row), np.hstack(sp_col))),
                    shape=(n_rows, len(src_cols)),
                    dtype=dtype
                )
                a = a.tocsr()

            return a

        new_cache = _thread_local.conversion_cache is None
        try:
            if new_cache:
                _thread_local.conversion_cache = {}
            else:
                cached, weakrefs = \
                    _thread_local.conversion_cache.get((id(domain), id(source)), (None, None))
                if cached and valid_refs(weakrefs):
                    return cached
            if domain is source.domain:
                table = cls.from_table_rows(source, row_indices)
                # assure resulting domain is the instance passed on input
                table.domain = domain
                # since sparse flags are not considered when checking for
                # domain equality, fix manually.
                table = assure_domain_conversion_sparsity(table, source)
                return table

            if isinstance(row_indices, slice):
                start, stop, stride = row_indices.indices(source.X.shape[0])
                n_rows = (stop - start) // stride
                if n_rows < 0:
                    n_rows = 0
            elif row_indices is ...:
                n_rows = len(source)
            else:
                n_rows = len(row_indices)

            self = cls()
            self.domain = domain
            conversion = DomainConversion(source.domain, domain)
            self.X = get_columns(row_indices, conversion.attributes, n_rows,
                                 is_sparse=conversion.sparse_X,
                                 variables=domain.attributes)
            if self.X.ndim == 1:
                self.X = self.X.reshape(-1, len(self.domain.attributes))

            self.Y = get_columns(row_indices, conversion.class_vars, n_rows,
                                 is_sparse=conversion.sparse_Y,
                                 variables=domain.class_vars)

            dtype = np.float64
            if any(isinstance(var, StringVariable) for var in domain.metas):
                dtype = np.object
            self.metas = get_columns(row_indices, conversion.metas,
                                     n_rows, dtype,
                                     is_sparse=conversion.sparse_metas,
                                     variables=domain.metas)
            if self.metas.ndim == 1:
                self.metas = self.metas.reshape(-1, len(self.domain.metas))
            if source.has_weights():
                self.W = source.W[row_indices]
            else:
                self.W = np.empty((n_rows, 0))
            self.name = getattr(source, 'name', '')
            if hasattr(source, 'ids'):
                self.ids = source.ids[row_indices]
            else:
                cls._init_ids(self)
            self.attributes = getattr(source, 'attributes', {})
            _thread_local.conversion_cache[(id(domain), id(source))] = \
                self, (weakref.ref(domain), weakref.ref(source))
            return self
        finally:
            if new_cache:
                _thread_local.conversion_cache = None

    def transform(self, domain):
        """
        Construct a table with a different domain.

        The new table keeps the row ids and other information. If the table
        is a subclass of :obj:`Table`, the resulting table will be of the same
        type.

        In a typical scenario, an existing table is augmented with a new
        column by ::

            domain = Domain(old_domain.attributes + [new_attribute],
                            old_domain.class_vars,
                            old_domain.metas)
            table = data.transform(domain)
            table[:, new_attribute] = new_column

        Args:
            domain (Domain): new domain

        Returns:
            A new table
        """
        return type(self).from_table(domain, self)

    @classmethod
    def from_table_rows(cls, source, row_indices):
        """
        Construct a new table by selecting rows from the source table.

        :param source: an existing table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = source.domain
        self.X = source.X[row_indices]
        if self.X.ndim == 1:
            self.X = self.X.reshape(-1, len(self.domain.attributes))
        self.Y = source._Y[row_indices]
        self.metas = source.metas[row_indices]
        if self.metas.ndim == 1:
            self.metas = self.metas.reshape(-1, len(self.domain.metas))
        self.W = source.W[row_indices]
        self.name = getattr(source, 'name', '')
        self.ids = np.array(source.ids[row_indices])
        self.attributes = getattr(source, 'attributes', {})
        return self

    @classmethod
    def from_numpy(cls, domain, X, Y=None, metas=None, W=None,
                   attributes=None, ids=None):
        """
        Construct a table from numpy arrays with the given domain. The number
        of variables in the domain must match the number of columns in the
        corresponding arrays. All arrays must have the same number of rows.
        Arrays may be of different numpy types, and may be dense or sparse.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param X: array with attribute values
        :type X: np.array
        :param Y: array with class values
        :type Y: np.array
        :param metas: array with meta attributes
        :type metas: np.array
        :param W: array with weights
        :type W: np.array
        :return:
        """
        X, Y, W = _check_arrays(X, Y, W, dtype='float64')
        metas, = _check_arrays(metas, dtype=object, shape_1=X.shape[0])
        ids, = _check_arrays(ids, dtype=int, shape_1=X.shape[0])

        if Y is not None and Y.ndim == 1:
            Y = Y.reshape(Y.shape[0], 1)
        if domain is None:
            domain = Domain.from_numpy(X, Y, metas)

        if Y is None:
            if sp.issparse(X):
                Y = np.empty((X.shape[0], 0), dtype=np.float64)
            else:
                Y = X[:, len(domain.attributes):]
                X = X[:, :len(domain.attributes)]
        if metas is None:
            metas = np.empty((X.shape[0], 0), object)
        if W is None or W.size == 0:
            W = np.empty((X.shape[0], 0))
        else:
            W = W.reshape(W.size)

        if X.shape[1] != len(domain.attributes):
            raise ValueError(
                "Invalid number of variable columns ({} != {})".format(
                    X.shape[1], len(domain.attributes))
            )
        if Y.shape[1] != len(domain.class_vars):
            raise ValueError(
                "Invalid number of class columns ({} != {})".format(
                    Y.shape[1], len(domain.class_vars))
            )
        if metas.shape[1] != len(domain.metas):
            raise ValueError(
                "Invalid number of meta attribute columns ({} != {})".format(
                    metas.shape[1], len(domain.metas))
            )
        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:
            raise ValueError(
                "Parts of data contain different numbers of rows.")

        self = cls()
        self.domain = domain
        self.X = X
        self.Y = Y
        self.metas = metas
        self.W = W
        self.n_rows = self.X.shape[0]
        if ids is None:
            cls._init_ids(self)
        else:
            self.ids = ids
        self.attributes = {} if attributes is None else attributes
        return self

    @classmethod
    def from_list(cls, domain, rows, weights=None):
        if weights is not None and len(rows) != len(weights):
            raise ValueError("mismatching number of instances and weights")
        self = cls.from_domain(domain, len(rows), weights is not None)
        attrs, classes = domain.attributes, domain.class_vars
        metas = domain.metas
        nattrs, ncls = len(domain.attributes), len(domain.class_vars)
        for i, row in enumerate(rows):
            if isinstance(row, Instance):
                row = row.list
            for j, (var, val) in enumerate(zip(attrs, row)):
                self.X[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):
                self._Y[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):
                self.metas[i, j] = var.to_val(val)
        if weights is not None:
            self.W = np.array(weights)
        self.attributes = {}
        return self

    @classmethod
    def _init_ids(cls, obj):
        with cls._next_instance_lock:
            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))
            cls._next_instance_id += obj.X.shape[0]

    @classmethod
    def new_id(cls):
        with cls._next_instance_lock:
            id = cls._next_instance_id
            cls._next_instance_id += 1
            return id

    def save(self, filename):
        """
        Save a data table to a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        """
        ext = os.path.splitext(filename)[1]
        from Orange.data.io import FileFormat
        writer = FileFormat.writers.get(ext)
        if not writer:
            desc = FileFormat.names.get(ext)
            if desc:
                raise IOError(
                    "Writing of {}s is not supported".format(desc.lower()))
            else:
                raise IOError("Unknown file name extension.")
        writer.write_file(filename, self)

    @classmethod
    def from_file(cls, filename, sheet=None):
        """
        Read a data table from a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        :param sheet: Sheet in a file (optional)
        :type sheet: str
        :return: a new data table
        :rtype: Orange.data.Table
        """
        from Orange.data.io import FileFormat

        absolute_filename = FileFormat.locate(filename, dataset_dirs)
        reader = FileFormat.get_reader(absolute_filename)
        reader.select_sheet(sheet)
        data = reader.read()

        # Readers return plain table. Make sure to cast it to appropriate
        # (subclass) type
        if cls != data.__class__:
            data = cls(data)

        # no need to call _init_ids as fuctions from .io already
        # construct a table with .ids

        data.__file__ = absolute_filename
        return data

    @classmethod
    def from_url(cls, url):
        from Orange.data.io import UrlReader
        reader = UrlReader(url)
        data = reader.read()
        if cls != data.__class__:
            data = cls(data)
        return data

    # Helper function for __setitem__:
    # Set the row of table data matrices
    # noinspection PyProtectedMember
    def _set_row(self, example, row):
        domain = self.domain
        if isinstance(example, Instance):
            if example.domain == domain:
                if isinstance(example, RowInstance):
                    self.X[row] = example._x
                    self._Y[row] = example._y
                else:
                    self.X[row] = example._x
                    self._Y[row] = example._y
                self.metas[row] = example._metas
                return

            self.X[row], self._Y[row], self.metas[row] = \
                self.domain.convert(example)
            try:
                self.ids[row] = example.id
            except:
                with type(self)._next_instance_lock:
                    self.ids[row] = type(self)._next_instance_id
                    type(self)._next_instance_id += 1

        else:
            self.X[row] = [var.to_val(val)
                           for var, val in zip(domain.attributes, example)]
            self._Y[row] = [var.to_val(val)
                            for var, val in
                            zip(domain.class_vars,
                                example[len(domain.attributes):])]
            self.metas[row] = np.array([var.Unknown for var in domain.metas],
                                       dtype=object)

    def _check_all_dense(self):
        return all(x in (Storage.DENSE, Storage.MISSING)
                   for x in (self.X_density(), self.Y_density(),
                             self.metas_density()))

    def __getitem__(self, key):
        if isinstance(key, Integral):
            return RowInstance(self, key)
        if not isinstance(key, tuple):
            return self.from_table_rows(self, key)

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")

        row_idx, col_idx = key
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, (str, Integral, Variable)):
                col_idx = self.domain.index(col_idx)
                var = self.domain[col_idx]
                if 0 <= col_idx < len(self.domain.attributes):
                    val = self.X[row_idx, col_idx]
                elif col_idx >= len(self.domain.attributes):
                    val = self._Y[row_idx,
                                  col_idx - len(self.domain.attributes)]
                else:
                    val = self.metas[row_idx, -1 - col_idx]
                if isinstance(col_idx, DiscreteVariable) and var is not col_idx:
                    val = col_idx.get_mapper_from(var)(val)
                return Value(var, val)
            else:
                row_idx = [row_idx]

        # multiple rows OR single row but multiple columns:
        # construct a new table
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if attributes is not None:
            n_attrs = len(self.domain.attributes)
            r_attrs = [attributes[i]
                       for i, col in enumerate(col_indices)
                       if 0 <= col < n_attrs]
            r_classes = [attributes[i]
                         for i, col in enumerate(col_indices)
                         if col >= n_attrs]
            r_metas = [attributes[i]
                       for i, col in enumerate(col_indices) if col < 0]
            domain = Domain(r_attrs, r_classes, r_metas)
        else:
            domain = self.domain
        return self.from_table(domain, self, row_idx)

    def __setitem__(self, key, value):
        if not isinstance(key, tuple):
            if isinstance(value, Real):
                self.X[key, :] = value
                return
            self._set_row(value, key)
            return

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")
        row_idx, col_idx = key

        # single row
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, slice):
                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))
            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):
                col_idx = list(col_idx)
            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):
                if isinstance(value, (Sequence, np.ndarray)):
                    values = value
                elif isinstance(value, Iterable):
                    values = list(value)
                else:
                    raise TypeError("Setting multiple values requires a "
                                    "sequence or numpy array")
                if len(values) != len(col_idx):
                    raise ValueError("Invalid number of values")
            else:
                col_idx, values = [col_idx], [value]
            if isinstance(col_idx, DiscreteVariable) \
                    and self.domain[col_idx] != col_idx:
                values = self.domain[col_idx].get_mapper_from(col_idx)(values)
            for val, col_idx in zip(values, col_idx):
                if not isinstance(val, Integral):
                    val = self.domain[col_idx].to_val(val)
                if not isinstance(col_idx, Integral):
                    col_idx = self.domain.index(col_idx)
                if col_idx >= 0:
                    if col_idx < self.X.shape[1]:
                        self.X[row_idx, col_idx] = val
                    else:
                        self._Y[row_idx, col_idx - self.X.shape[1]] = val
                else:
                    self.metas[row_idx, -1 - col_idx] = val

        # multiple rows, multiple columns
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if col_indices is ...:
            col_indices = range(len(self.domain))
        n_attrs = self.X.shape[1]
        if isinstance(value, str):
            if not attributes:
                attributes = self.domain.attributes
            for var, col in zip(attributes, col_indices):
                if 0 <= col < n_attrs:
                    self.X[row_idx, col] = var.to_val(value)
                elif col >= n_attrs:
                    self._Y[row_idx, col - n_attrs] = var.to_val(value)
                else:
                    self.metas[row_idx, -1 - col] = var.to_val(value)
        else:
            attr_cols = np.fromiter(
                (col for col in col_indices if 0 <= col < n_attrs), int)
            class_cols = np.fromiter(
                (col - n_attrs for col in col_indices if col >= n_attrs), int)
            meta_cols = np.fromiter(
                (-1 - col for col in col_indices if col < 0), int)
            if value is None:
                value = Unknown

            if not isinstance(value, (Real, np.ndarray)) and \
                    (len(attr_cols) or len(class_cols)):
                raise TypeError(
                    "Ordinary attributes can only have primitive values")
            if len(attr_cols):
                self.X[row_idx, attr_cols] = value
            if len(class_cols):
                self._Y[row_idx, class_cols] = value
            if len(meta_cols):
                self.metas[row_idx, meta_cols] = value

    def __len__(self):
        return self.X.shape[0]

    def __str__(self):
        return "[" + ",\n ".join(str(ex) for ex in self) + "]"

    def __repr__(self):
        head = 5
        if self.is_sparse():
            head = min(self.X.shape[0], head)
        s = "[" + ",\n ".join(repr(ex) for ex in self[:head])
        if len(self) > head:
            s += ",\n ..."
        s += "\n]"
        return s

    @classmethod
    def concatenate(cls, tables, axis=0):
        """Concatenate tables into a new table"""
        def vstack(arrs):
            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)

        def merge1d(arrs):
            arrs = list(arrs)
            ydims = {arr.ndim for arr in arrs}
            if ydims == {1}:
                return np.hstack(arrs)
            else:
                return vstack([
                    arr if arr.ndim == 2 else np.atleast_2d(arr).T
                    for arr in arrs
                ])

        def collect(attr):
            return [getattr(arr, attr) for arr in tables]

        if axis == 1:
            raise ValueError("concatenate no longer supports axis 1")
        if not tables:
            raise ValueError('need at least one table to concatenate')
        if len(tables) == 1:
            return tables[0].copy()
        domain = tables[0].domain
        if any(table.domain != domain for table in tables):
            raise ValueError('concatenated tables must have the same domain')

        conc = cls.from_numpy(
            domain,
            vstack(collect("X")),
            merge1d(collect("Y")),
            vstack(collect("metas")),
            merge1d(collect("W"))
        )
        conc.ids = np.hstack([t.ids for t in tables])
        names = [table.name for table in tables if table.name != "untitled"]
        if names:
            conc.name = names[0]
        # TODO: Add attributes = {} to __init__
        conc.attributes = getattr(conc, "attributes", {})
        for table in reversed(tables):
            conc.attributes.update(table.attributes)
        return conc

    def is_view(self):
        """
        Return `True` if all arrays represent a view referring to another table
        """
        return ((not self.X.shape[-1] or self.X.base is not None) and
                (not self._Y.shape[-1] or self._Y.base is not None) and
                (not self.metas.shape[-1] or self.metas.base is not None) and
                (not self._weights.shape[-1] or self.W.base is not None))

    def is_copy(self):
        """
        Return `True` if the table owns its data
        """
        return ((not self.X.shape[-1] or self.X.base is None) and
                (self._Y.base is None) and
                (self.metas.base is None) and
                (self.W.base is None))

    def is_sparse(self):
        """
        Return `True` if the table stores data in sparse format
        """
        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])

    def ensure_copy(self):
        """
        Ensure that the table owns its data; copy arrays when necessary.
        """
        def is_view(x):
            # Sparse matrices don't have views like numpy arrays. Since indexing on
            # them creates copies in constructor we can skip this check here.
            return not sp.issparse(x) and x.base is not None

        if is_view(self.X):
            self.X = self.X.copy()
        if is_view(self._Y):
            self._Y = self._Y.copy()
        if is_view(self.metas):
            self.metas = self.metas.copy()
        if is_view(self.W):
            self.W = self.W.copy()

    def copy(self):
        """
        Return a copy of the table
        """
        t = self.__class__(self)
        t.ensure_copy()
        return t

    @staticmethod
    def __determine_density(data):
        if data is None:
            return Storage.Missing
        if data is not None and sp.issparse(data):
            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE
        else:
            return Storage.DENSE

    def X_density(self):
        if not hasattr(self, "_X_density"):
            self._X_density = self.__determine_density(self.X)
        return self._X_density

    def Y_density(self):
        if not hasattr(self, "_Y_density"):
            self._Y_density = self.__determine_density(self._Y)
        return self._Y_density

    def metas_density(self):
        if not hasattr(self, "_metas_density"):
            self._metas_density = self.__determine_density(self.metas)
        return self._metas_density

    def set_weights(self, weight=1):
        """
        Set weights of data instances; create a vector of weights if necessary.
        """
        if not self.W.shape[-1]:
            self.W = np.empty(len(self))
        self.W[:] = weight

    def has_weights(self):
        """Return `True` if the data instances are weighed. """
        return self.W.shape[-1] != 0

    def total_weight(self):
        """
        Return the total weight of instances in the table, or their number if
        they are unweighted.
        """
        if self.W.shape[-1]:
            return sum(self.W)
        return len(self)

    def has_missing(self):
        """Return `True` if there are any missing attribute or class values."""
        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X
        return missing_x or bn.anynan(self._Y)

    def has_missing_attribute(self):
        """Return `True` if there are any missing attribute values."""
        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X

    def has_missing_class(self):
        """Return `True` if there are any missing class values."""
        return bn.anynan(self._Y)

    def get_nan_frequency_attribute(self):
        if self.X.size == 0:
            return 0
        return np.isnan(self.X).sum() / self.X.size

    def get_nan_frequency_class(self):
        if self.Y.size == 0:
            return 0
        return np.isnan(self._Y).sum() / self._Y.size

    def checksum(self, include_metas=True):
        # TODO: zlib.adler32 does not work for numpy arrays with dtype object
        # (after pickling and unpickling such arrays, checksum changes)
        # Why, and should we fix it or remove it?
        """Return a checksum over X, Y, metas and W."""
        cs = zlib.adler32(np.ascontiguousarray(self.X))
        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)
        if include_metas:
            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)
        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)
        return cs

    def shuffle(self):
        """Randomly shuffle the rows of the table."""
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be shuffled")
        ind = np.arange(self.X.shape[0])
        np.random.shuffle(ind)
        self.X = self.X[ind]
        self._Y = self._Y[ind]
        self.metas = self.metas[ind]
        self.W = self.W[ind]

    def get_column_view(self, index):
        """
        Return a vector - as a view, not a copy - with a column of the table,
        and a bool flag telling whether this column is sparse. Note that
        vertical slicing of sparse matrices is inefficient.

        :param index: the index of the column
        :type index: int, str or Orange.data.Variable
        :return: (one-dimensional numpy array, sparse)
        """

        def rx(M):
            if sp.issparse(M):
                return np.asarray(M.todense())[:, 0], True
            else:
                return M, False

        if isinstance(index, Integral):
            col_index = index
        else:
            col_index = self.domain.index(index)
        if col_index >= 0:
            if col_index < self.X.shape[1]:
                col = rx(self.X[:, col_index])
            else:
                col = rx(self._Y[:, col_index - self.X.shape[1]])
        else:
            col = rx(self.metas[:, -1 - col_index])

        if isinstance(index, DiscreteVariable) \
                and index.values != self.domain[col_index].values:
            col = index.get_mapper_from(self.domain[col_index])(col[0]), col[1]
            col[0].flags.writeable = False
        return col

    def _filter_is_defined(self, columns=None, negate=False):
        # structure of function is obvious; pylint: disable=too-many-branches
        def _sp_anynan(a):
            return a.indptr[1:] != a[-1:] + a.shape[1]

        if columns is None:
            if sp.issparse(self.X):
                remove = _sp_anynan(self.X)
            else:
                remove = bn.anynan(self.X, axis=1)
            if sp.issparse(self._Y):
                remove += _sp_anynan(self._Y)
            else:
                remove += bn.anynan(self._Y, axis=1)
            if sp.issparse(self.metas):
                remove += _sp_anynan(self._metas)
            else:
                for i, var in enumerate(self.domain.metas):
                    col = self.metas[:, i].flatten()
                    if var.is_primitive():
                        remove += np.isnan(col.astype(float))
                    else:
                        remove += ~col.astype(bool)
        else:
            remove = np.zeros(len(self), dtype=bool)
            for column in columns:
                col, sparse = self.get_column_view(column)
                if sparse:
                    remove += col == 0
                elif self.domain[column].is_primitive():
                    remove += bn.anynan([col.astype(float)], axis=0)
                else:
                    remove += col.astype(bool)
        retain = remove if negate else np.logical_not(remove)
        return self.from_table_rows(self, retain)

    def _filter_has_class(self, negate=False):
        if sp.issparse(self._Y):
            if negate:
                retain = (self._Y.indptr[1:] !=
                          self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                retain = (self._Y.indptr[1:] ==
                          self._Y.indptr[-1:] + self._Y.shape[1])
        else:
            retain = bn.anynan(self._Y, axis=1)
            if not negate:
                retain = np.logical_not(retain)
        return self.from_table_rows(self, retain)

    def _filter_same_value(self, column, value, negate=False):
        if not isinstance(value, Real):
            value = self.domain[column].to_val(value)
        sel = self.get_column_view(column)[0] == value
        if negate:
            sel = np.logical_not(sel)
        return self.from_table_rows(self, sel)

    def _filter_values(self, filter):
        selection = self._values_filter_to_indicator(filter)
        return self.from_table(self.domain, self, selection)

    def _values_filter_to_indicator(self, filter):
        """Return selection of rows matching the filter conditions

        Handles conjunction/disjunction and negate modifiers

        Parameters
        ----------
        filter: Values object containing the conditions

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import Values

        if isinstance(filter, Values):
            conditions = filter.conditions
            conjunction = filter.conjunction
        else:
            conditions = [filter]
            conjunction = True
        if conjunction:
            sel = np.ones(len(self), dtype=bool)
        else:
            sel = np.zeros(len(self), dtype=bool)

        for f in conditions:
            selection = self._filter_to_indicator(f)

            if conjunction:
                sel *= selection
            else:
                sel += selection

        if filter.negate:
            sel = ~sel
        return sel

    def _filter_to_indicator(self, filter):
        """Return selection of rows that match the condition.

        Parameters
        ----------
        filter: ValueFilter describing the condition

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import (
            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,
            FilterStringList, IsDefined, Values
        )
        if isinstance(filter, Values):
            return self._values_filter_to_indicator(filter)

        def get_col_indices():
            cols = chain(self.domain.variables, self.domain.metas)
            if isinstance(filter, IsDefined):
                if filter.columns is not None:
                    return list(filter.columns)
                else:
                    return list(cols)

            if filter.column is not None:
                return [filter.column]

            if isinstance(filter, FilterDiscrete):
                raise ValueError("Discrete filter can't be applied across rows")
            if isinstance(filter, FilterContinuous):
                return [col for col in cols if col.is_continuous]
            if isinstance(filter,
                          (FilterString, FilterStringList, FilterRegex)):
                return [col for col in cols if col.is_string]
            raise TypeError("Invalid filter")

        def col_filter(col_idx):
            col = self.get_column_view(col_idx)[0]
            if isinstance(filter, IsDefined):
                if self.domain[col_idx].is_primitive():
                    return ~np.isnan(col.astype(float))
                else:
                    return col.astype(np.bool)
            if isinstance(filter, FilterDiscrete):
                return self._discrete_filter_to_indicator(filter, col)
            if isinstance(filter, FilterContinuous):
                return self._continuous_filter_to_indicator(filter, col)
            if isinstance(filter, FilterString):
                return self._string_filter_to_indicator(filter, col)
            if isinstance(filter, FilterStringList):
                if not filter.case_sensitive:
                    col = np.char.lower(np.array(col, dtype=str))
                    vals = [val.lower() for val in filter.values]
                else:
                    vals = filter.values
                return reduce(operator.add, (col == val for val in vals))
            if isinstance(filter, FilterRegex):
                return np.vectorize(filter)(col)
            raise TypeError("Invalid filter")

        col_indices = get_col_indices()
        if len(col_indices) == 1:
            sel = col_filter(col_indices[0])
        else:
            sel = np.ones(len(self), dtype=bool)
            for col_idx in col_indices:
                sel *= col_filter(col_idx)

        if isinstance(filter, IsDefined) and filter.negate:
            sel = ~sel
        return sel

    def _discrete_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given discrete filter.

        Parameters
        ----------
        filter: FilterDiscrete
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.values is None:  # <- is defined filter
            col = col.astype(float)
            return ~np.isnan(col)

        sel = np.zeros(len(self), dtype=bool)
        for val in filter.values:
            if not isinstance(val, Real):
                val = self.domain[filter.column].to_val(val)
            sel += (col == val)
        return sel

    def _continuous_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given continuous filter.

        Parameters
        ----------
        filter: FilterContinuous
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            col = col.astype(float)
            return ~np.isnan(col)

        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)

    def _string_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given string filter.

        Parameters
        ----------
        filter: FilterString
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            return col.astype(bool)

        col = col.astype(str)
        fmin = filter.min or ""
        fmax = filter.max or ""

        if not filter.case_sensitive:
            # convert all to lower case
            col = np.char.lower(col)
            fmin = fmin.lower()
            fmax = fmax.lower()

        if filter.oper == filter.Contains:
            return np.fromiter((fmin in e for e in col),
                               dtype=bool)
        if filter.oper == filter.StartsWith:
            return np.fromiter((e.startswith(fmin) for e in col),
                               dtype=bool)
        if filter.oper == filter.EndsWith:
            return np.fromiter((e.endswith(fmin) for e in col),
                               dtype=bool)

        return self._range_filter_to_indicator(filter, col, fmin, fmax)

    @staticmethod
    def _range_filter_to_indicator(filter, col, fmin, fmax):
        with np.errstate(invalid="ignore"):   # nan's are properly discarded
            if filter.oper == filter.Equal:
                return col == fmin
            if filter.oper == filter.NotEqual:
                return col != fmin
            if filter.oper == filter.Less:
                return col < fmin
            if filter.oper == filter.LessEqual:
                return col <= fmin
            if filter.oper == filter.Greater:
                return col > fmin
            if filter.oper == filter.GreaterEqual:
                return col >= fmin
            if filter.oper == filter.Between:
                return (col >= fmin) * (col <= fmax)
            if filter.oper == filter.Outside:
                return (col < fmin) + (col > fmax)

            raise TypeError("Invalid operator")

    def _compute_basic_stats(self, columns=None,
                             include_metas=False, compute_variance=False):
        if compute_variance:
            raise NotImplementedError("computation of variance is "
                                      "not implemented yet")
        W = self.W if self.has_weights() else None
        rr = []
        stats = []
        if not columns:
            if self.domain.attributes:
                rr.append(fast_stats(self.X, W))
            if self.domain.class_vars:
                rr.append(fast_stats(self._Y, W))
            if include_metas and self.domain.metas:
                rr.append(fast_stats(self.metas, W))
            if len(rr):
                stats = np.vstack(tuple(rr))
        else:
            nattrs = len(self.domain.attributes)
            for column in columns:
                c = self.domain.index(column)
                if 0 <= c < nattrs:
                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])
                elif c >= nattrs:
                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])
                else:
                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])
                stats.append(S[0])
        return stats

    def _compute_distributions(self, columns=None):
        if columns is None:
            columns = range(len(self.domain.variables))
        else:
            columns = [self.domain.index(var) for var in columns]

        distributions = []
        if sp.issparse(self.X):
            self.X = self.X.tocsc()

        W = self.W.ravel() if self.has_weights() else None

        for col in columns:
            variable = self.domain[col]

            # Select the correct data column from X, Y or metas
            if 0 <= col < self.X.shape[1]:
                x = self.X[:, col]
            elif col < 0:
                x = self.metas[:, col * (-1) - 1]
                if np.issubdtype(x.dtype, np.dtype(object)):
                    x = x.astype(float)
            else:
                x = self._Y[:, col - self.X.shape[1]]

            if variable.is_discrete:
                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)
            elif not x.shape[0]:
                dist, unknowns = np.zeros((2, 0)), 0
            else:
                if W is not None:
                    if sp.issparse(x):
                        arg_sort = np.argsort(x.data)
                        ranks = x.indices[arg_sort]
                        vals = np.vstack((x.data[arg_sort], W[ranks]))
                    else:
                        ranks = np.argsort(x)
                        vals = np.vstack((x[ranks], W[ranks]))
                else:
                    x_values = x.data if sp.issparse(x) else x
                    vals = np.ones((2, x_values.shape[0]))
                    vals[0, :] = x_values
                    vals[0, :].sort()

                dist = np.array(_valuecount.valuecount(vals))
                # If sparse, then 0s will not be counted with `valuecount`, so
                # we have to add them to the result manually.
                if sp.issparse(x) and sparse_has_implicit_zeros(x):
                    if W is not None:
                        zero_weights = sparse_implicit_zero_weights(x, W).sum()
                    else:
                        zero_weights = sparse_count_implicit_zeros(x)
                    zero_vec = [0, zero_weights]
                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)
                # Since `countnans` assumes vector shape to be (1, n) and `x`
                # shape is (n, 1), we pass the transpose
                unknowns = countnans(x.T, W)
            distributions.append((dist, unknowns))

        return distributions

    def _compute_contingency(self, col_vars=None, row_var=None):
        n_atts = self.X.shape[1]

        if col_vars is None:
            col_vars = range(len(self.domain.variables))
        else:
            col_vars = [self.domain.index(var) for var in col_vars]
        if row_var is None:
            row_var = self.domain.class_var
            if row_var is None:
                raise ValueError("No row variable")

        row_desc = self.domain[row_var]
        if not row_desc.is_discrete:
            raise TypeError("Row variable must be discrete")
        row_indi = self.domain.index(row_var)
        n_rows = len(row_desc.values)
        if 0 <= row_indi < n_atts:
            row_data = self.X[:, row_indi]
        elif row_indi < 0:
            row_data = self.metas[:, -1 - row_indi]
        else:
            row_data = self._Y[:, row_indi - n_atts]

        W = self.W if self.has_weights() else None

        col_desc = [self.domain[var] for var in col_vars]
        col_indi = [self.domain.index(var) for var in col_vars]

        if any(not (var.is_discrete or var.is_continuous)
               for var in col_desc):
            raise ValueError("contingency can be computed only for discrete "
                             "and continuous values")

        # when we select a column in sparse matrix it is still two dimensional
        # and sparse - since it is just a column we can afford to transform
        # it to dense and make it 1D
        if issparse(row_data):
            row_data = row_data.toarray().ravel()
        if row_data.dtype.kind != "f": #meta attributes can be stored as type object
            row_data = row_data.astype(float)

        contingencies = [None] * len(col_desc)
        for arr, f_cond, f_ind in (
                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),
                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),
                (self.metas, lambda i: i < 0, lambda i: -1 - i)):

            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]

            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]
            disc_vars = [v for v in vars if v[2].is_discrete]
            if disc_vars:
                if sp.issparse(arr):
                    max_vals = max(len(v[2].values) for v in disc_vars)
                    disc_indi = {i for _, i, _ in disc_vars}
                    mask = [i in disc_indi for i in range(arr.shape[1])]
                    conts, nans_cols, nans_rows, nans = contingency(
                        arr, row_data, max_vals - 1, n_rows - 1, W, mask)
                    for col_i, arr_i, var in disc_vars:
                        n_vals = len(var.values)
                        contingencies[col_i] = (
                            conts[arr_i][:, :n_vals], nans_cols[arr_i],
                            nans_rows[arr_i], nans[arr_i])
                else:
                    for col_i, arr_i, var in disc_vars:
                        contingencies[col_i] = contingency(
                            arr[:, arr_i].astype(float),
                            row_data, len(var.values) - 1, n_rows - 1, W)

            cont_vars = [v for v in vars if v[2].is_continuous]
            if cont_vars:
                W_ = None
                if W is not None:
                    W_ = W.astype(dtype=np.float64)
                if sp.issparse(arr):
                    arr = sp.csc_matrix(arr)

                for col_i, arr_i, _ in cont_vars:
                    if sp.issparse(arr):
                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        W_ = None if W_ is None else W_[rows]
                        classes_ = row_data[rows]
                    else:
                        col_data, W_, classes_ = arr[:, arr_i], W_, row_data

                    col_data = col_data.astype(dtype=np.float64)
                    contingencies[col_i] = _contingency.contingency_floatarray(
                        col_data, classes_, n_rows, W_)

        return contingencies

    @classmethod
    def transpose(cls, table, feature_names_column="",
                  meta_attr_name="Feature name", feature_name="Feature"):
        """
        Transpose the table.

        :param table: Table - table to transpose
        :param feature_names_column: str - name of (String) meta attribute to
            use for feature names
        :param meta_attr_name: str - name of new meta attribute into which
            feature names are mapped
        :param feature_name: str - default feature name prefix
        :return: Table - transposed table
        """

        self = cls()
        n_cols, self.n_rows = table.X.shape
        old_domain = table.attributes.get("old_domain")

        # attributes
        # - classes and metas to attributes of attributes
        # - arbitrary meta column to feature names
        self.X = table.X.T
        if feature_names_column:
            names = [str(row[feature_names_column]) for row in table]
            names = get_unique_names_duplicates(names)
            attributes = [ContinuousVariable(name) for name in names]
        else:
            places = int(np.ceil(np.log10(n_cols))) if n_cols else 1
            attributes = [ContinuousVariable(f"{feature_name} {i:0{places}}")
                          for i in range(1, n_cols + 1)]
        if old_domain is not None and feature_names_column:
            for i, _ in enumerate(attributes):
                if attributes[i].name in old_domain:
                    var = old_domain[attributes[i].name]
                    attr = ContinuousVariable(var.name) if var.is_continuous \
                        else DiscreteVariable(var.name, var.values)
                    attr.attributes = var.attributes.copy()
                    attributes[i] = attr

        def set_attributes_of_attributes(_vars, _table):
            for i, variable in enumerate(_vars):
                if variable.name == feature_names_column:
                    continue
                for j, row in enumerate(_table):
                    value = variable.repr_val(row) if np.isscalar(row) \
                        else row[i] if isinstance(row[i], str) \
                        else variable.repr_val(row[i])

                    if value not in MISSING_VALUES:
                        attributes[j].attributes[variable.name] = value

        set_attributes_of_attributes(table.domain.class_vars, table.Y)
        set_attributes_of_attributes(table.domain.metas, table.metas)

        # weights
        self.W = np.empty((self.n_rows, 0))

        def get_table_from_attributes_of_attributes(_vars, _dtype=float):
            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)
            for i, _attr in enumerate(table.domain.attributes):
                for j, _var in enumerate(_vars):
                    val = str(_attr.attributes.get(_var.name, ""))
                    if not _var.is_string:
                        val = np.nan if val in MISSING_VALUES else \
                            _var.values.index(val) if \
                                _var.is_discrete else float(val)
                    T[i, j] = val
            return T

        # class_vars - attributes of attributes to class - from old domain
        class_vars = []
        if old_domain is not None:
            class_vars = old_domain.class_vars
        self.Y = get_table_from_attributes_of_attributes(class_vars)

        # metas
        # - feature names and attributes of attributes to metas
        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []
        if meta_attr_name not in [m.name for m in table.domain.metas] and \
                table.domain.attributes:
            self.metas = np.array([[a.name] for a in table.domain.attributes],
                                  dtype=object)
            metas.append(StringVariable(meta_attr_name))

        names = chain.from_iterable(list(attr.attributes)
                                    for attr in table.domain.attributes)
        names = sorted(set(names) - {var.name for var in class_vars})

        def guessed_var(i, var_name):
            orig_vals = M[:, i]
            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)
            values, variable = Orange.data.io.sanitize_variable(
                val_map, vals, orig_vals, var_type, {}, name=var_name)
            M[:, i] = values
            return variable

        _metas = [StringVariable(n) for n in names]
        if old_domain is not None:
            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]
        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)
        if old_domain is None:
            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]
        if _metas:
            self.metas = np.hstack((self.metas, M))
            metas.extend(_metas)

        self.domain = Domain(attributes, class_vars, metas)
        cls._init_ids(self)
        self.attributes = table.attributes.copy()
        self.attributes["old_domain"] = table.domain
        return self

    def to_sparse(self, sparse_attributes=True, sparse_class=False,
                  sparse_metas=False):
        def sparsify(features):
            for f in features:
                f.sparse = True

        new_domain = self.domain.copy()

        if sparse_attributes:
            sparsify(new_domain.attributes)
        if sparse_class:
            sparsify(new_domain.class_vars)
        if sparse_metas:
            sparsify(new_domain.metas)
        return self.transform(new_domain)

    def to_dense(self, dense_attributes=True, dense_class=True,
                 dense_metas=True):
        def densify(features):
            for f in features:
                f.sparse = False

        new_domain = self.domain.copy()

        if dense_attributes:
            densify(new_domain.attributes)
        if dense_class:
            densify(new_domain.class_vars)
        if dense_metas:
            densify(new_domain.metas)
        t = self.transform(new_domain)
        t.ids = self.ids    # preserve indices
        return t


def _check_arrays(*arrays, dtype=None, shape_1=None):
    checked = []
    if not len(arrays):
        return checked

    def ninstances(array):
        if hasattr(array, "shape"):
            return array.shape[0]
        else:
            return len(array) if array is not None else 0

    if shape_1 is None:
        shape_1 = ninstances(arrays[0])

    for array in arrays:
        if array is None:
            checked.append(array)
            continue

        if ninstances(array) != shape_1:
            raise ValueError("Leading dimension mismatch (%d != %d)"
                             % (ninstances(array), shape_1))

        if sp.issparse(array):
            array.data = np.asarray(array.data)
            has_inf = _check_inf(array.data)
        else:
            if dtype is not None:
                array = np.asarray(array, dtype=dtype)
            else:
                array = np.asarray(array)
            has_inf = _check_inf(array)

        if has_inf:
            array[np.isinf(array)] = np.nan
            warnings.warn("Array contains infinity.", RuntimeWarning)
        checked.append(array)

    return checked


def _check_inf(array):
    return array.dtype.char in np.typecodes['AllFloat'] and \
           np.isinf(array.data).any()


def _subarray(arr, rows, cols):
    rows = _optimize_indices(rows, arr.shape[0])
    cols = _optimize_indices(cols, arr.shape[1])
    return arr[_rxc_ix(rows, cols)]


def _optimize_indices(indices, maxlen):
    """
    Convert integer indices to slice if possible. It only converts increasing
    integer ranges with positive steps and valid starts and ends.
    Only convert valid ends so that invalid ranges will still raise
    an exception.

    Allows numpy to reuse the data array, because it defaults to copying
    if given indices.

    Parameters
    ----------
    indices : 1D sequence, slice or Ellipsis
    """
    if isinstance(indices, slice):
        return indices

    if indices is ...:
        return slice(None, None, 1)

    if len(indices) >= 1:
        indices = np.asarray(indices)
        if indices.dtype != np.bool:
            begin = indices[0]
            end = indices[-1]
            steps = np.diff(indices) if len(indices) > 1 else np.array([1])
            step = steps[0]

            # continuous ranges with constant step and valid start and stop index can be slices
            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:
                return slice(begin, end + step, step)

    return indices


def _rxc_ix(rows, cols):
    """
    Construct an index object to index the `rows` x `cols` cross product.

    Rows and columns can be a 1d bool or int sequence, or a slice.
    The later is a convenience and is interpreted the same
    as `slice(None, None, -1)`

    Parameters
    ----------
    rows : 1D sequence, slice
        Row indices.
    cols : 1D sequence, slice
        Column indices.

    See Also
    --------
    numpy.ix_

    Examples
    --------
    >>> import numpy as np
    >>> a = np.arange(10).reshape(2, 5)
    >>> a[_rxc_ix([0, 1], [3, 4])]
    array([[3, 4],
           [8, 9]])
    >>> a[_rxc_ix([False, True], slice(None, None, 1))]
    array([[5, 6, 7, 8, 9]])

    """
    isslice = (isinstance(rows, slice), isinstance(cols, slice))
    if isslice == (True, True):
        return rows, cols
    elif isslice == (True, False):
        return rows, np.asarray(np.ix_(cols), int).ravel()
    elif isslice == (False, True):
        return np.asarray(np.ix_(rows), int).ravel(), cols
    else:
        r, c = np.ix_(rows, cols)
        return np.asarray(r, int), np.asarray(c, int)


def assure_domain_conversion_sparsity(target, source):
    """
    Assure that the table obeys the domain conversion's suggestions about sparsity.

    Args:
        target (Table): the target table.
        source (Table): the source table.

    Returns:
        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion
            for transformation from source to the target domain.
    """
    conversion = DomainConversion(source.domain, target.domain)
    match_density = [assure_array_dense, assure_array_sparse]
    target.X = match_density[conversion.sparse_X](target.X)
    target.Y = match_density[conversion.sparse_Y](target.Y)
    target.metas = match_density[conversion.sparse_metas](target.metas)
    return target

```
--- 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