We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
to_dict() not in Chart.__dir__
All in title.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `altair/schema/baseobject.py`
Content:
```
1 import pandas as pd
2 import traitlets as T
3 
4 from ..utils._py3k_compat import string_types
5 
6 _attr_template = "Attribute not found: {0}. Valid keyword arguments for this class: {1}"
7 
8 
9 class BaseObject(T.HasTraits):
10 
11     skip = []
12 
13     def __init__(self, **kwargs):
14         all_traits = list(self.traits())
15         for k in kwargs:
16             if k not in all_traits:
17                 raise KeyError(_attr_template.format(k, all_traits))
18         super(BaseObject, self).__init__(**kwargs)
19 
20     @classmethod
21     def infer_keywords(cls, *args, **kwargs):
22         """Utility to initialize object from args and kwargs
23 
24         Arguments are converted to keyword arguments by inferring the keyword
25         from their type.
26         Keyword arguments are converted to the correct Instance class
27         if required.
28         """
29         def get_class(trait):
30             # TODO: what do do with lists?
31             if isinstance(trait, T.Union):
32                 for klass in map(get_class, trait.trait_types):
33                     if klass:
34                         return klass
35             elif isinstance(trait, T.Instance):
36                 return trait.klass
37 
38         traits = cls.class_traits()
39         classes = {n: get_class(t) for n, t in traits.items()}
40 
41         # Turn all keyword arguments to the appropriate class
42         for name, arg in kwargs.items():
43             Trait = classes.get(name, None)
44             if Trait is not None and not isinstance(arg, Trait):
45                 try:
46                     kwargs[name] = Trait(arg)
47                 except (TypeError, T.TraitError):
48                     pass  # errors will handled by traitlets below
49 
50         # find forward/backward mapping among unique classes
51         name_to_trait = {}
52         while classes:
53             name, trait = classes.popitem()
54             if trait is None:
55                 continue
56             if trait not in set.union(set(classes.values()),
57                                       set(name_to_trait.values())):
58                 name_to_trait[name] = trait
59         trait_to_name = {t: n for n, t in name_to_trait.items()}
60 
61         # Update all arguments
62         for arg in args:
63             name = trait_to_name.get(type(arg), None)
64             if name is None:
65                 raise ValueError("{0}: Unable to infer argument name for {1}".format(cls, arg))
66             elif name in kwargs:
67                 raise ValueError("{0}: {1} specified both by arg and kwarg".format(cls, name))
68             else:
69                 kwargs[name] = arg
70         return kwargs
71 
72     def update_traits(self, **kwargs):
73         for key, val in kwargs.items():
74             self.set_trait(key, val)
75         return self
76 
77     def update_inferred_traits(self, *args, **kwargs):
78         kwargs = self.infer_keywords(*args, **kwargs)
79         return self.update_traits(**kwargs)
80 
81     def update_subtraits(self, attrs, *args, **kwargs):
82         """Update sub-traits without overwriting other traits"""
83         if not (args or kwargs):
84             return self
85         if isinstance(attrs, string_types):
86             attrs = (attrs,)
87         if len(attrs) == 0:
88             self.update_inferred_traits(*args, **kwargs)
89         else:
90             attr = attrs[0]
91             if attr not in self.traits():
92                 raise ValueError('{0} has no trait {1}'.format(self, attr))
93             trait = getattr(self, attr)
94             if trait is None:
95                 trait = self.traits()[attr].klass()
96             setattr(self, attr, trait.update_subtraits(attrs[1:], *args, **kwargs))
97         return self
98 
99     def __contains__(self, key):
100         try:
101             value = getattr(self, key)
102         except AttributeError:
103             return False
104 
105         # comparison to None will break, so check DataFrame specifically
106         if isinstance(value, pd.DataFrame):
107             return True
108         elif value is not None:
109             if isinstance(value, (int, float, bool)):
110                 return True
111             else:
112                 return bool(value)
113         else:
114             return False
115 
116     def __dir__(self):
117         """Customize tab completed attributes."""
118         return list(self.traits())
119 
120     @classmethod
121     def from_dict(cls, dct):
122         """Instantiate the object from a valid JSON dictionary"""
123         from ..utils.visitors import FromDict
124         return FromDict().clsvisit(cls, dct)
125 
126     def to_dict(self, data=True):
127         """Emit the JSON representation for this object as as dict."""
128         from ..utils.visitors import ToDict
129         self._finalize()
130         return ToDict().visit(self, data)
131 
132     def _finalize(self, **kwargs):
133         """Finalize the object, and all contained objects, for export."""
134         def finalize_obj(obj):
135             if isinstance(obj, BaseObject):
136                 obj._finalize(**kwargs)
137             elif isinstance(obj, list):
138                 for item in obj:
139                     finalize_obj(item)
140 
141         for name in self.traits():
142             value = getattr(self, name)
143             finalize_obj(value)
144
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/altair/schema/baseobject.py b/altair/schema/baseobject.py
--- a/altair/schema/baseobject.py
+++ b/altair/schema/baseobject.py
@@ -115,7 +115,7 @@
 
     def __dir__(self):
         """Customize tab completed attributes."""
-        return list(self.traits())
+        return list(self.traits())+['to_dict', 'from_dict']
 
     @classmethod
     def from_dict(cls, dct):

{"golden_diff": "diff --git a/altair/schema/baseobject.py b/altair/schema/baseobject.py\n--- a/altair/schema/baseobject.py\n+++ b/altair/schema/baseobject.py\n@@ -115,7 +115,7 @@\n \n     def __dir__(self):\n         \"\"\"Customize tab completed attributes.\"\"\"\n-        return list(self.traits())\n+        return list(self.traits())+['to_dict', 'from_dict']\n \n     @classmethod\n     def from_dict(cls, dct):\n", "issue": "to_dict() not in Chart.__dir__\nAll in title.\n\n", "before_files": [{"content": "import pandas as pd\nimport traitlets as T\n\nfrom ..utils._py3k_compat import string_types\n\n_attr_template = \"Attribute not found: {0}. Valid keyword arguments for this class: {1}\"\n\n\nclass BaseObject(T.HasTraits):\n\n    skip = []\n\n    def __init__(self, **kwargs):\n        all_traits = list(self.traits())\n        for k in kwargs:\n            if k not in all_traits:\n                raise KeyError(_attr_template.format(k, all_traits))\n        super(BaseObject, self).__init__(**kwargs)\n\n    @classmethod\n    def infer_keywords(cls, *args, **kwargs):\n        \"\"\"Utility to initialize object from args and kwargs\n\n        Arguments are converted to keyword arguments by inferring the keyword\n        from their type.\n        Keyword arguments are converted to the correct Instance class\n        if required.\n        \"\"\"\n        def get_class(trait):\n            # TODO: what do do with lists?\n            if isinstance(trait, T.Union):\n                for klass in map(get_class, trait.trait_types):\n                    if klass:\n                        return klass\n            elif isinstance(trait, T.Instance):\n                return trait.klass\n\n        traits = cls.class_traits()\n        classes = {n: get_class(t) for n, t in traits.items()}\n\n        # Turn all keyword arguments to the appropriate class\n        for name, arg in kwargs.items():\n            Trait = classes.get(name, None)\n            if Trait is not None and not isinstance(arg, Trait):\n                try:\n                    kwargs[name] = Trait(arg)\n                except (TypeError, T.TraitError):\n                    pass  # errors will handled by traitlets below\n\n        # find forward/backward mapping among unique classes\n        name_to_trait = {}\n        while classes:\n            name, trait = classes.popitem()\n            if trait is None:\n                continue\n            if trait not in set.union(set(classes.values()),\n                                      set(name_to_trait.values())):\n                name_to_trait[name] = trait\n        trait_to_name = {t: n for n, t in name_to_trait.items()}\n\n        # Update all arguments\n        for arg in args:\n            name = trait_to_name.get(type(arg), None)\n            if name is None:\n                raise ValueError(\"{0}: Unable to infer argument name for {1}\".format(cls, arg))\n            elif name in kwargs:\n                raise ValueError(\"{0}: {1} specified both by arg and kwarg\".format(cls, name))\n            else:\n                kwargs[name] = arg\n        return kwargs\n\n    def update_traits(self, **kwargs):\n        for key, val in kwargs.items():\n            self.set_trait(key, val)\n        return self\n\n    def update_inferred_traits(self, *args, **kwargs):\n        kwargs = self.infer_keywords(*args, **kwargs)\n        return self.update_traits(**kwargs)\n\n    def update_subtraits(self, attrs, *args, **kwargs):\n        \"\"\"Update sub-traits without overwriting other traits\"\"\"\n        if not (args or kwargs):\n            return self\n        if isinstance(attrs, string_types):\n            attrs = (attrs,)\n        if len(attrs) == 0:\n            self.update_inferred_traits(*args, **kwargs)\n        else:\n            attr = attrs[0]\n            if attr not in self.traits():\n                raise ValueError('{0} has no trait {1}'.format(self, attr))\n            trait = getattr(self, attr)\n            if trait is None:\n                trait = self.traits()[attr].klass()\n            setattr(self, attr, trait.update_subtraits(attrs[1:], *args, **kwargs))\n        return self\n\n    def __contains__(self, key):\n        try:\n            value = getattr(self, key)\n        except AttributeError:\n            return False\n\n        # comparison to None will break, so check DataFrame specifically\n        if isinstance(value, pd.DataFrame):\n            return True\n        elif value is not None:\n            if isinstance(value, (int, float, bool)):\n                return True\n            else:\n                return bool(value)\n        else:\n            return False\n\n    def __dir__(self):\n        \"\"\"Customize tab completed attributes.\"\"\"\n        return list(self.traits())\n\n    @classmethod\n    def from_dict(cls, dct):\n        \"\"\"Instantiate the object from a valid JSON dictionary\"\"\"\n        from ..utils.visitors import FromDict\n        return FromDict().clsvisit(cls, dct)\n\n    def to_dict(self, data=True):\n        \"\"\"Emit the JSON representation for this object as as dict.\"\"\"\n        from ..utils.visitors import ToDict\n        self._finalize()\n        return ToDict().visit(self, data)\n\n    def _finalize(self, **kwargs):\n        \"\"\"Finalize the object, and all contained objects, for export.\"\"\"\n        def finalize_obj(obj):\n            if isinstance(obj, BaseObject):\n                obj._finalize(**kwargs)\n            elif isinstance(obj, list):\n                for item in obj:\n                    finalize_obj(item)\n\n        for name in self.traits():\n            value = getattr(self, name)\n            finalize_obj(value)\n", "path": "altair/schema/baseobject.py"}], "after_files": [{"content": "import pandas as pd\nimport traitlets as T\n\nfrom ..utils._py3k_compat import string_types\n\n_attr_template = \"Attribute not found: {0}. Valid keyword arguments for this class: {1}\"\n\n\nclass BaseObject(T.HasTraits):\n\n    skip = []\n\n    def __init__(self, **kwargs):\n        all_traits = list(self.traits())\n        for k in kwargs:\n            if k not in all_traits:\n                raise KeyError(_attr_template.format(k, all_traits))\n        super(BaseObject, self).__init__(**kwargs)\n\n    @classmethod\n    def infer_keywords(cls, *args, **kwargs):\n        \"\"\"Utility to initialize object from args and kwargs\n\n        Arguments are converted to keyword arguments by inferring the keyword\n        from their type.\n        Keyword arguments are converted to the correct Instance class\n        if required.\n        \"\"\"\n        def get_class(trait):\n            # TODO: what do do with lists?\n            if isinstance(trait, T.Union):\n                for klass in map(get_class, trait.trait_types):\n                    if klass:\n                        return klass\n            elif isinstance(trait, T.Instance):\n                return trait.klass\n\n        traits = cls.class_traits()\n        classes = {n: get_class(t) for n, t in traits.items()}\n\n        # Turn all keyword arguments to the appropriate class\n        for name, arg in kwargs.items():\n            Trait = classes.get(name, None)\n            if Trait is not None and not isinstance(arg, Trait):\n                try:\n                    kwargs[name] = Trait(arg)\n                except (TypeError, T.TraitError):\n                    pass  # errors will handled by traitlets below\n\n        # find forward/backward mapping among unique classes\n        name_to_trait = {}\n        while classes:\n            name, trait = classes.popitem()\n            if trait is None:\n                continue\n            if trait not in set.union(set(classes.values()),\n                                      set(name_to_trait.values())):\n                name_to_trait[name] = trait\n        trait_to_name = {t: n for n, t in name_to_trait.items()}\n\n        # Update all arguments\n        for arg in args:\n            name = trait_to_name.get(type(arg), None)\n            if name is None:\n                raise ValueError(\"{0}: Unable to infer argument name for {1}\".format(cls, arg))\n            elif name in kwargs:\n                raise ValueError(\"{0}: {1} specified both by arg and kwarg\".format(cls, name))\n            else:\n                kwargs[name] = arg\n        return kwargs\n\n    def update_traits(self, **kwargs):\n        for key, val in kwargs.items():\n            self.set_trait(key, val)\n        return self\n\n    def update_inferred_traits(self, *args, **kwargs):\n        kwargs = self.infer_keywords(*args, **kwargs)\n        return self.update_traits(**kwargs)\n\n    def update_subtraits(self, attrs, *args, **kwargs):\n        \"\"\"Update sub-traits without overwriting other traits\"\"\"\n        if not (args or kwargs):\n            return self\n        if isinstance(attrs, string_types):\n            attrs = (attrs,)\n        if len(attrs) == 0:\n            self.update_inferred_traits(*args, **kwargs)\n        else:\n            attr = attrs[0]\n            if attr not in self.traits():\n                raise ValueError('{0} has no trait {1}'.format(self, attr))\n            trait = getattr(self, attr)\n            if trait is None:\n                trait = self.traits()[attr].klass()\n            setattr(self, attr, trait.update_subtraits(attrs[1:], *args, **kwargs))\n        return self\n\n    def __contains__(self, key):\n        try:\n            value = getattr(self, key)\n        except AttributeError:\n            return False\n\n        # comparison to None will break, so check DataFrame specifically\n        if isinstance(value, pd.DataFrame):\n            return True\n        elif value is not None:\n            if isinstance(value, (int, float, bool)):\n                return True\n            else:\n                return bool(value)\n        else:\n            return False\n\n    def __dir__(self):\n        \"\"\"Customize tab completed attributes.\"\"\"\n        return list(self.traits())+['to_dict', 'from_dict']\n\n    @classmethod\n    def from_dict(cls, dct):\n        \"\"\"Instantiate the object from a valid JSON dictionary\"\"\"\n        from ..utils.visitors import FromDict\n        return FromDict().clsvisit(cls, dct)\n\n    def to_dict(self, data=True):\n        \"\"\"Emit the JSON representation for this object as as dict.\"\"\"\n        from ..utils.visitors import ToDict\n        self._finalize()\n        return ToDict().visit(self, data)\n\n    def _finalize(self, **kwargs):\n        \"\"\"Finalize the object, and all contained objects, for export.\"\"\"\n        def finalize_obj(obj):\n            if isinstance(obj, BaseObject):\n                obj._finalize(**kwargs)\n            elif isinstance(obj, list):\n                for item in obj:\n                    finalize_obj(item)\n\n        for name in self.traits():\n            value = getattr(self, name)\n            finalize_obj(value)\n", "path": "altair/schema/baseobject.py"}]}