{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group=None):\n        \"\"\"A dict of option names and values.\n\n        If ``group`` is given, get options only from the named group; otherwise\n        all options are included.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item != None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value != None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item != None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value != None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\n",
            "header": {
                "file": {
                    "path": "tornado/options.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "6eefe6b4",
                "new_commit_hash": "04692f7a",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/options.py"
            },
            "plus_file": {
                "path": "b/tornado/options.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 115,
                            "length": 11
                        },
                        "new_range": {
                            "start": 115,
                            "length": 8
                        },
                        "section": "class OptionParser(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        \"\"\"The set of option-groups created by ``define``.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        return set(opt.group_name for opt in self._options.values())",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def group_dict(self, group=None):",
                                "type": "deleted"
                            },
                            {
                                "content": "        \"\"\"A dict of option names and values.",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "        If ``group`` is given, get options only from the named group; otherwise",
                                "type": "deleted"
                            },
                            {
                                "content": "        all options are included.",
                                "type": "deleted"
                            },
                            {
                                "content": "    def group_dict(self, group):",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"The names and values of options in a group.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        Useful for copying options into Application settings::",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "method",
                            "name": "OptionParser.group_dict",
                            "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group=None):\n        \"\"\"A dict of option names and values.\n\n        If ``group`` is given, get options only from the named group; otherwise\n        all options are included.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 118,
                            "end_lineno": 138,
                            "parent": {
                                "file_name": "tornado/options.py",
                                "type": "class",
                                "name": "OptionParser",
                                "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group=None):\n        \"\"\"A dict of option names and values.\n\n        If ``group`` is given, get options only from the named group; otherwise\n        all options are included.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 81,
                                "end_lineno": 317,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/options.py",
                            "type": "class",
                            "name": "OptionParser",
                            "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group=None):\n        \"\"\"A dict of option names and values.\n\n        If ``group`` is given, get options only from the named group; otherwise\n        all options are included.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 81,
                            "end_lineno": 317,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 137,
                            "length": 6
                        },
                        "new_range": {
                            "start": 134,
                            "length": 11
                        },
                        "section": "class OptionParser(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            (name, opt.value()) for name, opt in self._options.items()",
                                "type": "context"
                            },
                            {
                                "content": "            if not group or group == opt.group_name)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def as_dict(self):",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"The names and values of all options.\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        return dict(",
                                "type": "added"
                            },
                            {
                                "content": "            (name, opt.value()) for name, opt in self._options.items())",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def define(self, name, default=None, type=None, help=None, metavar=None,",
                                "type": "context"
                            },
                            {
                                "content": "               multiple=False, group=None, callback=None):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Defines a new command line option.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "class",
                            "name": "OptionParser",
                            "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 81,
                            "end_lineno": 319,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "method",
                            "name": "OptionParser.as_dict",
                            "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 137,
                            "end_lineno": 140,
                            "parent": {
                                "file_name": "tornado/options.py",
                                "type": "class",
                                "name": "OptionParser",
                                "content": "class OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 81,
                                "end_lineno": 319,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport os\nimport sys\n\nfrom tornado.options import OptionParser, Error\nfrom tornado.util import basestring_type\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # python 2\nexcept ImportError:\n    from io import StringIO  # python 3\n\ntry:\n    from unittest import mock  # python 3.3\nexcept ImportError:\n    try:\n        import mock  # third-party mock package\n    except ImportError:\n        mock = None\n\n\nclass OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        default_group_dict = options.group_dict()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, default_group_dict)\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport os\nimport sys\n\nfrom tornado.options import OptionParser, Error\nfrom tornado.util import basestring_type\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # python 2\nexcept ImportError:\n    from io import StringIO  # python 3\n\ntry:\n    from unittest import mock  # python 3.3\nexcept ImportError:\n    try:\n        import mock  # third-party mock package\n    except ImportError:\n        mock = None\n\n\nclass OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_as_dict(self):\n        options = self._sample_options()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, options.as_dict())\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])\n",
            "header": {
                "file": {
                    "path": "tornado/test/options_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "d32df0de",
                "new_commit_hash": "23ce0fe4",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/options_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/options_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 135,
                            "length": 6
                        },
                        "new_range": {
                            "start": 135,
                            "length": 11
                        },
                        "section": "class OptionsTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        actual = sorted(options.items())",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(expected, actual)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_as_dict(self):",
                                "type": "added"
                            },
                            {
                                "content": "        options = self._sample_options()",
                                "type": "added"
                            },
                            {
                                "content": "        expected = {'a': 1, 'b': 2, 'help': options.help}",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(expected, options.as_dict())",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_group_dict(self):",
                                "type": "context"
                            },
                            {
                                "content": "        options = OptionParser()",
                                "type": "context"
                            },
                            {
                                "content": "        options.define('a', default=1)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/options_test.py",
                            "type": "class",
                            "name": "OptionsTest",
                            "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_as_dict(self):\n        options = self._sample_options()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, options.as_dict())\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 25,
                            "end_lineno": 212,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/options_test.py",
                            "type": "method",
                            "name": "OptionsTest.test_as_dict",
                            "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_as_dict(self):\n        options = self._sample_options()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, options.as_dict())\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 138,
                            "end_lineno": 141,
                            "parent": {
                                "file_name": "tornado/test/options_test.py",
                                "type": "class",
                                "name": "OptionsTest",
                                "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_as_dict(self):\n        options = self._sample_options()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, options.as_dict())\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 25,
                                "end_lineno": 212,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 144,
                            "length": 10
                        },
                        "new_range": {
                            "start": 149,
                            "length": 6
                        },
                        "section": "class OptionsTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        this_file = frame.f_code.co_filename",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(set(['b_group', '', this_file]), options.groups())",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        default_group_dict = options.group_dict()",
                                "type": "deleted"
                            },
                            {
                                "content": "        expected = {'a': 1, 'b': 2, 'help': options.help}",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.assertEqual(expected, default_group_dict)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "        b_group_dict = options.group_dict('b_group')",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual({'b': 2}, b_group_dict)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/options_test.py",
                            "type": "method",
                            "name": "OptionsTest.test_group_dict",
                            "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        default_group_dict = options.group_dict()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, default_group_dict)\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 138,
                            "end_lineno": 154,
                            "parent": {
                                "file_name": "tornado/test/options_test.py",
                                "type": "class",
                                "name": "OptionsTest",
                                "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        default_group_dict = options.group_dict()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, default_group_dict)\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 25,
                                "end_lineno": 211,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/options_test.py",
                            "type": "class",
                            "name": "OptionsTest",
                            "content": "class OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        default_group_dict = options.group_dict()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, default_group_dict)\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 25,
                            "end_lineno": 211,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "f57fd525f9d765b9578a025ae65919a4e79efeeb^",
    "new_commit_hash": "f57fd525f9d765b9578a025ae65919a4e79efeeb",
    "commit_message": "OptionParser.group_dict() now requires a group. Add as_dict().",
    "commit_date": "2013-05-23T17:06:35-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "f57fd525f9d765b9578a025ae65919a4e79efeeb",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport os\nimport sys\n\nfrom tornado.options import OptionParser, Error\nfrom tornado.util import basestring_type\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # python 2\nexcept ImportError:\n    from io import StringIO  # python 3\n\ntry:\n    from unittest import mock  # python 3.3\nexcept ImportError:\n    try:\n        import mock  # third-party mock package\n    except ImportError:\n        mock = None\n\n\nclass OptionsTest(unittest.TestCase):\n    def test_parse_command_line(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_command_line([\"main.py\", \"--port=443\"])\n        self.assertEqual(options.port, 443)\n\n    def test_parse_config_file(self):\n        options = OptionParser()\n        options.define(\"port\", default=80)\n        options.parse_config_file(os.path.join(os.path.dirname(__file__),\n                                               \"options_test.cfg\"))\n        self.assertEquals(options.port, 443)\n\n    def test_parse_callbacks(self):\n        options = OptionParser()\n        self.called = False\n\n        def callback():\n            self.called = True\n        options.add_parse_callback(callback)\n\n        # non-final parse doesn't run callbacks\n        options.parse_command_line([\"main.py\"], final=False)\n        self.assertFalse(self.called)\n\n        # final parse does\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n        # callbacks can be run more than once on the same options\n        # object if there are multiple final parses\n        self.called = False\n        options.parse_command_line([\"main.py\"])\n        self.assertTrue(self.called)\n\n    def test_help(self):\n        options = OptionParser()\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(SystemExit):\n                options.parse_command_line([\"main.py\", \"--help\"])\n            usage = sys.stderr.getvalue()\n        finally:\n            sys.stderr = orig_stderr\n        self.assertIn(\"Usage:\", usage)\n\n    def test_subcommand(self):\n        base_options = OptionParser()\n        base_options.define(\"verbose\", default=False)\n        sub_options = OptionParser()\n        sub_options.define(\"foo\", type=str)\n        rest = base_options.parse_command_line(\n            [\"main.py\", \"--verbose\", \"subcommand\", \"--foo=bar\"])\n        self.assertEqual(rest, [\"subcommand\", \"--foo=bar\"])\n        self.assertTrue(base_options.verbose)\n        rest2 = sub_options.parse_command_line(rest)\n        self.assertEqual(rest2, [])\n        self.assertEqual(sub_options.foo, \"bar\")\n\n        # the two option sets are distinct\n        try:\n            orig_stderr = sys.stderr\n            sys.stderr = StringIO()\n            with self.assertRaises(Error):\n                sub_options.parse_command_line([\"subcommand\", \"--verbose\"])\n        finally:\n            sys.stderr = orig_stderr\n\n    def test_setattr(self):\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        options.foo = 2\n        self.assertEqual(options.foo, 2)\n\n    def test_setattr_type_check(self):\n        # setattr requires that options be the right type and doesn't\n        # parse from string formats.\n        options = OptionParser()\n        options.define('foo', default=1, type=int)\n        with self.assertRaises(Error):\n            options.foo = '2'\n\n    def test_setattr_with_callback(self):\n        values = []\n        options = OptionParser()\n        options.define('foo', default=1, type=int, callback=values.append)\n        options.foo = 2\n        self.assertEqual(values, [2])\n\n    def _sample_options(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', default=2)\n        return options\n\n    def test_iter(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        self.assertEqual(set(['a', 'b', 'help']), set(iter(options)))\n\n    def test_getitem(self):\n        options = self._sample_options()\n        self.assertEqual(1, options['a'])\n\n    def test_items(self):\n        options = self._sample_options()\n        # OptionParsers always define 'help'.\n        expected = [('a', 1), ('b', 2), ('help', options.help)]\n        actual = sorted(options.items())\n        self.assertEqual(expected, actual)\n\n    def test_as_dict(self):\n        options = self._sample_options()\n        expected = {'a': 1, 'b': 2, 'help': options.help}\n        self.assertEqual(expected, options.as_dict())\n\n    def test_group_dict(self):\n        options = OptionParser()\n        options.define('a', default=1)\n        options.define('b', group='b_group', default=2)\n\n        frame = sys._getframe(0)\n        this_file = frame.f_code.co_filename\n        self.assertEqual(set(['b_group', '', this_file]), options.groups())\n\n        b_group_dict = options.group_dict('b_group')\n        self.assertEqual({'b': 2}, b_group_dict)\n\n        self.assertEqual({}, options.group_dict('nonexistent'))\n\n    @unittest.skipIf(mock is None, 'mock package not present')\n    def test_mock_patch(self):\n        # ensure that our setattr hooks don't interfere with mock.patch\n        options = OptionParser()\n        options.define('foo', default=1)\n        options.parse_command_line(['main.py', '--foo=2'])\n        self.assertEqual(options.foo, 2)\n\n        with mock.patch.object(options.mockable(), 'foo', 3):\n            self.assertEqual(options.foo, 3)\n        self.assertEqual(options.foo, 2)\n\n        # Try nested patches mixed with explicit sets\n        with mock.patch.object(options.mockable(), 'foo', 4):\n            self.assertEqual(options.foo, 4)\n            options.foo = 5\n            self.assertEqual(options.foo, 5)\n            with mock.patch.object(options.mockable(), 'foo', 6):\n                self.assertEqual(options.foo, 6)\n            self.assertEqual(options.foo, 5)\n        self.assertEqual(options.foo, 2)\n\n    def test_types(self):\n        options = OptionParser()\n        options.define('str', type=str)\n        options.define('basestring', type=basestring_type)\n        options.define('int', type=int)\n        options.define('float', type=float)\n        options.define('datetime', type=datetime.datetime)\n        options.define('timedelta', type=datetime.timedelta)\n        options.parse_command_line(['main.py',\n                                    '--str=asdf',\n                                    '--basestring=qwer',\n                                    '--int=42',\n                                    '--float=1.5',\n                                    '--datetime=2013-04-28 05:16',\n                                    '--timedelta=45s'])\n        self.assertEqual(options.str, 'asdf')\n        self.assertEqual(options.basestring, 'qwer')\n        self.assertEqual(options.int, 42)\n        self.assertEqual(options.float, 1.5)\n        self.assertEqual(options.datetime,\n                         datetime.datetime(2013, 4, 28, 5, 16))\n        self.assertEqual(options.timedelta, datetime.timedelta(seconds=45))\n\n    def test_multiple_string(self):\n        options = OptionParser()\n        options.define('foo', type=str, multiple=True)\n        options.parse_command_line(['main.py', '--foo=a,b,c'])\n        self.assertEqual(options.foo, ['a', 'b', 'c'])\n\n    def test_multiple_int(self):\n        options = OptionParser()\n        options.define('foo', type=int, multiple=True)\n        options.parse_command_line(['main.py', '--foo=1,3,5:7'])\n        self.assertEqual(options.foo, [1, 3, 5, 6, 7])\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 725ms\nPrepared 1 package in 710ms\nInstalled 1 package in 0.91ms\n + tornado==3.1.dev2 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb)\nResolved 29 packages in 11ms\nInstalled 29 packages in 74ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb\n.................\ncollected 17 items\n\n=================================== ERRORS =====================================\n__________ OptionsTest.test_parse_config_file __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/r2e_tests/test_1.py\", line 35, in test_parse_config_file\n    options.parse_config_file(os.path.join(os.path.dirname(__file__),\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/tornado/options.py\", line 253, in parse_config_file\n    with open(path) as f:\nFileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/r2e_tests/options_test.cfg'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::OptionsTest::test_as_dict\nPASSED r2e_tests.test_1::OptionsTest::test_getitem\nPASSED r2e_tests.test_1::OptionsTest::test_group_dict\nPASSED r2e_tests.test_1::OptionsTest::test_help\nPASSED r2e_tests.test_1::OptionsTest::test_items\nPASSED r2e_tests.test_1::OptionsTest::test_iter\nPASSED r2e_tests.test_1::OptionsTest::test_mock_patch\nPASSED r2e_tests.test_1::OptionsTest::test_multiple_int\nPASSED r2e_tests.test_1::OptionsTest::test_multiple_string\nPASSED r2e_tests.test_1::OptionsTest::test_parse_callbacks\nPASSED r2e_tests.test_1::OptionsTest::test_parse_command_line\nERROR r2e_tests.test_1::OptionsTest::test_parse_config_file\nPASSED r2e_tests.test_1::OptionsTest::test_setattr\nPASSED r2e_tests.test_1::OptionsTest::test_setattr_type_check\nPASSED r2e_tests.test_1::OptionsTest::test_setattr_with_callback\nPASSED r2e_tests.test_1::OptionsTest::test_subcommand\nPASSED r2e_tests.test_1::OptionsTest::test_types\n=================== 1 error, 16 passed in 0.01s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb\n.................\ncollected 17 items\n\n=================================== ERRORS =====================================\n__________ OptionsTest.test_as_dict __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/r2e_tests/test_1.py\", line 141, in test_as_dict\n    self.assertEqual(expected, options.as_dict())\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/tornado/options.py\", line 97, in __getattr__\n    raise AttributeError(\"Unrecognized option %r\" % name)\nAttributeError: Unrecognized option 'as_dict'\n__________ OptionsTest.test_parse_config_file __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/r2e_tests/test_1.py\", line 35, in test_parse_config_file\n    options.parse_config_file(os.path.join(os.path.dirname(__file__),\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/tornado/options.py\", line 251, in parse_config_file\n    with open(path) as f:\nFileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f57fd525f9d765b9578a025ae65919a4e79efeeb/r2e_tests/options_test.cfg'\n\n==================== short test summary info ====================\nERROR r2e_tests.test_1::OptionsTest::test_as_dict\nPASSED r2e_tests.test_1::OptionsTest::test_getitem\nPASSED r2e_tests.test_1::OptionsTest::test_group_dict\nPASSED r2e_tests.test_1::OptionsTest::test_help\nPASSED r2e_tests.test_1::OptionsTest::test_items\nPASSED r2e_tests.test_1::OptionsTest::test_iter\nPASSED r2e_tests.test_1::OptionsTest::test_mock_patch\nPASSED r2e_tests.test_1::OptionsTest::test_multiple_int\nPASSED r2e_tests.test_1::OptionsTest::test_multiple_string\nPASSED r2e_tests.test_1::OptionsTest::test_parse_callbacks\nPASSED r2e_tests.test_1::OptionsTest::test_parse_command_line\nERROR r2e_tests.test_1::OptionsTest::test_parse_config_file\nPASSED r2e_tests.test_1::OptionsTest::test_setattr\nPASSED r2e_tests.test_1::OptionsTest::test_setattr_type_check\nPASSED r2e_tests.test_1::OptionsTest::test_setattr_with_callback\nPASSED r2e_tests.test_1::OptionsTest::test_subcommand\nPASSED r2e_tests.test_1::OptionsTest::test_types\n=================== 2 errors, 15 passed in 0.01s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/options.py tornado/test/options_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `OptionParser` Missing `as_dict()` Method Causes AttributeError

**Description:**
When attempting to retrieve all defined options as a dictionary using the `as_dict()` method, an `AttributeError` is raised because the method does not exist. This prevents users from easily accessing all option names and their corresponding values in a single dictionary.

**Example Code:**
```python
options = OptionParser()
options.define('a', default=1)
options.define('b', default=2)
options.define('help', default='Help text')
options.as_dict()  # This line raises AttributeError
```

**Expected Behavior:**
Calling `as_dict()` on an `OptionParser` instance should return a dictionary of all option names and their values, such as:
```python
{'a': 1, 'b': 2, 'help': 'Help text'}
```

**Actual Behavior:**
An `AttributeError` is raised with the message:
```
AttributeError: Unrecognized option 'as_dict'
```
[/ISSUE]
--- END ISSUE ---

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

--- BEGIN FILE ---
```
### tornado/options.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A command line parsing module that lets modules define their own options.

Each module defines its own options which are added to the global
option namespace, e.g.::

    from tornado.options import define, options

    define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
    define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
           help="Main user memcache servers")

    def connect():
        db = database.Connection(options.mysql_host)
        ...

The ``main()`` method of your application does not need to be aware of all of
the options used throughout your program; they are all automatically loaded
when the modules are loaded.  However, all modules that define options
must have been imported before the command line is parsed.

Your ``main()`` method can parse the command line or parse a config file with
either::

    tornado.options.parse_command_line()
    # or
    tornado.options.parse_config_file("/etc/server.conf")

Command line formats are what you would expect (``--myoption=myvalue``).
Config files are just Python files. Global names become options, e.g.::

    myoption = "myvalue"
    myotheroption = "myothervalue"

We support `datetimes <datetime.datetime>`, `timedeltas
<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to
`define`). We also accept multi-value options. See the documentation for
`define()` below.

`tornado.options.options` is a singleton instance of `OptionParser`, and
the top-level functions in this module (`define`, `parse_command_line`, etc)
simply call methods on it.  You may create additional `OptionParser`
instances to define isolated sets of options, such as for subcommands.
"""

from __future__ import absolute_import, division, print_function, with_statement

import datetime
import numbers
import re
import sys
import os
import textwrap

from tornado.escape import _unicode
from tornado.log import define_logging_options
from tornado import stack_context
from tornado.util import basestring_type, exec_in


class Error(Exception):
    """Exception raised by errors in the options module."""
    pass


class OptionParser(object):
    """A collection of options, a dictionary with object-like access.

    Normally accessed via static functions in the `tornado.options` module,
    which reference a global instance.
    """
    def __init__(self):
        # we have to use self.__dict__ because we override setattr.
        self.__dict__['_options'] = {}
        self.__dict__['_parse_callbacks'] = []
        self.define("help", type=bool, help="show this help information",
                    callback=self._help_callback)

    def __getattr__(self, name):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].value()
        raise AttributeError("Unrecognized option %r" % name)

    def __setattr__(self, name, value):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].set(value)
        raise AttributeError("Unrecognized option %r" % name)

    def __iter__(self):
        return iter(self._options)

    def __getitem__(self, item):
        return self._options[item].value()

    def items(self):
        """A sequence of (name, value) pairs."""
        return [(name, opt.value()) for name, opt in self._options.items()]

    def groups(self):
        """The set of option-groups created by ``define``."""
        return set(opt.group_name for opt in self._options.values())

    def group_dict(self, group=None):
        """A dict of option names and values.

        If ``group`` is given, get options only from the named group; otherwise
        all options are included.

        Useful for copying options into Application settings::

            from tornado.options import define, parse_command_line, options

            define('template_path', group='application')
            define('static_path', group='application')

            parse_command_line()

            application = Application(
                handlers, **options.group_dict('application'))
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items()
            if not group or group == opt.group_name)

    def define(self, name, default=None, type=None, help=None, metavar=None,
               multiple=False, group=None, callback=None):
        """Defines a new command line option.

        If ``type`` is given (one of str, float, int, datetime, or timedelta)
        or can be inferred from the ``default``, we parse the command line
        arguments based on the given type. If ``multiple`` is True, we accept
        comma-separated values, and the option value is always a list.

        For multi-value integers, we also accept the syntax ``x:y``, which
        turns into ``range(x, y)`` - very useful for long integer ranges.

        ``help`` and ``metavar`` are used to construct the
        automatically generated command line help string. The help
        message is formatted like::

           --name=METAVAR      help string

        ``group`` is used to group the defined options in logical
        groups. By default, command line options are grouped by the
        file in which they are defined.

        Command line option names must be unique globally. They can be parsed
        from the command line with `parse_command_line` or parsed from a
        config file with `parse_config_file`.

        If a ``callback`` is given, it will be run with the new value whenever
        the option is changed.  This can be used to combine command-line
        and file-based options::

            define("config", type=str, help="path to config file",
                   callback=lambda path: parse_config_file(path, final=False))

        With this definition, options in the file specified by ``--config`` will
        override options set earlier on the command line, but can be overridden
        by later flags.
        """
        if name in self._options:
            raise Error("Option %r already defined in %s", name,
                        self._options[name].file_name)
        frame = sys._getframe(0)
        options_file = frame.f_code.co_filename
        file_name = frame.f_back.f_code.co_filename
        if file_name == options_file:
            file_name = ""
        if type is None:
            if not multiple and default is not None:
                type = default.__class__
            else:
                type = str
        if group:
            group_name = group
        else:
            group_name = file_name
        self._options[name] = _Option(name, file_name=file_name,
                                      default=default, type=type, help=help,
                                      metavar=metavar, multiple=multiple,
                                      group_name=group_name,
                                      callback=callback)

    def parse_command_line(self, args=None, final=True):
        """Parses all options given on the command line (defaults to
        `sys.argv`).

        Note that ``args[0]`` is ignored since it is the program name
        in `sys.argv`.

        We return a list of all arguments that are not parsed as options.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        if args is None:
            args = sys.argv
        remaining = []
        for i in range(1, len(args)):
            # All things after the last option are command line arguments
            if not args[i].startswith("-"):
                remaining = args[i:]
                break
            if args[i] == "--":
                remaining = args[i + 1:]
                break
            arg = args[i].lstrip("-")
            name, equals, value = arg.partition("=")
            name = name.replace('-', '_')
            if not name in self._options:
                self.print_help()
                raise Error('Unrecognized command line option: %r' % name)
            option = self._options[name]
            if not equals:
                if option.type == bool:
                    value = "true"
                else:
                    raise Error('Option %r requires a value' % name)
            option.parse(value)

        if final:
            self.run_parse_callbacks()

        return remaining

    def parse_config_file(self, path, final=True):
        """Parses and loads the Python config file at the given path.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        config = {}
        with open(path) as f:
            exec_in(f.read(), config, config)
        for name in config:
            if name in self._options:
                self._options[name].set(config[name])

        if final:
            self.run_parse_callbacks()

    def print_help(self, file=None):
        """Prints all the command line options to stderr (or another file)."""
        if file is None:
            file = sys.stderr
        print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
        print("\nOptions:\n", file=file)
        by_group = {}
        for option in self._options.values():
            by_group.setdefault(option.group_name, []).append(option)

        for filename, o in sorted(by_group.items()):
            if filename:
                print("\n%s options:\n" % os.path.normpath(filename), file=file)
            o.sort(key=lambda option: option.name)
            for option in o:
                prefix = option.name
                if option.metavar:
                    prefix += "=" + option.metavar
                description = option.help or ""
                if option.default is not None and option.default != '':
                    description += " (default %s)" % option.default
                lines = textwrap.wrap(description, 79 - 35)
                if len(prefix) > 30 or len(lines) == 0:
                    lines.insert(0, '')
                print("  --%-30s %s" % (prefix, lines[0]), file=file)
                for line in lines[1:]:
                    print("%-34s %s" % (' ', line), file=file)
        print(file=file)

    def _help_callback(self, value):
        if value:
            self.print_help()
            sys.exit(0)

    def add_parse_callback(self, callback):
        """Adds a parse callback, to be invoked when option parsing is done."""
        self._parse_callbacks.append(stack_context.wrap(callback))

    def run_parse_callbacks(self):
        for callback in self._parse_callbacks:
            callback()

    def mockable(self):
        """Returns a wrapper around self that is compatible with
        `mock.patch <unittest.mock.patch>`.

        The `mock.patch <unittest.mock.patch>` function (included in
        the standard library `unittest.mock` package since Python 3.3,
        or in the third-party ``mock`` package for older versions of
        Python) is incompatible with objects like ``options`` that
        override ``__getattr__`` and ``__setattr__``.  This function
        returns an object that can be used with `mock.patch.object
        <unittest.mock.patch.object>` to modify option values::

            with mock.patch.object(options.mockable(), 'name', value):
                assert options.name == value
        """
        return _Mockable(self)


class _Mockable(object):
    """`mock.patch` compatible wrapper for `OptionParser`.

    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
    the attribute it set instead of setting a new one (assuming that
    the object does not catpure ``__setattr__``, so the patch
    created a new attribute in ``__dict__``).

    _Mockable's getattr and setattr pass through to the underlying
    OptionParser, and delattr undoes the effect of a previous setattr.
    """
    def __init__(self, options):
        # Modify __dict__ directly to bypass __setattr__
        self.__dict__['_options'] = options
        self.__dict__['_originals'] = {}

    def __getattr__(self, name):
        return getattr(self._options, name)

    def __setattr__(self, name, value):
        assert name not in self._originals, "don't reuse mockable objects"
        self._originals[name] = getattr(self._options, name)
        setattr(self._options, name, value)

    def __delattr__(self, name):
        setattr(self._options, name, self._originals.pop(name))


class _Option(object):
    def __init__(self, name, default=None, type=basestring_type, help=None,
                 metavar=None, multiple=False, file_name=None, group_name=None,
                 callback=None):
        if default is None and multiple:
            default = []
        self.name = name
        self.type = type
        self.help = help
        self.metavar = metavar
        self.multiple = multiple
        self.file_name = file_name
        self.group_name = group_name
        self.callback = callback
        self.default = default
        self._value = None

    def value(self):
        return self.default if self._value is None else self._value

    def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()

    def set(self, value):
        if self.multiple:
            if not isinstance(value, list):
                raise Error("Option %r is required to be a list of %s" %
                            (self.name, self.type.__name__))
            for item in value:
                if item != None and not isinstance(item, self.type):
                    raise Error("Option %r is required to be a list of %s" %
                                (self.name, self.type.__name__))
        else:
            if value != None and not isinstance(value, self.type):
                raise Error("Option %r is required to be a %s (%s given)" %
                            (self.name, self.type.__name__, type(value)))
        self._value = value
        if self.callback is not None:
            self.callback(self._value)

    # Supported date/time formats in our options
    _DATETIME_FORMATS = [
        "%a %b %d %H:%M:%S %Y",
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%dT%H:%M",
        "%Y%m%d %H:%M:%S",
        "%Y%m%d %H:%M",
        "%Y-%m-%d",
        "%Y%m%d",
        "%H:%M:%S",
        "%H:%M",
    ]

    def _parse_datetime(self, value):
        for format in self._DATETIME_FORMATS:
            try:
                return datetime.datetime.strptime(value, format)
            except ValueError:
                pass
        raise Error('Unrecognized date/time format: %r' % value)

    _TIMEDELTA_ABBREVS = [
        ('hours', ['h']),
        ('minutes', ['m', 'min']),
        ('seconds', ['s', 'sec']),
        ('milliseconds', ['ms']),
        ('microseconds', ['us']),
        ('days', ['d']),
        ('weeks', ['w']),
    ]

    _TIMEDELTA_ABBREV_DICT = dict(
        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS
        for abbrev in abbrevs)

    _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'

    _TIMEDELTA_PATTERN = re.compile(
        r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)

    def _parse_timedelta(self, value):
        try:
            sum = datetime.timedelta()
            start = 0
            while start < len(value):
                m = self._TIMEDELTA_PATTERN.match(value, start)
                if not m:
                    raise Exception()
                num = float(m.group(1))
                units = m.group(2) or 'seconds'
                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
                sum += datetime.timedelta(**{units: num})
                start = m.end()
            return sum
        except Exception:
            raise

    def _parse_bool(self, value):
        return value.lower() not in ("false", "0", "f")

    def _parse_string(self, value):
        return _unicode(value)


options = OptionParser()
"""Global options object.

All defined options are available as attributes on this object.
"""


def define(name, default=None, type=None, help=None, metavar=None,
           multiple=False, group=None, callback=None):
    """Defines an option in the global namespace.

    See `OptionParser.define`.
    """
    return options.define(name, default=default, type=type, help=help,
                          metavar=metavar, multiple=multiple, group=group,
                          callback=callback)


def parse_command_line(args=None, final=True):
    """Parses global options from the command line.

    See `OptionParser.parse_command_line`.
    """
    return options.parse_command_line(args, final=final)


def parse_config_file(path, final=True):
    """Parses global options from a config file.

    See `OptionParser.parse_config_file`.
    """
    return options.parse_config_file(path, final=final)


def print_help(file=None):
    """Prints all the command line options to stderr (or another file).

    See `OptionParser.print_help`.
    """
    return options.print_help(file)


def add_parse_callback(callback):
    """Adds a parse callback, to be invoked when option parsing is done.

    See `OptionParser.add_parse_callback`
    """
    options.add_parse_callback(callback)


# Default options
define_logging_options(options)

```
--- 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:** `OptionParser` Missing `as_dict()` Method Causes AttributeError

**Description:**
When attempting to retrieve all defined options as a dictionary using the `as_dict()` method, an `AttributeError` is raised because the method does not exist. This prevents users from easily accessing all option names and their corresponding values in a single dictionary.

**Example Code:**
```python
options = OptionParser()
options.define('a', default=1)
options.define('b', default=2)
options.define('help', default='Help text')
options.as_dict()  # This line raises AttributeError
```

**Expected Behavior:**
Calling `as_dict()` on an `OptionParser` instance should return a dictionary of all option names and their values, such as:
```python
{'a': 1, 'b': 2, 'help': 'Help text'}
```

**Actual Behavior:**
An `AttributeError` is raised with the message:
```
AttributeError: Unrecognized option 'as_dict'
```
[/ISSUE]
{
    "OptionsTest.test_as_dict": "PASSED",
    "OptionsTest.test_getitem": "PASSED",
    "OptionsTest.test_group_dict": "PASSED",
    "OptionsTest.test_help": "PASSED",
    "OptionsTest.test_items": "PASSED",
    "OptionsTest.test_iter": "PASSED",
    "OptionsTest.test_mock_patch": "PASSED",
    "OptionsTest.test_multiple_int": "PASSED",
    "OptionsTest.test_multiple_string": "PASSED",
    "OptionsTest.test_parse_callbacks": "PASSED",
    "OptionsTest.test_parse_command_line": "PASSED",
    "OptionsTest.test_parse_config_file": "ERROR",
    "OptionsTest.test_setattr": "PASSED",
    "OptionsTest.test_setattr_type_check": "PASSED",
    "OptionsTest.test_setattr_with_callback": "PASSED",
    "OptionsTest.test_subcommand": "PASSED",
    "OptionsTest.test_types": "PASSED"
}
diff --git a/tornado/options.py b/tornado/options.py
index 6eefe6b4..04692f7a 100644
--- a/tornado/options.py
+++ b/tornado/options.py
@@ -115,11 +115,8 @@ class OptionParser(object):
         """The set of option-groups created by ``define``."""
         return set(opt.group_name for opt in self._options.values())
 
-    def group_dict(self, group=None):
-        """A dict of option names and values.
-
-        If ``group`` is given, get options only from the named group; otherwise
-        all options are included.
+    def group_dict(self, group):
+        """The names and values of options in a group.
 
         Useful for copying options into Application settings::
 
@@ -137,6 +134,11 @@ class OptionParser(object):
             (name, opt.value()) for name, opt in self._options.items()
             if not group or group == opt.group_name)
 
+    def as_dict(self):
+        """The names and values of all options."""
+        return dict(
+            (name, opt.value()) for name, opt in self._options.items())
+
     def define(self, name, default=None, type=None, help=None, metavar=None,
                multiple=False, group=None, callback=None):
         """Defines a new command line option.

{"tornado/options.py": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group=None):\n        \"\"\"A dict of option names and values.\n\n        If ``group`` is given, get options only from the named group; otherwise\n        all options are included.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\", name,\n                        self._options[name].file_name)\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item != None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value != None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\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:** `OptionParser` Missing `as_dict()` Method Causes AttributeError

**Description:**
When attempting to retrieve all defined options as a dictionary using the `as_dict()` method, an `AttributeError` is raised because the method does not exist. This prevents users from easily accessing all option names and their corresponding values in a single dictionary.

**Example Code:**
```python
options = OptionParser()
options.define('a', default=1)
options.define('b', default=2)
options.define('help', default='Help text')
options.as_dict()  # This line raises AttributeError
```

**Expected Behavior:**
Calling `as_dict()` on an `OptionParser` instance should return a dictionary of all option names and their values, such as:
```python
{'a': 1, 'b': 2, 'help': 'Help text'}
```

**Actual Behavior:**
An `AttributeError` is raised with the message:
```
AttributeError: Unrecognized option 'as_dict'
```
[/ISSUE]
--- END ISSUE ---

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

--- BEGIN FILE ---
```
### tornado/options.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A command line parsing module that lets modules define their own options.

Each module defines its own options which are added to the global
option namespace, e.g.::

    from tornado.options import define, options

    define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
    define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
           help="Main user memcache servers")

    def connect():
        db = database.Connection(options.mysql_host)
        ...

The ``main()`` method of your application does not need to be aware of all of
the options used throughout your program; they are all automatically loaded
when the modules are loaded.  However, all modules that define options
must have been imported before the command line is parsed.

Your ``main()`` method can parse the command line or parse a config file with
either::

    tornado.options.parse_command_line()
    # or
    tornado.options.parse_config_file("/etc/server.conf")

Command line formats are what you would expect (``--myoption=myvalue``).
Config files are just Python files. Global names become options, e.g.::

    myoption = "myvalue"
    myotheroption = "myothervalue"

We support `datetimes <datetime.datetime>`, `timedeltas
<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to
`define`). We also accept multi-value options. See the documentation for
`define()` below.

`tornado.options.options` is a singleton instance of `OptionParser`, and
the top-level functions in this module (`define`, `parse_command_line`, etc)
simply call methods on it.  You may create additional `OptionParser`
instances to define isolated sets of options, such as for subcommands.
"""

from __future__ import absolute_import, division, print_function, with_statement

import datetime
import numbers
import re
import sys
import os
import textwrap

from tornado.escape import _unicode
from tornado.log import define_logging_options
from tornado import stack_context
from tornado.util import basestring_type, exec_in


class Error(Exception):
    """Exception raised by errors in the options module."""
    pass


class OptionParser(object):
    """A collection of options, a dictionary with object-like access.

    Normally accessed via static functions in the `tornado.options` module,
    which reference a global instance.
    """
    def __init__(self):
        # we have to use self.__dict__ because we override setattr.
        self.__dict__['_options'] = {}
        self.__dict__['_parse_callbacks'] = []
        self.define("help", type=bool, help="show this help information",
                    callback=self._help_callback)

    def __getattr__(self, name):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].value()
        raise AttributeError("Unrecognized option %r" % name)

    def __setattr__(self, name, value):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].set(value)
        raise AttributeError("Unrecognized option %r" % name)

    def __iter__(self):
        return iter(self._options)

    def __getitem__(self, item):
        return self._options[item].value()

    def items(self):
        """A sequence of (name, value) pairs."""
        return [(name, opt.value()) for name, opt in self._options.items()]

    def groups(self):
        """The set of option-groups created by ``define``."""
        return set(opt.group_name for opt in self._options.values())

    def group_dict(self, group=None):
        """A dict of option names and values.

        If ``group`` is given, get options only from the named group; otherwise
        all options are included.

        Useful for copying options into Application settings::

            from tornado.options import define, parse_command_line, options

            define('template_path', group='application')
            define('static_path', group='application')

            parse_command_line()

            application = Application(
                handlers, **options.group_dict('application'))
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items()
            if not group or group == opt.group_name)

    def define(self, name, default=None, type=None, help=None, metavar=None,
               multiple=False, group=None, callback=None):
        """Defines a new command line option.

        If ``type`` is given (one of str, float, int, datetime, or timedelta)
        or can be inferred from the ``default``, we parse the command line
        arguments based on the given type. If ``multiple`` is True, we accept
        comma-separated values, and the option value is always a list.

        For multi-value integers, we also accept the syntax ``x:y``, which
        turns into ``range(x, y)`` - very useful for long integer ranges.

        ``help`` and ``metavar`` are used to construct the
        automatically generated command line help string. The help
        message is formatted like::

           --name=METAVAR      help string

        ``group`` is used to group the defined options in logical
        groups. By default, command line options are grouped by the
        file in which they are defined.

        Command line option names must be unique globally. They can be parsed
        from the command line with `parse_command_line` or parsed from a
        config file with `parse_config_file`.

        If a ``callback`` is given, it will be run with the new value whenever
        the option is changed.  This can be used to combine command-line
        and file-based options::

            define("config", type=str, help="path to config file",
                   callback=lambda path: parse_config_file(path, final=False))

        With this definition, options in the file specified by ``--config`` will
        override options set earlier on the command line, but can be overridden
        by later flags.
        """
        if name in self._options:
            raise Error("Option %r already defined in %s", name,
                        self._options[name].file_name)
        frame = sys._getframe(0)
        options_file = frame.f_code.co_filename
        file_name = frame.f_back.f_code.co_filename
        if file_name == options_file:
            file_name = ""
        if type is None:
            if not multiple and default is not None:
                type = default.__class__
            else:
                type = str
        if group:
            group_name = group
        else:
            group_name = file_name
        self._options[name] = _Option(name, file_name=file_name,
                                      default=default, type=type, help=help,
                                      metavar=metavar, multiple=multiple,
                                      group_name=group_name,
                                      callback=callback)

    def parse_command_line(self, args=None, final=True):
        """Parses all options given on the command line (defaults to
        `sys.argv`).

        Note that ``args[0]`` is ignored since it is the program name
        in `sys.argv`.

        We return a list of all arguments that are not parsed as options.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        if args is None:
            args = sys.argv
        remaining = []
        for i in range(1, len(args)):
            # All things after the last option are command line arguments
            if not args[i].startswith("-"):
                remaining = args[i:]
                break
            if args[i] == "--":
                remaining = args[i + 1:]
                break
            arg = args[i].lstrip("-")
            name, equals, value = arg.partition("=")
            name = name.replace('-', '_')
            if not name in self._options:
                self.print_help()
                raise Error('Unrecognized command line option: %r' % name)
            option = self._options[name]
            if not equals:
                if option.type == bool:
                    value = "true"
                else:
                    raise Error('Option %r requires a value' % name)
            option.parse(value)

        if final:
            self.run_parse_callbacks()

        return remaining

    def parse_config_file(self, path, final=True):
        """Parses and loads the Python config file at the given path.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        config = {}
        with open(path) as f:
            exec_in(f.read(), config, config)
        for name in config:
            if name in self._options:
                self._options[name].set(config[name])

        if final:
            self.run_parse_callbacks()

    def print_help(self, file=None):
        """Prints all the command line options to stderr (or another file)."""
        if file is None:
            file = sys.stderr
        print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
        print("\nOptions:\n", file=file)
        by_group = {}
        for option in self._options.values():
            by_group.setdefault(option.group_name, []).append(option)

        for filename, o in sorted(by_group.items()):
            if filename:
                print("\n%s options:\n" % os.path.normpath(filename), file=file)
            o.sort(key=lambda option: option.name)
            for option in o:
                prefix = option.name
                if option.metavar:
                    prefix += "=" + option.metavar
                description = option.help or ""
                if option.default is not None and option.default != '':
                    description += " (default %s)" % option.default
                lines = textwrap.wrap(description, 79 - 35)
                if len(prefix) > 30 or len(lines) == 0:
                    lines.insert(0, '')
                print("  --%-30s %s" % (prefix, lines[0]), file=file)
                for line in lines[1:]:
                    print("%-34s %s" % (' ', line), file=file)
        print(file=file)

    def _help_callback(self, value):
        if value:
            self.print_help()
            sys.exit(0)

    def add_parse_callback(self, callback):
        """Adds a parse callback, to be invoked when option parsing is done."""
        self._parse_callbacks.append(stack_context.wrap(callback))

    def run_parse_callbacks(self):
        for callback in self._parse_callbacks:
            callback()

    def mockable(self):
        """Returns a wrapper around self that is compatible with
        `mock.patch <unittest.mock.patch>`.

        The `mock.patch <unittest.mock.patch>` function (included in
        the standard library `unittest.mock` package since Python 3.3,
        or in the third-party ``mock`` package for older versions of
        Python) is incompatible with objects like ``options`` that
        override ``__getattr__`` and ``__setattr__``.  This function
        returns an object that can be used with `mock.patch.object
        <unittest.mock.patch.object>` to modify option values::

            with mock.patch.object(options.mockable(), 'name', value):
                assert options.name == value
        """
        return _Mockable(self)


class _Mockable(object):
    """`mock.patch` compatible wrapper for `OptionParser`.

    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
    the attribute it set instead of setting a new one (assuming that
    the object does not catpure ``__setattr__``, so the patch
    created a new attribute in ``__dict__``).

    _Mockable's getattr and setattr pass through to the underlying
    OptionParser, and delattr undoes the effect of a previous setattr.
    """
    def __init__(self, options):
        # Modify __dict__ directly to bypass __setattr__
        self.__dict__['_options'] = options
        self.__dict__['_originals'] = {}

    def __getattr__(self, name):
        return getattr(self._options, name)

    def __setattr__(self, name, value):
        assert name not in self._originals, "don't reuse mockable objects"
        self._originals[name] = getattr(self._options, name)
        setattr(self._options, name, value)

    def __delattr__(self, name):
        setattr(self._options, name, self._originals.pop(name))


class _Option(object):
    def __init__(self, name, default=None, type=basestring_type, help=None,
                 metavar=None, multiple=False, file_name=None, group_name=None,
                 callback=None):
        if default is None and multiple:
            default = []
        self.name = name
        self.type = type
        self.help = help
        self.metavar = metavar
        self.multiple = multiple
        self.file_name = file_name
        self.group_name = group_name
        self.callback = callback
        self.default = default
        self._value = None

    def value(self):
        return self.default if self._value is None else self._value

    def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()

    def set(self, value):
        if self.multiple:
            if not isinstance(value, list):
                raise Error("Option %r is required to be a list of %s" %
                            (self.name, self.type.__name__))
            for item in value:
                if item != None and not isinstance(item, self.type):
                    raise Error("Option %r is required to be a list of %s" %
                                (self.name, self.type.__name__))
        else:
            if value != None and not isinstance(value, self.type):
                raise Error("Option %r is required to be a %s (%s given)" %
                            (self.name, self.type.__name__, type(value)))
        self._value = value
        if self.callback is not None:
            self.callback(self._value)

    # Supported date/time formats in our options
    _DATETIME_FORMATS = [
        "%a %b %d %H:%M:%S %Y",
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%dT%H:%M",
        "%Y%m%d %H:%M:%S",
        "%Y%m%d %H:%M",
        "%Y-%m-%d",
        "%Y%m%d",
        "%H:%M:%S",
        "%H:%M",
    ]

    def _parse_datetime(self, value):
        for format in self._DATETIME_FORMATS:
            try:
                return datetime.datetime.strptime(value, format)
            except ValueError:
                pass
        raise Error('Unrecognized date/time format: %r' % value)

    _TIMEDELTA_ABBREVS = [
        ('hours', ['h']),
        ('minutes', ['m', 'min']),
        ('seconds', ['s', 'sec']),
        ('milliseconds', ['ms']),
        ('microseconds', ['us']),
        ('days', ['d']),
        ('weeks', ['w']),
    ]

    _TIMEDELTA_ABBREV_DICT = dict(
        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS
        for abbrev in abbrevs)

    _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'

    _TIMEDELTA_PATTERN = re.compile(
        r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)

    def _parse_timedelta(self, value):
        try:
            sum = datetime.timedelta()
            start = 0
            while start < len(value):
                m = self._TIMEDELTA_PATTERN.match(value, start)
                if not m:
                    raise Exception()
                num = float(m.group(1))
                units = m.group(2) or 'seconds'
                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
                sum += datetime.timedelta(**{units: num})
                start = m.end()
            return sum
        except Exception:
            raise

    def _parse_bool(self, value):
        return value.lower() not in ("false", "0", "f")

    def _parse_string(self, value):
        return _unicode(value)


options = OptionParser()
"""Global options object.

All defined options are available as attributes on this object.
"""


def define(name, default=None, type=None, help=None, metavar=None,
           multiple=False, group=None, callback=None):
    """Defines an option in the global namespace.

    See `OptionParser.define`.
    """
    return options.define(name, default=default, type=type, help=help,
                          metavar=metavar, multiple=multiple, group=group,
                          callback=callback)


def parse_command_line(args=None, final=True):
    """Parses global options from the command line.

    See `OptionParser.parse_command_line`.
    """
    return options.parse_command_line(args, final=final)


def parse_config_file(path, final=True):
    """Parses global options from a config file.

    See `OptionParser.parse_config_file`.
    """
    return options.parse_config_file(path, final=final)


def print_help(file=None):
    """Prints all the command line options to stderr (or another file).

    See `OptionParser.print_help`.
    """
    return options.print_help(file)


def add_parse_callback(callback):
    """Adds a parse callback, to be invoked when option parsing is done.

    See `OptionParser.add_parse_callback`
    """
    options.add_parse_callback(callback)


# Default options
define_logging_options(options)

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