{"prompt_id": 0, "project": "apimd", "module": "apimd.loader", "class": "", "method": "walk_packages", "focal_method_txt": "def walk_packages(name: str, path: str) -> Iterator[tuple[str, str]]:\n \"\"\"Walk packages without import them.\"\"\"\n path = abspath(path) + sep\n valid = (path + name, path + name + PEP561_SUFFIX)\n for root, _, fs in walk(path):\n for f in fs:\n if not f.endswith(('.py', '.pyi')):\n continue\n f_path = parent(join(root, f))\n if not f_path.startswith(valid):\n continue\n name = (f_path\n .removeprefix(path)\n .replace(PEP561_SUFFIX, \"\")\n .replace(sep, '.')\n .removesuffix('.__init__'))\n yield name, f_path", "focal_method_lines": [43, 59], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "PEP561_SUFFIX"], "type_context": "from typing import Optional\nfrom collections.abc import Sequence, Iterator\nfrom sys import path as sys_path\nfrom os import mkdir, walk\nfrom os.path import isdir, isfile, abspath, join, sep, dirname\nfrom importlib.abc import Loader\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom importlib.util import find_spec, spec_from_file_location, module_from_spec\nfrom .logger import logger\nfrom .parser import parent, Parser\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\nPEP561_SUFFIX = '-stubs'\n\ndef walk_packages(name: str, path: str) -> Iterator[tuple[str, str]]:\n \"\"\"Walk packages without import them.\"\"\"\n path = abspath(path) + sep\n valid = (path + name, path + name + PEP561_SUFFIX)\n for root, _, fs in walk(path):\n for f in fs:\n if not f.endswith(('.py', '.pyi')):\n continue\n f_path = parent(join(root, f))\n if not f_path.startswith(valid):\n continue\n name = (f_path\n .removeprefix(path)\n .replace(PEP561_SUFFIX, \"\")\n .replace(sep, '.')\n .removesuffix('.__init__'))\n yield name, f_path", "has_branch": true, "total_branches": 2} {"prompt_id": 1, "project": "apimd", "module": "apimd.loader", "class": "", "method": "loader", "focal_method_txt": "def loader(root: str, pwd: str, link: bool, level: int, toc: bool) -> str:\n \"\"\"Package searching algorithm.\"\"\"\n p = Parser.new(link, level, toc)\n for name, path in walk_packages(root, pwd):\n # Load its source or stub\n pure_py = False\n for ext in [\".py\", \".pyi\"]:\n path_ext = path + ext\n if not isfile(path_ext):\n continue\n logger.debug(f\"{name} <= {path_ext}\")\n p.parse(name, _read(path_ext))\n if ext == \".py\":\n pure_py = True\n if pure_py:\n continue\n logger.debug(f\"loading extension module for fully documented:\")\n # Try to load module here\n for ext in EXTENSION_SUFFIXES:\n path_ext = path + ext\n if not isfile(path_ext):\n continue\n logger.debug(f\"{name} <= {path_ext}\")\n if _load_module(name, path_ext, p):\n break\n else:\n logger.warning(f\"no module for {name} in this platform\")\n return p.compile()", "focal_method_lines": [78, 105], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "PEP561_SUFFIX"], "type_context": "from typing import Optional\nfrom collections.abc import Sequence, Iterator\nfrom sys import path as sys_path\nfrom os import mkdir, walk\nfrom os.path import isdir, isfile, abspath, join, sep, dirname\nfrom importlib.abc import Loader\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom importlib.util import find_spec, spec_from_file_location, module_from_spec\nfrom .logger import logger\nfrom .parser import parent, Parser\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\nPEP561_SUFFIX = '-stubs'\n\ndef loader(root: str, pwd: str, link: bool, level: int, toc: bool) -> str:\n \"\"\"Package searching algorithm.\"\"\"\n p = Parser.new(link, level, toc)\n for name, path in walk_packages(root, pwd):\n # Load its source or stub\n pure_py = False\n for ext in [\".py\", \".pyi\"]:\n path_ext = path + ext\n if not isfile(path_ext):\n continue\n logger.debug(f\"{name} <= {path_ext}\")\n p.parse(name, _read(path_ext))\n if ext == \".py\":\n pure_py = True\n if pure_py:\n continue\n logger.debug(f\"loading extension module for fully documented:\")\n # Try to load module here\n for ext in EXTENSION_SUFFIXES:\n path_ext = path + ext\n if not isfile(path_ext):\n continue\n logger.debug(f\"{name} <= {path_ext}\")\n if _load_module(name, path_ext, p):\n break\n else:\n logger.warning(f\"no module for {name} in this platform\")\n return p.compile()", "has_branch": true, "total_branches": 2} {"prompt_id": 2, "project": "apimd", "module": "apimd.parser", "class": "", "method": "is_public_family", "focal_method_txt": "def is_public_family(name: str) -> bool:\n \"\"\"Check the name is come from public modules or not.\"\"\"\n for n in name.split('.'):\n # Magic name\n if is_magic(n):\n continue\n # Local or private name\n if n.startswith('_'):\n return False\n return True", "focal_method_lines": [61, 70], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef is_public_family(name: str) -> bool:\n \"\"\"Check the name is come from public modules or not.\"\"\"\n for n in name.split('.'):\n # Magic name\n if is_magic(n):\n continue\n # Local or private name\n if n.startswith('_'):\n return False\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 3, "project": "apimd", "module": "apimd.parser", "class": "", "method": "walk_body", "focal_method_txt": "def walk_body(body: Sequence[stmt]) -> Iterator[stmt]:\n \"\"\"Traverse around body and its simple definition scope.\"\"\"\n for node in body:\n if isinstance(node, If):\n yield from walk_body(node.body)\n yield from walk_body(node.orelse)\n elif isinstance(node, Try):\n yield from walk_body(node.body)\n for h in node.handlers:\n yield from walk_body(h.body)\n yield from walk_body(node.orelse)\n yield from walk_body(node.finalbody)\n else:\n yield node", "focal_method_lines": [73, 86], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef walk_body(body: Sequence[stmt]) -> Iterator[stmt]:\n \"\"\"Traverse around body and its simple definition scope.\"\"\"\n for node in body:\n if isinstance(node, If):\n yield from walk_body(node.body)\n yield from walk_body(node.orelse)\n elif isinstance(node, Try):\n yield from walk_body(node.body)\n for h in node.handlers:\n yield from walk_body(h.body)\n yield from walk_body(node.orelse)\n yield from walk_body(node.finalbody)\n else:\n yield node", "has_branch": true, "total_branches": 2} {"prompt_id": 4, "project": "apimd", "module": "apimd.parser", "class": "", "method": "esc_underscore", "focal_method_txt": "def esc_underscore(doc: str) -> str:\n \"\"\"Escape underscore in names.\"\"\"\n if doc.count('_') > 1:\n return doc.replace('_', r\"\\_\")\n else:\n return doc", "focal_method_lines": [100, 105], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef esc_underscore(doc: str) -> str:\n \"\"\"Escape underscore in names.\"\"\"\n if doc.count('_') > 1:\n return doc.replace('_', r\"\\_\")\n else:\n return doc", "has_branch": true, "total_branches": 2} {"prompt_id": 5, "project": "apimd", "module": "apimd.parser", "class": "", "method": "doctest", "focal_method_txt": "def doctest(doc: str) -> str:\n \"\"\"Wrap doctest as markdown Python code.\"\"\"\n keep = False\n docs = []\n lines = doc.splitlines()\n for i, line in enumerate(lines):\n signed = line.startswith(\">>> \")\n if signed:\n if not keep:\n docs.append(\"```python\")\n keep = True\n elif keep:\n docs.append(\"```\")\n keep = False\n docs.append(line)\n if signed and i == len(lines) - 1:\n docs.append(\"```\")\n keep = False\n return '\\n'.join(docs)", "focal_method_lines": [108, 126], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef doctest(doc: str) -> str:\n \"\"\"Wrap doctest as markdown Python code.\"\"\"\n keep = False\n docs = []\n lines = doc.splitlines()\n for i, line in enumerate(lines):\n signed = line.startswith(\">>> \")\n if signed:\n if not keep:\n docs.append(\"```python\")\n keep = True\n elif keep:\n docs.append(\"```\")\n keep = False\n docs.append(line)\n if signed and i == len(lines) - 1:\n docs.append(\"```\")\n keep = False\n return '\\n'.join(docs)", "has_branch": true, "total_branches": 2} {"prompt_id": 6, "project": "apimd", "module": "apimd.parser", "class": "", "method": "table", "focal_method_txt": "def table(*titles: str, items: Iterable[Union[str, Iterable[str]]]) -> str:\n \"\"\"Create multi-column table with the titles.\n\n Usage:\n >>> table('a', 'b', [['c', 'd'], ['e', 'f']])\n | a | b |\n |:---:|:---:|\n | c | d |\n | e | f |\n \"\"\"\n return '\\n'.join([_table_cell(titles), _table_split(titles),\n '\\n'.join(_table_cell([n] if isinstance(n, str) else n)\n for n in items)]) + '\\n\\n'", "focal_method_lines": [140, 150], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef table(*titles: str, items: Iterable[Union[str, Iterable[str]]]) -> str:\n \"\"\"Create multi-column table with the titles.\n\n Usage:\n >>> table('a', 'b', [['c', 'd'], ['e', 'f']])\n | a | b |\n |:---:|:---:|\n | c | d |\n | e | f |\n \"\"\"\n return '\\n'.join([_table_cell(titles), _table_split(titles),\n '\\n'.join(_table_cell([n] if isinstance(n, str) else n)\n for n in items)]) + '\\n\\n'", "has_branch": false, "total_branches": 0} {"prompt_id": 7, "project": "apimd", "module": "apimd.parser", "class": "", "method": "const_type", "focal_method_txt": "def const_type(node: expr) -> str:\n \"\"\"Constant type inference.\"\"\"\n if isinstance(node, Constant):\n return _type_name(node.value)\n elif isinstance(node, (Tuple, List, Set)):\n return _type_name(node).lower() + _e_type(node.elts)\n elif isinstance(node, Dict):\n return 'dict' + _e_type(node.keys, node.values)\n elif isinstance(node, Call) and isinstance(node.func, (Name, Attribute)):\n func = unparse(node.func)\n if func in chain({'bool', 'int', 'float', 'complex', 'str'},\n PEP585.keys(), PEP585.values()):\n return func\n return ANY", "focal_method_lines": [181, 194], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\ndef const_type(node: expr) -> str:\n \"\"\"Constant type inference.\"\"\"\n if isinstance(node, Constant):\n return _type_name(node.value)\n elif isinstance(node, (Tuple, List, Set)):\n return _type_name(node).lower() + _e_type(node.elts)\n elif isinstance(node, Dict):\n return 'dict' + _e_type(node.keys, node.values)\n elif isinstance(node, Call) and isinstance(node.func, (Name, Attribute)):\n func = unparse(node.func)\n if func in chain({'bool', 'int', 'float', 'complex', 'str'},\n PEP585.keys(), PEP585.values()):\n return func\n return ANY", "has_branch": true, "total_branches": 2} {"prompt_id": 8, "project": "apimd", "module": "apimd.parser", "class": "Resolver", "method": "visit_Constant", "focal_method_txt": " def visit_Constant(self, node: Constant) -> AST:\n \"\"\"Check string is a name.\"\"\"\n if not isinstance(node.value, str):\n return node\n try:\n e = cast(Expr, parse(node.value).body[0])\n except SyntaxError:\n return node\n else:\n return self.visit(e.value)", "focal_method_lines": [207, 216], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\nclass Resolver(NodeTransformer):\n\n def __init__(self, root: str, alias: dict[str, str], self_ty: str = \"\"):\n \"\"\"Set root module, alias and generic self name.\"\"\"\n super(Resolver, self).__init__()\n self.root = root\n self.alias = alias\n self.self_ty = self_ty\n\n def visit_Constant(self, node: Constant) -> AST:\n \"\"\"Check string is a name.\"\"\"\n if not isinstance(node.value, str):\n return node\n try:\n e = cast(Expr, parse(node.value).body[0])\n except SyntaxError:\n return node\n else:\n return self.visit(e.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 9, "project": "apimd", "module": "apimd.parser", "class": "Resolver", "method": "visit_Name", "focal_method_txt": " def visit_Name(self, node: Name) -> AST:\n \"\"\"Replace global names with its expression recursively.\"\"\"\n if node.id == self.self_ty:\n return Name(\"Self\", Load())\n name = _m(self.root, node.id)\n if name in self.alias and name not in self.alias[name]:\n e = cast(Expr, parse(self.alias[name]).body[0])\n # Support `TypeVar`\n if isinstance(e.value, Call) and isinstance(e.value.func, Name):\n func_name = e.value.func.id\n idf = self.alias.get(_m(self.root, func_name), func_name)\n if idf == 'typing.TypeVar':\n return node\n return self.visit(e.value)\n else:\n return node", "focal_method_lines": [218, 233], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\nclass Resolver(NodeTransformer):\n\n def __init__(self, root: str, alias: dict[str, str], self_ty: str = \"\"):\n \"\"\"Set root module, alias and generic self name.\"\"\"\n super(Resolver, self).__init__()\n self.root = root\n self.alias = alias\n self.self_ty = self_ty\n\n def visit_Name(self, node: Name) -> AST:\n \"\"\"Replace global names with its expression recursively.\"\"\"\n if node.id == self.self_ty:\n return Name(\"Self\", Load())\n name = _m(self.root, node.id)\n if name in self.alias and name not in self.alias[name]:\n e = cast(Expr, parse(self.alias[name]).body[0])\n # Support `TypeVar`\n if isinstance(e.value, Call) and isinstance(e.value.func, Name):\n func_name = e.value.func.id\n idf = self.alias.get(_m(self.root, func_name), func_name)\n if idf == 'typing.TypeVar':\n return node\n return self.visit(e.value)\n else:\n return node", "has_branch": true, "total_branches": 2} {"prompt_id": 10, "project": "apimd", "module": "apimd.parser", "class": "Resolver", "method": "visit_Subscript", "focal_method_txt": " def visit_Subscript(self, node: Subscript) -> AST:\n \"\"\"Implementation of PEP585 and PEP604.\"\"\"\n if not isinstance(node.value, Name):\n return node\n name = node.value.id\n idf = self.alias.get(_m(self.root, name), name)\n if idf == 'typing.Union':\n if not isinstance(node.slice, Tuple):\n return node.slice\n b = node.slice.elts[0]\n for e in node.slice.elts[1:]:\n b = BinOp(b, BitOr(), e)\n return b\n elif idf == 'typing.Optional':\n return BinOp(node.slice, BitOr(), Constant(None))\n elif idf in PEP585:\n logger.warning(f\"{node.lineno}:{node.col_offset}: \"\n f\"find deprecated name {idf}, \"\n f\"recommended to use {PEP585[idf]}\")\n return Subscript(Name(PEP585[idf], Load), node.slice, node.ctx)\n else:\n return node", "focal_method_lines": [235, 256], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\nclass Resolver(NodeTransformer):\n\n def __init__(self, root: str, alias: dict[str, str], self_ty: str = \"\"):\n \"\"\"Set root module, alias and generic self name.\"\"\"\n super(Resolver, self).__init__()\n self.root = root\n self.alias = alias\n self.self_ty = self_ty\n\n def visit_Subscript(self, node: Subscript) -> AST:\n \"\"\"Implementation of PEP585 and PEP604.\"\"\"\n if not isinstance(node.value, Name):\n return node\n name = node.value.id\n idf = self.alias.get(_m(self.root, name), name)\n if idf == 'typing.Union':\n if not isinstance(node.slice, Tuple):\n return node.slice\n b = node.slice.elts[0]\n for e in node.slice.elts[1:]:\n b = BinOp(b, BitOr(), e)\n return b\n elif idf == 'typing.Optional':\n return BinOp(node.slice, BitOr(), Constant(None))\n elif idf in PEP585:\n logger.warning(f\"{node.lineno}:{node.col_offset}: \"\n f\"find deprecated name {idf}, \"\n f\"recommended to use {PEP585[idf]}\")\n return Subscript(Name(PEP585[idf], Load), node.slice, node.ctx)\n else:\n return node", "has_branch": true, "total_branches": 2} {"prompt_id": 11, "project": "apimd", "module": "apimd.parser", "class": "Resolver", "method": "visit_Attribute", "focal_method_txt": " def visit_Attribute(self, node: Attribute) -> AST:\n \"\"\"Remove `typing.*` prefix of annotation.\"\"\"\n if not isinstance(node.value, Name):\n return node\n if node.value.id == 'typing':\n return Name(node.attr, Load())\n else:\n return node", "focal_method_lines": [258, 265], "in_stack": false, "globals": ["__author__", "__copyright__", "__license__", "__email__", "_I", "_G", "_API", "ANY"], "type_context": "from typing import cast, TypeVar, Union, Optional\nfrom types import ModuleType\nfrom collections.abc import Sequence, Iterable, Iterator\nfrom itertools import chain\nfrom dataclasses import dataclass, field\nfrom inspect import getdoc\nfrom ast import (\n parse, unparse, get_docstring, AST, FunctionDef, AsyncFunctionDef, ClassDef,\n Assign, AnnAssign, Delete, Import, ImportFrom, Name, Expr, Subscript, BinOp,\n BitOr, Call, If, Try, Tuple, List, Set, Dict, Constant, Load, Attribute,\n arg, expr, stmt, arguments, NodeTransformer,\n)\nfrom .logger import logger\nfrom .pep585 import PEP585\n\n__author__ = \"Yuan Chang\"\n__copyright__ = \"Copyright (C) 2020-2021\"\n__license__ = \"MIT\"\n__email__ = \"pyslvs@gmail.com\"\n_I = Union[Import, ImportFrom]\n_G = Union[Assign, AnnAssign]\n_API = Union[FunctionDef, AsyncFunctionDef, ClassDef]\nANY = 'Any'\n\nclass Resolver(NodeTransformer):\n\n def __init__(self, root: str, alias: dict[str, str], self_ty: str = \"\"):\n \"\"\"Set root module, alias and generic self name.\"\"\"\n super(Resolver, self).__init__()\n self.root = root\n self.alias = alias\n self.self_ty = self_ty\n\n def visit_Attribute(self, node: Attribute) -> AST:\n \"\"\"Remove `typing.*` prefix of annotation.\"\"\"\n if not isinstance(node.value, Name):\n return node\n if node.value.id == 'typing':\n return Name(node.attr, Load())\n else:\n return node", "has_branch": true, "total_branches": 2} {"prompt_id": 12, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "apply", "focal_method_txt": " def apply(self, func: Callable[[List[float]], float], name: str) -> float:\n \"\"\"Apply a function to the results of one named timer\"\"\"\n if name in self._timings:\n return func(self._timings[name])\n raise KeyError(name)", "focal_method_lines": [41, 45], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def apply(self, func: Callable[[List[float]], float], name: str) -> float:\n \"\"\"Apply a function to the results of one named timer\"\"\"\n if name in self._timings:\n return func(self._timings[name])\n raise KeyError(name)", "has_branch": true, "total_branches": 2} {"prompt_id": 13, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "min", "focal_method_txt": " def min(self, name: str) -> float:\n \"\"\"Minimal value of timings\"\"\"\n return self.apply(lambda values: min(values or [0]), name=name)", "focal_method_lines": [55, 57], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def min(self, name: str) -> float:\n \"\"\"Minimal value of timings\"\"\"\n return self.apply(lambda values: min(values or [0]), name=name)", "has_branch": false, "total_branches": 0} {"prompt_id": 14, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "max", "focal_method_txt": " def max(self, name: str) -> float:\n \"\"\"Maximal value of timings\"\"\"\n return self.apply(lambda values: max(values or [0]), name=name)", "focal_method_lines": [59, 61], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def max(self, name: str) -> float:\n \"\"\"Maximal value of timings\"\"\"\n return self.apply(lambda values: max(values or [0]), name=name)", "has_branch": false, "total_branches": 0} {"prompt_id": 15, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "mean", "focal_method_txt": " def mean(self, name: str) -> float:\n \"\"\"Mean value of timings\"\"\"\n return self.apply(lambda values: statistics.mean(values or [0]), name=name)", "focal_method_lines": [63, 65], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def mean(self, name: str) -> float:\n \"\"\"Mean value of timings\"\"\"\n return self.apply(lambda values: statistics.mean(values or [0]), name=name)", "has_branch": false, "total_branches": 0} {"prompt_id": 16, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "median", "focal_method_txt": " def median(self, name: str) -> float:\n \"\"\"Median value of timings\"\"\"\n return self.apply(lambda values: statistics.median(values or [0]), name=name)", "focal_method_lines": [67, 69], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def median(self, name: str) -> float:\n \"\"\"Median value of timings\"\"\"\n return self.apply(lambda values: statistics.median(values or [0]), name=name)", "has_branch": false, "total_branches": 0} {"prompt_id": 17, "project": "codetiming", "module": "codetiming._timers", "class": "Timers", "method": "stdev", "focal_method_txt": " def stdev(self, name: str) -> float:\n \"\"\"Standard deviation of timings\"\"\"\n if name in self._timings:\n value = self._timings[name]\n return statistics.stdev(value) if len(value) >= 2 else math.nan\n raise KeyError(name)", "focal_method_lines": [71, 76], "in_stack": false, "globals": [], "type_context": "import collections\nimport math\nimport statistics\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List\n\n\n\nclass Timers(UserDict):\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Add a private dictionary keeping track of all timings\"\"\"\n super().__init__(*args, **kwargs)\n self._timings: Dict[str, List[float]] = collections.defaultdict(list)\n\n def stdev(self, name: str) -> float:\n \"\"\"Standard deviation of timings\"\"\"\n if name in self._timings:\n value = self._timings[name]\n return statistics.stdev(value) if len(value) >= 2 else math.nan\n raise KeyError(name)", "has_branch": true, "total_branches": 2} {"prompt_id": 18, "project": "cookiecutter", "module": "cookiecutter.find", "class": "", "method": "find_template", "focal_method_txt": "def find_template(repo_dir):\n \"\"\"Determine which child directory of `repo_dir` is the project template.\n\n :param repo_dir: Local directory of newly cloned repo.\n :returns project_template: Relative path to project template.\n \"\"\"\n logger.debug('Searching %s for the project template.', repo_dir)\n\n repo_dir_contents = os.listdir(repo_dir)\n\n project_template = None\n for item in repo_dir_contents:\n if 'cookiecutter' in item and '{{' in item and '}}' in item:\n project_template = item\n break\n\n if project_template:\n project_template = os.path.join(repo_dir, project_template)\n logger.debug('The project template appears to be %s', project_template)\n return project_template\n else:\n raise NonTemplatedInputDirException", "focal_method_lines": [9, 30], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport os\nfrom cookiecutter.exceptions import NonTemplatedInputDirException\n\nlogger = logging.getLogger(__name__)\n\ndef find_template(repo_dir):\n \"\"\"Determine which child directory of `repo_dir` is the project template.\n\n :param repo_dir: Local directory of newly cloned repo.\n :returns project_template: Relative path to project template.\n \"\"\"\n logger.debug('Searching %s for the project template.', repo_dir)\n\n repo_dir_contents = os.listdir(repo_dir)\n\n project_template = None\n for item in repo_dir_contents:\n if 'cookiecutter' in item and '{{' in item and '}}' in item:\n project_template = item\n break\n\n if project_template:\n project_template = os.path.join(repo_dir, project_template)\n logger.debug('The project template appears to be %s', project_template)\n return project_template\n else:\n raise NonTemplatedInputDirException", "has_branch": true, "total_branches": 2} {"prompt_id": 19, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "read_user_choice", "focal_method_txt": "def read_user_choice(var_name, options):\n \"\"\"Prompt the user to choose from several options for the given variable.\n\n The first item will be returned if no input happens.\n\n :param str var_name: Variable as specified in the context\n :param list options: Sequence of options that are available to select from\n :return: Exactly one item of ``options`` that has been chosen by the user\n \"\"\"\n # Please see https://click.palletsprojects.com/en/7.x/api/#click.prompt\n if not isinstance(options, list):\n raise TypeError\n\n if not options:\n raise ValueError\n\n choice_map = OrderedDict(\n ('{}'.format(i), value) for i, value in enumerate(options, 1)\n )\n choices = choice_map.keys()\n default = '1'\n\n choice_lines = ['{} - {}'.format(*c) for c in choice_map.items()]\n prompt = '\\n'.join(\n (\n 'Select {}:'.format(var_name),\n '\\n'.join(choice_lines),\n 'Choose from {}'.format(', '.join(choices)),\n )\n )\n\n user_choice = click.prompt(\n prompt, type=click.Choice(choices), default=default, show_choices=False\n )\n return choice_map[user_choice]", "focal_method_lines": [43, 77], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef read_user_choice(var_name, options):\n \"\"\"Prompt the user to choose from several options for the given variable.\n\n The first item will be returned if no input happens.\n\n :param str var_name: Variable as specified in the context\n :param list options: Sequence of options that are available to select from\n :return: Exactly one item of ``options`` that has been chosen by the user\n \"\"\"\n # Please see https://click.palletsprojects.com/en/7.x/api/#click.prompt\n if not isinstance(options, list):\n raise TypeError\n\n if not options:\n raise ValueError\n\n choice_map = OrderedDict(\n ('{}'.format(i), value) for i, value in enumerate(options, 1)\n )\n choices = choice_map.keys()\n default = '1'\n\n choice_lines = ['{} - {}'.format(*c) for c in choice_map.items()]\n prompt = '\\n'.join(\n (\n 'Select {}:'.format(var_name),\n '\\n'.join(choice_lines),\n 'Choose from {}'.format(', '.join(choices)),\n )\n )\n\n user_choice = click.prompt(\n prompt, type=click.Choice(choices), default=default, show_choices=False\n )\n return choice_map[user_choice]", "has_branch": true, "total_branches": 2} {"prompt_id": 20, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "process_json", "focal_method_txt": "def process_json(user_value):\n \"\"\"Load user-supplied value as a JSON dict.\n\n :param str user_value: User-supplied value to load as a JSON dict\n \"\"\"\n try:\n user_dict = json.loads(user_value, object_pairs_hook=OrderedDict)\n except Exception:\n # Leave it up to click to ask the user again\n raise click.UsageError('Unable to decode to JSON.')\n\n if not isinstance(user_dict, dict):\n # Leave it up to click to ask the user again\n raise click.UsageError('Requires JSON dict.')\n\n return user_dict", "focal_method_lines": [80, 95], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef process_json(user_value):\n \"\"\"Load user-supplied value as a JSON dict.\n\n :param str user_value: User-supplied value to load as a JSON dict\n \"\"\"\n try:\n user_dict = json.loads(user_value, object_pairs_hook=OrderedDict)\n except Exception:\n # Leave it up to click to ask the user again\n raise click.UsageError('Unable to decode to JSON.')\n\n if not isinstance(user_dict, dict):\n # Leave it up to click to ask the user again\n raise click.UsageError('Requires JSON dict.')\n\n return user_dict", "has_branch": true, "total_branches": 2} {"prompt_id": 21, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "read_user_dict", "focal_method_txt": "def read_user_dict(var_name, default_value):\n \"\"\"Prompt the user to provide a dictionary of data.\n\n :param str var_name: Variable as specified in the context\n :param default_value: Value that will be returned if no input is provided\n :return: A Python dictionary to use in the context.\n \"\"\"\n # Please see https://click.palletsprojects.com/en/7.x/api/#click.prompt\n if not isinstance(default_value, dict):\n raise TypeError\n\n default_display = 'default'\n\n user_value = click.prompt(\n var_name, default=default_display, type=click.STRING, value_proc=process_json\n )\n\n if user_value == default_display:\n # Return the given default w/o any processing\n return default_value\n return user_value", "focal_method_lines": [98, 118], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef read_user_dict(var_name, default_value):\n \"\"\"Prompt the user to provide a dictionary of data.\n\n :param str var_name: Variable as specified in the context\n :param default_value: Value that will be returned if no input is provided\n :return: A Python dictionary to use in the context.\n \"\"\"\n # Please see https://click.palletsprojects.com/en/7.x/api/#click.prompt\n if not isinstance(default_value, dict):\n raise TypeError\n\n default_display = 'default'\n\n user_value = click.prompt(\n var_name, default=default_display, type=click.STRING, value_proc=process_json\n )\n\n if user_value == default_display:\n # Return the given default w/o any processing\n return default_value\n return user_value", "has_branch": true, "total_branches": 2} {"prompt_id": 22, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "render_variable", "focal_method_txt": "def render_variable(env, raw, cookiecutter_dict):\n \"\"\"Render the next variable to be displayed in the user prompt.\n\n Inside the prompting taken from the cookiecutter.json file, this renders\n the next variable. For example, if a project_name is \"Peanut Butter\n Cookie\", the repo_name could be be rendered with:\n\n `{{ cookiecutter.project_name.replace(\" \", \"_\") }}`.\n\n This is then presented to the user as the default.\n\n :param Environment env: A Jinja2 Environment object.\n :param raw: The next value to be prompted for by the user.\n :param dict cookiecutter_dict: The current context as it's gradually\n being populated with variables.\n :return: The rendered value for the default variable.\n \"\"\"\n if raw is None:\n return None\n elif isinstance(raw, dict):\n return {\n render_variable(env, k, cookiecutter_dict): render_variable(\n env, v, cookiecutter_dict\n )\n for k, v in raw.items()\n }\n elif isinstance(raw, list):\n return [render_variable(env, v, cookiecutter_dict) for v in raw]\n elif not isinstance(raw, str):\n raw = str(raw)\n\n template = env.from_string(raw)\n\n rendered_template = template.render(cookiecutter=cookiecutter_dict)\n return rendered_template", "focal_method_lines": [121, 155], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef render_variable(env, raw, cookiecutter_dict):\n \"\"\"Render the next variable to be displayed in the user prompt.\n\n Inside the prompting taken from the cookiecutter.json file, this renders\n the next variable. For example, if a project_name is \"Peanut Butter\n Cookie\", the repo_name could be be rendered with:\n\n `{{ cookiecutter.project_name.replace(\" \", \"_\") }}`.\n\n This is then presented to the user as the default.\n\n :param Environment env: A Jinja2 Environment object.\n :param raw: The next value to be prompted for by the user.\n :param dict cookiecutter_dict: The current context as it's gradually\n being populated with variables.\n :return: The rendered value for the default variable.\n \"\"\"\n if raw is None:\n return None\n elif isinstance(raw, dict):\n return {\n render_variable(env, k, cookiecutter_dict): render_variable(\n env, v, cookiecutter_dict\n )\n for k, v in raw.items()\n }\n elif isinstance(raw, list):\n return [render_variable(env, v, cookiecutter_dict) for v in raw]\n elif not isinstance(raw, str):\n raw = str(raw)\n\n template = env.from_string(raw)\n\n rendered_template = template.render(cookiecutter=cookiecutter_dict)\n return rendered_template", "has_branch": true, "total_branches": 2} {"prompt_id": 23, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "prompt_choice_for_config", "focal_method_txt": "def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input):\n \"\"\"Prompt user with a set of options to choose from.\n\n Each of the possible choices is rendered beforehand.\n \"\"\"\n rendered_options = [render_variable(env, raw, cookiecutter_dict) for raw in options]\n\n if no_input:\n return rendered_options[0]\n return read_user_choice(key, rendered_options)", "focal_method_lines": [158, 167], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input):\n \"\"\"Prompt user with a set of options to choose from.\n\n Each of the possible choices is rendered beforehand.\n \"\"\"\n rendered_options = [render_variable(env, raw, cookiecutter_dict) for raw in options]\n\n if no_input:\n return rendered_options[0]\n return read_user_choice(key, rendered_options)", "has_branch": true, "total_branches": 2} {"prompt_id": 24, "project": "cookiecutter", "module": "cookiecutter.prompt", "class": "", "method": "prompt_for_config", "focal_method_txt": "def prompt_for_config(context, no_input=False):\n \"\"\"Prompt user to enter a new config.\n\n :param dict context: Source for field names and sample values.\n :param no_input: Prompt the user at command line for manual configuration?\n \"\"\"\n cookiecutter_dict = OrderedDict([])\n env = StrictEnvironment(context=context)\n\n # First pass: Handle simple and raw variables, plus choices.\n # These must be done first because the dictionaries keys and\n # values might refer to them.\n for key, raw in context['cookiecutter'].items():\n if key.startswith('_') and not key.startswith('__'):\n cookiecutter_dict[key] = raw\n continue\n elif key.startswith('__'):\n cookiecutter_dict[key] = render_variable(env, raw, cookiecutter_dict)\n continue\n\n try:\n if isinstance(raw, list):\n # We are dealing with a choice variable\n val = prompt_choice_for_config(\n cookiecutter_dict, env, key, raw, no_input\n )\n cookiecutter_dict[key] = val\n elif not isinstance(raw, dict):\n # We are dealing with a regular variable\n val = render_variable(env, raw, cookiecutter_dict)\n\n if not no_input:\n val = read_user_variable(key, val)\n\n cookiecutter_dict[key] = val\n except UndefinedError as err:\n msg = \"Unable to render variable '{}'\".format(key)\n raise UndefinedVariableInTemplate(msg, err, context)\n\n # Second pass; handle the dictionaries.\n for key, raw in context['cookiecutter'].items():\n # Skip private type dicts not ot be rendered.\n if key.startswith('_') and not key.startswith('__'):\n continue\n\n try:\n if isinstance(raw, dict):\n # We are dealing with a dict variable\n val = render_variable(env, raw, cookiecutter_dict)\n\n if not no_input and not key.startswith('__'):\n val = read_user_dict(key, val)\n\n cookiecutter_dict[key] = val\n except UndefinedError as err:\n msg = \"Unable to render variable '{}'\".format(key)\n raise UndefinedVariableInTemplate(msg, err, context)\n\n return cookiecutter_dict", "focal_method_lines": [170, 228], "in_stack": false, "globals": [], "type_context": "import json\nfrom collections import OrderedDict\nimport click\nfrom jinja2.exceptions import UndefinedError\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.exceptions import UndefinedVariableInTemplate\n\n\n\ndef prompt_for_config(context, no_input=False):\n \"\"\"Prompt user to enter a new config.\n\n :param dict context: Source for field names and sample values.\n :param no_input: Prompt the user at command line for manual configuration?\n \"\"\"\n cookiecutter_dict = OrderedDict([])\n env = StrictEnvironment(context=context)\n\n # First pass: Handle simple and raw variables, plus choices.\n # These must be done first because the dictionaries keys and\n # values might refer to them.\n for key, raw in context['cookiecutter'].items():\n if key.startswith('_') and not key.startswith('__'):\n cookiecutter_dict[key] = raw\n continue\n elif key.startswith('__'):\n cookiecutter_dict[key] = render_variable(env, raw, cookiecutter_dict)\n continue\n\n try:\n if isinstance(raw, list):\n # We are dealing with a choice variable\n val = prompt_choice_for_config(\n cookiecutter_dict, env, key, raw, no_input\n )\n cookiecutter_dict[key] = val\n elif not isinstance(raw, dict):\n # We are dealing with a regular variable\n val = render_variable(env, raw, cookiecutter_dict)\n\n if not no_input:\n val = read_user_variable(key, val)\n\n cookiecutter_dict[key] = val\n except UndefinedError as err:\n msg = \"Unable to render variable '{}'\".format(key)\n raise UndefinedVariableInTemplate(msg, err, context)\n\n # Second pass; handle the dictionaries.\n for key, raw in context['cookiecutter'].items():\n # Skip private type dicts not ot be rendered.\n if key.startswith('_') and not key.startswith('__'):\n continue\n\n try:\n if isinstance(raw, dict):\n # We are dealing with a dict variable\n val = render_variable(env, raw, cookiecutter_dict)\n\n if not no_input and not key.startswith('__'):\n val = read_user_dict(key, val)\n\n cookiecutter_dict[key] = val\n except UndefinedError as err:\n msg = \"Unable to render variable '{}'\".format(key)\n raise UndefinedVariableInTemplate(msg, err, context)\n\n return cookiecutter_dict", "has_branch": true, "total_branches": 2} {"prompt_id": 25, "project": "cookiecutter", "module": "cookiecutter.replay", "class": "", "method": "get_file_name", "focal_method_txt": "def get_file_name(replay_dir, template_name):\n \"\"\"Get the name of file.\"\"\"\n suffix = '.json' if not template_name.endswith('.json') else ''\n file_name = '{}{}'.format(template_name, suffix)\n return os.path.join(replay_dir, file_name)", "focal_method_lines": [11, 15], "in_stack": false, "globals": [], "type_context": "import json\nimport os\nfrom cookiecutter.utils import make_sure_path_exists\n\n\n\ndef get_file_name(replay_dir, template_name):\n \"\"\"Get the name of file.\"\"\"\n suffix = '.json' if not template_name.endswith('.json') else ''\n file_name = '{}{}'.format(template_name, suffix)\n return os.path.join(replay_dir, file_name)", "has_branch": false, "total_branches": 0} {"prompt_id": 26, "project": "cookiecutter", "module": "cookiecutter.replay", "class": "", "method": "dump", "focal_method_txt": "def dump(replay_dir, template_name, context):\n \"\"\"Write json data to file.\"\"\"\n if not make_sure_path_exists(replay_dir):\n raise IOError('Unable to create replay dir at {}'.format(replay_dir))\n\n if not isinstance(template_name, str):\n raise TypeError('Template name is required to be of type str')\n\n if not isinstance(context, dict):\n raise TypeError('Context is required to be of type dict')\n\n if 'cookiecutter' not in context:\n raise ValueError('Context is required to contain a cookiecutter key')\n\n replay_file = get_file_name(replay_dir, template_name)\n\n with open(replay_file, 'w') as outfile:\n json.dump(context, outfile, indent=2)", "focal_method_lines": [18, 35], "in_stack": false, "globals": [], "type_context": "import json\nimport os\nfrom cookiecutter.utils import make_sure_path_exists\n\n\n\ndef dump(replay_dir, template_name, context):\n \"\"\"Write json data to file.\"\"\"\n if not make_sure_path_exists(replay_dir):\n raise IOError('Unable to create replay dir at {}'.format(replay_dir))\n\n if not isinstance(template_name, str):\n raise TypeError('Template name is required to be of type str')\n\n if not isinstance(context, dict):\n raise TypeError('Context is required to be of type dict')\n\n if 'cookiecutter' not in context:\n raise ValueError('Context is required to contain a cookiecutter key')\n\n replay_file = get_file_name(replay_dir, template_name)\n\n with open(replay_file, 'w') as outfile:\n json.dump(context, outfile, indent=2)", "has_branch": true, "total_branches": 2} {"prompt_id": 27, "project": "cookiecutter", "module": "cookiecutter.replay", "class": "", "method": "load", "focal_method_txt": "def load(replay_dir, template_name):\n \"\"\"Read json data from file.\"\"\"\n if not isinstance(template_name, str):\n raise TypeError('Template name is required to be of type str')\n\n replay_file = get_file_name(replay_dir, template_name)\n\n with open(replay_file, 'r') as infile:\n context = json.load(infile)\n\n if 'cookiecutter' not in context:\n raise ValueError('Context is required to contain a cookiecutter key')\n\n return context", "focal_method_lines": [38, 51], "in_stack": false, "globals": [], "type_context": "import json\nimport os\nfrom cookiecutter.utils import make_sure_path_exists\n\n\n\ndef load(replay_dir, template_name):\n \"\"\"Read json data from file.\"\"\"\n if not isinstance(template_name, str):\n raise TypeError('Template name is required to be of type str')\n\n replay_file = get_file_name(replay_dir, template_name)\n\n with open(replay_file, 'r') as infile:\n context = json.load(infile)\n\n if 'cookiecutter' not in context:\n raise ValueError('Context is required to contain a cookiecutter key')\n\n return context", "has_branch": true, "total_branches": 2} {"prompt_id": 28, "project": "cookiecutter", "module": "cookiecutter.repository", "class": "", "method": "expand_abbreviations", "focal_method_txt": "def expand_abbreviations(template, abbreviations):\n \"\"\"Expand abbreviations in a template name.\n\n :param template: The project template name.\n :param abbreviations: Abbreviation definitions.\n \"\"\"\n if template in abbreviations:\n return abbreviations[template]\n\n # Split on colon. If there is no colon, rest will be empty\n # and prefix will be the whole template\n prefix, sep, rest = template.partition(':')\n if prefix in abbreviations:\n return abbreviations[prefix].format(rest)\n\n return template", "focal_method_lines": [30, 45], "in_stack": false, "globals": ["REPO_REGEX"], "type_context": "import os\nimport re\nfrom cookiecutter.exceptions import RepositoryNotFound\nfrom cookiecutter.vcs import clone\nfrom cookiecutter.zipfile import unzip\n\nREPO_REGEX = re.compile(\n r\"\"\"\n# something like git:// ssh:// file:// etc.\n((((git|hg)\\+)?(git|ssh|file|https?):(//)?)\n | # or\n (\\w+@[\\w\\.]+) # something like user@...\n)\n\"\"\",\n re.VERBOSE,\n)\n\ndef expand_abbreviations(template, abbreviations):\n \"\"\"Expand abbreviations in a template name.\n\n :param template: The project template name.\n :param abbreviations: Abbreviation definitions.\n \"\"\"\n if template in abbreviations:\n return abbreviations[template]\n\n # Split on colon. If there is no colon, rest will be empty\n # and prefix will be the whole template\n prefix, sep, rest = template.partition(':')\n if prefix in abbreviations:\n return abbreviations[prefix].format(rest)\n\n return template", "has_branch": true, "total_branches": 2} {"prompt_id": 29, "project": "cookiecutter", "module": "cookiecutter.repository", "class": "", "method": "repository_has_cookiecutter_json", "focal_method_txt": "def repository_has_cookiecutter_json(repo_directory):\n \"\"\"Determine if `repo_directory` contains a `cookiecutter.json` file.\n\n :param repo_directory: The candidate repository directory.\n :return: True if the `repo_directory` is valid, else False.\n \"\"\"\n repo_directory_exists = os.path.isdir(repo_directory)\n\n repo_config_exists = os.path.isfile(\n os.path.join(repo_directory, 'cookiecutter.json')\n )\n return repo_directory_exists and repo_config_exists", "focal_method_lines": [48, 59], "in_stack": false, "globals": ["REPO_REGEX"], "type_context": "import os\nimport re\nfrom cookiecutter.exceptions import RepositoryNotFound\nfrom cookiecutter.vcs import clone\nfrom cookiecutter.zipfile import unzip\n\nREPO_REGEX = re.compile(\n r\"\"\"\n# something like git:// ssh:// file:// etc.\n((((git|hg)\\+)?(git|ssh|file|https?):(//)?)\n | # or\n (\\w+@[\\w\\.]+) # something like user@...\n)\n\"\"\",\n re.VERBOSE,\n)\n\ndef repository_has_cookiecutter_json(repo_directory):\n \"\"\"Determine if `repo_directory` contains a `cookiecutter.json` file.\n\n :param repo_directory: The candidate repository directory.\n :return: True if the `repo_directory` is valid, else False.\n \"\"\"\n repo_directory_exists = os.path.isdir(repo_directory)\n\n repo_config_exists = os.path.isfile(\n os.path.join(repo_directory, 'cookiecutter.json')\n )\n return repo_directory_exists and repo_config_exists", "has_branch": false, "total_branches": 0} {"prompt_id": 30, "project": "cookiecutter", "module": "cookiecutter.repository", "class": "", "method": "determine_repo_dir", "focal_method_txt": "def determine_repo_dir(\n template,\n abbreviations,\n clone_to_dir,\n checkout,\n no_input,\n password=None,\n directory=None,\n):\n \"\"\"\n Locate the repository directory from a template reference.\n\n Applies repository abbreviations to the template reference.\n If the template refers to a repository URL, clone it.\n If the template is a path to a local repository, use it.\n\n :param template: A directory containing a project template directory,\n or a URL to a git repository.\n :param abbreviations: A dictionary of repository abbreviation\n definitions.\n :param clone_to_dir: The directory to clone the repository into.\n :param checkout: The branch, tag or commit ID to checkout after clone.\n :param no_input: Prompt the user at command line for manual configuration?\n :param password: The password to use when extracting the repository.\n :param directory: Directory within repo where cookiecutter.json lives.\n :return: A tuple containing the cookiecutter template directory, and\n a boolean descriving whether that directory should be cleaned up\n after the template has been instantiated.\n :raises: `RepositoryNotFound` if a repository directory could not be found.\n \"\"\"\n template = expand_abbreviations(template, abbreviations)\n\n if is_zip_file(template):\n unzipped_dir = unzip(\n zip_uri=template,\n is_url=is_repo_url(template),\n clone_to_dir=clone_to_dir,\n no_input=no_input,\n password=password,\n )\n repository_candidates = [unzipped_dir]\n cleanup = True\n elif is_repo_url(template):\n cloned_repo = clone(\n repo_url=template,\n checkout=checkout,\n clone_to_dir=clone_to_dir,\n no_input=no_input,\n )\n repository_candidates = [cloned_repo]\n cleanup = False\n else:\n repository_candidates = [template, os.path.join(clone_to_dir, template)]\n cleanup = False\n\n if directory:\n repository_candidates = [\n os.path.join(s, directory) for s in repository_candidates\n ]\n\n for repo_candidate in repository_candidates:\n if repository_has_cookiecutter_json(repo_candidate):\n return repo_candidate, cleanup\n\n raise RepositoryNotFound(\n 'A valid repository for \"{}\" could not be found in the following '\n 'locations:\\n{}'.format(template, '\\n'.join(repository_candidates))\n )", "focal_method_lines": [62, 126], "in_stack": false, "globals": ["REPO_REGEX"], "type_context": "import os\nimport re\nfrom cookiecutter.exceptions import RepositoryNotFound\nfrom cookiecutter.vcs import clone\nfrom cookiecutter.zipfile import unzip\n\nREPO_REGEX = re.compile(\n r\"\"\"\n# something like git:// ssh:// file:// etc.\n((((git|hg)\\+)?(git|ssh|file|https?):(//)?)\n | # or\n (\\w+@[\\w\\.]+) # something like user@...\n)\n\"\"\",\n re.VERBOSE,\n)\n\ndef determine_repo_dir(\n template,\n abbreviations,\n clone_to_dir,\n checkout,\n no_input,\n password=None,\n directory=None,\n):\n \"\"\"\n Locate the repository directory from a template reference.\n\n Applies repository abbreviations to the template reference.\n If the template refers to a repository URL, clone it.\n If the template is a path to a local repository, use it.\n\n :param template: A directory containing a project template directory,\n or a URL to a git repository.\n :param abbreviations: A dictionary of repository abbreviation\n definitions.\n :param clone_to_dir: The directory to clone the repository into.\n :param checkout: The branch, tag or commit ID to checkout after clone.\n :param no_input: Prompt the user at command line for manual configuration?\n :param password: The password to use when extracting the repository.\n :param directory: Directory within repo where cookiecutter.json lives.\n :return: A tuple containing the cookiecutter template directory, and\n a boolean descriving whether that directory should be cleaned up\n after the template has been instantiated.\n :raises: `RepositoryNotFound` if a repository directory could not be found.\n \"\"\"\n template = expand_abbreviations(template, abbreviations)\n\n if is_zip_file(template):\n unzipped_dir = unzip(\n zip_uri=template,\n is_url=is_repo_url(template),\n clone_to_dir=clone_to_dir,\n no_input=no_input,\n password=password,\n )\n repository_candidates = [unzipped_dir]\n cleanup = True\n elif is_repo_url(template):\n cloned_repo = clone(\n repo_url=template,\n checkout=checkout,\n clone_to_dir=clone_to_dir,\n no_input=no_input,\n )\n repository_candidates = [cloned_repo]\n cleanup = False\n else:\n repository_candidates = [template, os.path.join(clone_to_dir, template)]\n cleanup = False\n\n if directory:\n repository_candidates = [\n os.path.join(s, directory) for s in repository_candidates\n ]\n\n for repo_candidate in repository_candidates:\n if repository_has_cookiecutter_json(repo_candidate):\n return repo_candidate, cleanup\n\n raise RepositoryNotFound(\n 'A valid repository for \"{}\" could not be found in the following '\n 'locations:\\n{}'.format(template, '\\n'.join(repository_candidates))\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 31, "project": "cookiecutter", "module": "cookiecutter.zipfile", "class": "", "method": "unzip", "focal_method_txt": "def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None):\n \"\"\"Download and unpack a zipfile at a given URI.\n\n This will download the zipfile to the cookiecutter repository,\n and unpack into a temporary directory.\n\n :param zip_uri: The URI for the zipfile.\n :param is_url: Is the zip URI a URL or a file?\n :param clone_to_dir: The cookiecutter repository directory\n to put the archive into.\n :param no_input: Suppress any prompts\n :param password: The password to use when unpacking the repository.\n \"\"\"\n # Ensure that clone_to_dir exists\n clone_to_dir = os.path.expanduser(clone_to_dir)\n make_sure_path_exists(clone_to_dir)\n\n if is_url:\n # Build the name of the cached zipfile,\n # and prompt to delete if it already exists.\n identifier = zip_uri.rsplit('/', 1)[1]\n zip_path = os.path.join(clone_to_dir, identifier)\n\n if os.path.exists(zip_path):\n download = prompt_and_delete(zip_path, no_input=no_input)\n else:\n download = True\n\n if download:\n # (Re) download the zipfile\n r = requests.get(zip_uri, stream=True)\n with open(zip_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n else:\n # Just use the local zipfile as-is.\n zip_path = os.path.abspath(zip_uri)\n\n # Now unpack the repository. The zipfile will be unpacked\n # into a temporary directory\n try:\n zip_file = ZipFile(zip_path)\n\n if len(zip_file.namelist()) == 0:\n raise InvalidZipRepository('Zip repository {} is empty'.format(zip_uri))\n\n # The first record in the zipfile should be the directory entry for\n # the archive. If it isn't a directory, there's a problem.\n first_filename = zip_file.namelist()[0]\n if not first_filename.endswith('/'):\n raise InvalidZipRepository(\n 'Zip repository {} does not include '\n 'a top-level directory'.format(zip_uri)\n )\n\n # Construct the final target directory\n project_name = first_filename[:-1]\n unzip_base = tempfile.mkdtemp()\n unzip_path = os.path.join(unzip_base, project_name)\n\n # Extract the zip file into the temporary directory\n try:\n zip_file.extractall(path=unzip_base)\n except RuntimeError:\n # File is password protected; try to get a password from the\n # environment; if that doesn't work, ask the user.\n if password is not None:\n try:\n zip_file.extractall(path=unzip_base, pwd=password.encode('utf-8'))\n except RuntimeError:\n raise InvalidZipRepository(\n 'Invalid password provided for protected repository'\n )\n elif no_input:\n raise InvalidZipRepository(\n 'Unable to unlock password protected repository'\n )\n else:\n retry = 0\n while retry is not None:\n try:\n password = read_repo_password('Repo password')\n zip_file.extractall(\n path=unzip_base, pwd=password.encode('utf-8')\n )\n retry = None\n except RuntimeError:\n retry += 1\n if retry == 3:\n raise InvalidZipRepository(\n 'Invalid password provided for protected repository'\n )\n\n except BadZipFile:\n raise InvalidZipRepository(\n 'Zip repository {} is not a valid zip archive:'.format(zip_uri)\n )\n\n return unzip_path", "focal_method_lines": [12, 111], "in_stack": false, "globals": [], "type_context": "import os\nimport tempfile\nfrom zipfile import BadZipFile, ZipFile\nimport requests\nfrom cookiecutter.exceptions import InvalidZipRepository\nfrom cookiecutter.prompt import read_repo_password\nfrom cookiecutter.utils import make_sure_path_exists, prompt_and_delete\n\n\n\ndef unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None):\n \"\"\"Download and unpack a zipfile at a given URI.\n\n This will download the zipfile to the cookiecutter repository,\n and unpack into a temporary directory.\n\n :param zip_uri: The URI for the zipfile.\n :param is_url: Is the zip URI a URL or a file?\n :param clone_to_dir: The cookiecutter repository directory\n to put the archive into.\n :param no_input: Suppress any prompts\n :param password: The password to use when unpacking the repository.\n \"\"\"\n # Ensure that clone_to_dir exists\n clone_to_dir = os.path.expanduser(clone_to_dir)\n make_sure_path_exists(clone_to_dir)\n\n if is_url:\n # Build the name of the cached zipfile,\n # and prompt to delete if it already exists.\n identifier = zip_uri.rsplit('/', 1)[1]\n zip_path = os.path.join(clone_to_dir, identifier)\n\n if os.path.exists(zip_path):\n download = prompt_and_delete(zip_path, no_input=no_input)\n else:\n download = True\n\n if download:\n # (Re) download the zipfile\n r = requests.get(zip_uri, stream=True)\n with open(zip_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n else:\n # Just use the local zipfile as-is.\n zip_path = os.path.abspath(zip_uri)\n\n # Now unpack the repository. The zipfile will be unpacked\n # into a temporary directory\n try:\n zip_file = ZipFile(zip_path)\n\n if len(zip_file.namelist()) == 0:\n raise InvalidZipRepository('Zip repository {} is empty'.format(zip_uri))\n\n # The first record in the zipfile should be the directory entry for\n # the archive. If it isn't a directory, there's a problem.\n first_filename = zip_file.namelist()[0]\n if not first_filename.endswith('/'):\n raise InvalidZipRepository(\n 'Zip repository {} does not include '\n 'a top-level directory'.format(zip_uri)\n )\n\n # Construct the final target directory\n project_name = first_filename[:-1]\n unzip_base = tempfile.mkdtemp()\n unzip_path = os.path.join(unzip_base, project_name)\n\n # Extract the zip file into the temporary directory\n try:\n zip_file.extractall(path=unzip_base)\n except RuntimeError:\n # File is password protected; try to get a password from the\n # environment; if that doesn't work, ask the user.\n if password is not None:\n try:\n zip_file.extractall(path=unzip_base, pwd=password.encode('utf-8'))\n except RuntimeError:\n raise InvalidZipRepository(\n 'Invalid password provided for protected repository'\n )\n elif no_input:\n raise InvalidZipRepository(\n 'Unable to unlock password protected repository'\n )\n else:\n retry = 0\n while retry is not None:\n try:\n password = read_repo_password('Repo password')\n zip_file.extractall(\n path=unzip_base, pwd=password.encode('utf-8')\n )\n retry = None\n except RuntimeError:\n retry += 1\n if retry == 3:\n raise InvalidZipRepository(\n 'Invalid password provided for protected repository'\n )\n\n except BadZipFile:\n raise InvalidZipRepository(\n 'Zip repository {} is not a valid zip archive:'.format(zip_uri)\n )\n\n return unzip_path", "has_branch": true, "total_branches": 2} {"prompt_id": 32, "project": "dataclasses_json", "module": "dataclasses_json.cfg", "class": "", "method": "config", "focal_method_txt": "def config(metadata: dict = None, *,\n # TODO: these can be typed more precisely\n # Specifically, a Callable[A, B], where `B` is bound as a JSON type\n encoder: Callable = None,\n decoder: Callable = None,\n mm_field: MarshmallowField = None,\n letter_case: Callable[[str], str] = None,\n undefined: Optional[Union[str, Undefined]] = None,\n field_name: str = None,\n exclude: Optional[Callable[[str, T], bool]] = None,\n ) -> Dict[str, dict]:\n if metadata is None:\n metadata = {}\n\n lib_metadata = metadata.setdefault('dataclasses_json', {})\n\n if encoder is not None:\n lib_metadata['encoder'] = encoder\n\n if decoder is not None:\n lib_metadata['decoder'] = decoder\n\n if mm_field is not None:\n lib_metadata['mm_field'] = mm_field\n\n if field_name is not None:\n if letter_case is not None:\n @functools.wraps(letter_case)\n def override(_, _letter_case=letter_case, _field_name=field_name):\n return _letter_case(_field_name)\n else:\n def override(_, _field_name=field_name):\n return _field_name\n letter_case = override\n\n if letter_case is not None:\n lib_metadata['letter_case'] = letter_case\n\n if undefined is not None:\n # Get the corresponding action for undefined parameters\n if isinstance(undefined, str):\n if not hasattr(Undefined, undefined.upper()):\n valid_actions = list(action.name for action in Undefined)\n raise UndefinedParameterError(\n f\"Invalid undefined parameter action, \"\n f\"must be one of {valid_actions}\")\n undefined = Undefined[undefined.upper()]\n\n lib_metadata['undefined'] = undefined\n\n if exclude is not None:\n lib_metadata['exclude'] = exclude\n\n return metadata", "focal_method_lines": [43, 96], "in_stack": false, "globals": ["T", "global_config"], "type_context": "import functools\nfrom typing import Callable, Dict, Optional, TypeVar, Union\nfrom marshmallow.fields import Field as MarshmallowField\nfrom dataclasses_json.undefined import Undefined, UndefinedParameterError\n\nT = TypeVar(\"T\")\nglobal_config = _GlobalConfig()\n\ndef config(metadata: dict = None, *,\n # TODO: these can be typed more precisely\n # Specifically, a Callable[A, B], where `B` is bound as a JSON type\n encoder: Callable = None,\n decoder: Callable = None,\n mm_field: MarshmallowField = None,\n letter_case: Callable[[str], str] = None,\n undefined: Optional[Union[str, Undefined]] = None,\n field_name: str = None,\n exclude: Optional[Callable[[str, T], bool]] = None,\n ) -> Dict[str, dict]:\n if metadata is None:\n metadata = {}\n\n lib_metadata = metadata.setdefault('dataclasses_json', {})\n\n if encoder is not None:\n lib_metadata['encoder'] = encoder\n\n if decoder is not None:\n lib_metadata['decoder'] = decoder\n\n if mm_field is not None:\n lib_metadata['mm_field'] = mm_field\n\n if field_name is not None:\n if letter_case is not None:\n @functools.wraps(letter_case)\n def override(_, _letter_case=letter_case, _field_name=field_name):\n return _letter_case(_field_name)\n else:\n def override(_, _field_name=field_name):\n return _field_name\n letter_case = override\n\n if letter_case is not None:\n lib_metadata['letter_case'] = letter_case\n\n if undefined is not None:\n # Get the corresponding action for undefined parameters\n if isinstance(undefined, str):\n if not hasattr(Undefined, undefined.upper()):\n valid_actions = list(action.name for action in Undefined)\n raise UndefinedParameterError(\n f\"Invalid undefined parameter action, \"\n f\"must be one of {valid_actions}\")\n undefined = Undefined[undefined.upper()]\n\n lib_metadata['undefined'] = undefined\n\n if exclude is not None:\n lib_metadata['exclude'] = exclude\n\n return metadata", "has_branch": true, "total_branches": 2} {"prompt_id": 33, "project": "dataclasses_json", "module": "dataclasses_json.core", "class": "_ExtendedEncoder", "method": "default", "focal_method_txt": " def default(self, o) -> Json:\n result: Json\n if _isinstance_safe(o, Collection):\n if _isinstance_safe(o, Mapping):\n result = dict(o)\n else:\n result = list(o)\n elif _isinstance_safe(o, datetime):\n result = o.timestamp()\n elif _isinstance_safe(o, UUID):\n result = str(o)\n elif _isinstance_safe(o, Enum):\n result = o.value\n elif _isinstance_safe(o, Decimal):\n result = str(o)\n else:\n result = json.JSONEncoder.default(self, o)\n return result", "focal_method_lines": [32, 49], "in_stack": false, "globals": ["Json", "confs", "FieldOverride"], "type_context": "import copy\nimport json\nimport warnings\nfrom collections import defaultdict, namedtuple\nfrom dataclasses import (MISSING,\n _is_dataclass_instance,\n fields,\n is_dataclass # type: ignore\n )\nfrom datetime import datetime, timezone\nfrom decimal import Decimal\nfrom enum import Enum\nfrom typing import Any, Collection, Mapping, Union, get_type_hints\nfrom uuid import UUID\nfrom typing_inspect import is_union_type\nfrom dataclasses_json import cfg\nfrom dataclasses_json.utils import (_get_type_cons,\n _handle_undefined_parameters_safe,\n _is_collection, _is_mapping, _is_new_type,\n _is_optional, _isinstance_safe,\n _issubclass_safe)\n\nJson = Union[dict, list, str, int, float, bool, None]\nconfs = ['encoder', 'decoder', 'mm_field', 'letter_case', 'exclude']\nFieldOverride = namedtuple('FieldOverride', confs)\n\nclass _ExtendedEncoder(json.JSONEncoder):\n\n def default(self, o) -> Json:\n result: Json\n if _isinstance_safe(o, Collection):\n if _isinstance_safe(o, Mapping):\n result = dict(o)\n else:\n result = list(o)\n elif _isinstance_safe(o, datetime):\n result = o.timestamp()\n elif _isinstance_safe(o, UUID):\n result = str(o)\n elif _isinstance_safe(o, Enum):\n result = o.value\n elif _isinstance_safe(o, Decimal):\n result = str(o)\n else:\n result = json.JSONEncoder.default(self, o)\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 34, "project": "dataclasses_json", "module": "dataclasses_json.mm", "class": "", "method": "build_type", "focal_method_txt": "def build_type(type_, options, mixin, field, cls):\n def inner(type_, options):\n while True:\n if not _is_new_type(type_):\n break\n\n type_ = type_.__supertype__\n\n if is_dataclass(type_):\n if _issubclass_safe(type_, mixin):\n options['field_many'] = bool(\n _is_supported_generic(field.type) and _is_collection(\n field.type))\n return fields.Nested(type_.schema(), **options)\n else:\n warnings.warn(f\"Nested dataclass field {field.name} of type \"\n f\"{field.type} detected in \"\n f\"{cls.__name__} that is not an instance of \"\n f\"dataclass_json. Did you mean to recursively \"\n f\"serialize this field? If so, make sure to \"\n f\"augment {type_} with either the \"\n f\"`dataclass_json` decorator or mixin.\")\n return fields.Field(**options)\n\n origin = getattr(type_, '__origin__', type_)\n args = [inner(a, {}) for a in getattr(type_, '__args__', []) if\n a is not type(None)]\n\n if _is_optional(type_):\n options[\"allow_none\"] = True\n\n if origin in TYPES:\n return TYPES[origin](*args, **options)\n\n if _issubclass_safe(origin, Enum):\n return EnumField(enum=origin, by_value=True, *args, **options)\n\n if is_union_type(type_):\n union_types = [a for a in getattr(type_, '__args__', []) if\n a is not type(None)]\n union_desc = dict(zip(union_types, args))\n return _UnionField(union_desc, cls, field, **options)\n\n warnings.warn(\n f\"Unknown type {type_} at {cls.__name__}.{field.name}: {field.type} \"\n f\"It's advised to pass the correct marshmallow type to `mm_field`.\")\n return fields.Field(**options)\n\n return inner(type_, options)", "focal_method_lines": [226, 274], "in_stack": false, "globals": ["TYPES", "A", "JsonData", "TEncoded", "TOneOrMulti", "TOneOrMultiEncoded"], "type_context": "import typing\nimport warnings\nimport sys\nfrom copy import deepcopy\nfrom dataclasses import MISSING, is_dataclass, fields as dc_fields\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom uuid import UUID\nfrom enum import Enum\nfrom typing_inspect import is_union_type\nfrom marshmallow import fields, Schema, post_load\nfrom marshmallow_enum import EnumField\nfrom marshmallow.exceptions import ValidationError\nfrom dataclasses_json.core import (_is_supported_generic, _decode_dataclass,\n _ExtendedEncoder, _user_overrides_or_exts)\nfrom dataclasses_json.utils import (_is_collection, _is_optional,\n _issubclass_safe, _timestamp_to_dt_aware,\n _is_new_type, _get_type_origin,\n _handle_undefined_parameters_safe,\n CatchAllVar)\n\nTYPES = {\n typing.Mapping: fields.Mapping,\n typing.MutableMapping: fields.Mapping,\n typing.List: fields.List,\n typing.Dict: fields.Dict,\n typing.Tuple: fields.Tuple,\n typing.Callable: fields.Function,\n typing.Any: fields.Raw,\n dict: fields.Dict,\n list: fields.List,\n str: fields.Str,\n int: fields.Int,\n float: fields.Float,\n bool: fields.Bool,\n datetime: _TimestampField,\n UUID: fields.UUID,\n Decimal: fields.Decimal,\n CatchAllVar: fields.Dict,\n}\nA = typing.TypeVar('A')\nJsonData = typing.Union[str, bytes, bytearray]\nTEncoded = typing.Dict[str, typing.Any]\nTOneOrMulti = typing.Union[typing.List[A], A]\nTOneOrMultiEncoded = typing.Union[typing.List[TEncoded], TEncoded]\n\nclass _UnionField(fields.Field):\n\n def __init__(self, desc, cls, field, *args, **kwargs):\n self.desc = desc\n self.cls = cls\n self.field = field\n super().__init__(*args, **kwargs)\n\ndef build_type(type_, options, mixin, field, cls):\n def inner(type_, options):\n while True:\n if not _is_new_type(type_):\n break\n\n type_ = type_.__supertype__\n\n if is_dataclass(type_):\n if _issubclass_safe(type_, mixin):\n options['field_many'] = bool(\n _is_supported_generic(field.type) and _is_collection(\n field.type))\n return fields.Nested(type_.schema(), **options)\n else:\n warnings.warn(f\"Nested dataclass field {field.name} of type \"\n f\"{field.type} detected in \"\n f\"{cls.__name__} that is not an instance of \"\n f\"dataclass_json. Did you mean to recursively \"\n f\"serialize this field? If so, make sure to \"\n f\"augment {type_} with either the \"\n f\"`dataclass_json` decorator or mixin.\")\n return fields.Field(**options)\n\n origin = getattr(type_, '__origin__', type_)\n args = [inner(a, {}) for a in getattr(type_, '__args__', []) if\n a is not type(None)]\n\n if _is_optional(type_):\n options[\"allow_none\"] = True\n\n if origin in TYPES:\n return TYPES[origin](*args, **options)\n\n if _issubclass_safe(origin, Enum):\n return EnumField(enum=origin, by_value=True, *args, **options)\n\n if is_union_type(type_):\n union_types = [a for a in getattr(type_, '__args__', []) if\n a is not type(None)]\n union_desc = dict(zip(union_types, args))\n return _UnionField(union_desc, cls, field, **options)\n\n warnings.warn(\n f\"Unknown type {type_} at {cls.__name__}.{field.name}: {field.type} \"\n f\"It's advised to pass the correct marshmallow type to `mm_field`.\")\n return fields.Field(**options)\n\n return inner(type_, options)", "has_branch": true, "total_branches": 2} {"prompt_id": 35, "project": "dataclasses_json", "module": "dataclasses_json.mm", "class": "", "method": "schema", "focal_method_txt": "def schema(cls, mixin, infer_missing):\n schema = {}\n overrides = _user_overrides_or_exts(cls)\n # TODO check the undefined parameters and add the proper schema action\n # https://marshmallow.readthedocs.io/en/stable/quickstart.html\n for field in dc_fields(cls):\n metadata = (field.metadata or {}).get('dataclasses_json', {})\n metadata = overrides[field.name]\n if metadata.mm_field is not None:\n schema[field.name] = metadata.mm_field\n else:\n type_ = field.type\n options = {}\n missing_key = 'missing' if infer_missing else 'default'\n if field.default is not MISSING:\n options[missing_key] = field.default\n elif field.default_factory is not MISSING:\n options[missing_key] = field.default_factory\n\n if options.get(missing_key, ...) is None:\n options['allow_none'] = True\n\n if _is_optional(type_):\n options.setdefault(missing_key, None)\n options['allow_none'] = True\n if len(type_.__args__) == 2:\n # Union[str, int, None] is optional too, but it has more than 1 typed field.\n type_ = type_.__args__[0]\n\n if metadata.letter_case is not None:\n options['data_key'] = metadata.letter_case(field.name)\n\n t = build_type(type_, options, mixin, field, cls)\n # if type(t) is not fields.Field: # If we use `isinstance` we would return nothing.\n if field.type != typing.Optional[CatchAllVar]:\n schema[field.name] = t\n\n return schema", "focal_method_lines": [277, 314], "in_stack": false, "globals": ["TYPES", "A", "JsonData", "TEncoded", "TOneOrMulti", "TOneOrMultiEncoded"], "type_context": "import typing\nimport warnings\nimport sys\nfrom copy import deepcopy\nfrom dataclasses import MISSING, is_dataclass, fields as dc_fields\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom uuid import UUID\nfrom enum import Enum\nfrom typing_inspect import is_union_type\nfrom marshmallow import fields, Schema, post_load\nfrom marshmallow_enum import EnumField\nfrom marshmallow.exceptions import ValidationError\nfrom dataclasses_json.core import (_is_supported_generic, _decode_dataclass,\n _ExtendedEncoder, _user_overrides_or_exts)\nfrom dataclasses_json.utils import (_is_collection, _is_optional,\n _issubclass_safe, _timestamp_to_dt_aware,\n _is_new_type, _get_type_origin,\n _handle_undefined_parameters_safe,\n CatchAllVar)\n\nTYPES = {\n typing.Mapping: fields.Mapping,\n typing.MutableMapping: fields.Mapping,\n typing.List: fields.List,\n typing.Dict: fields.Dict,\n typing.Tuple: fields.Tuple,\n typing.Callable: fields.Function,\n typing.Any: fields.Raw,\n dict: fields.Dict,\n list: fields.List,\n str: fields.Str,\n int: fields.Int,\n float: fields.Float,\n bool: fields.Bool,\n datetime: _TimestampField,\n UUID: fields.UUID,\n Decimal: fields.Decimal,\n CatchAllVar: fields.Dict,\n}\nA = typing.TypeVar('A')\nJsonData = typing.Union[str, bytes, bytearray]\nTEncoded = typing.Dict[str, typing.Any]\nTOneOrMulti = typing.Union[typing.List[A], A]\nTOneOrMultiEncoded = typing.Union[typing.List[TEncoded], TEncoded]\n\ndef schema(cls, mixin, infer_missing):\n schema = {}\n overrides = _user_overrides_or_exts(cls)\n # TODO check the undefined parameters and add the proper schema action\n # https://marshmallow.readthedocs.io/en/stable/quickstart.html\n for field in dc_fields(cls):\n metadata = (field.metadata or {}).get('dataclasses_json', {})\n metadata = overrides[field.name]\n if metadata.mm_field is not None:\n schema[field.name] = metadata.mm_field\n else:\n type_ = field.type\n options = {}\n missing_key = 'missing' if infer_missing else 'default'\n if field.default is not MISSING:\n options[missing_key] = field.default\n elif field.default_factory is not MISSING:\n options[missing_key] = field.default_factory\n\n if options.get(missing_key, ...) is None:\n options['allow_none'] = True\n\n if _is_optional(type_):\n options.setdefault(missing_key, None)\n options['allow_none'] = True\n if len(type_.__args__) == 2:\n # Union[str, int, None] is optional too, but it has more than 1 typed field.\n type_ = type_.__args__[0]\n\n if metadata.letter_case is not None:\n options['data_key'] = metadata.letter_case(field.name)\n\n t = build_type(type_, options, mixin, field, cls)\n # if type(t) is not fields.Field: # If we use `isinstance` we would return nothing.\n if field.type != typing.Optional[CatchAllVar]:\n schema[field.name] = t\n\n return schema", "has_branch": true, "total_branches": 2} {"prompt_id": 36, "project": "dataclasses_json", "module": "dataclasses_json.mm", "class": "", "method": "build_schema", "focal_method_txt": "def build_schema(cls: typing.Type[A],\n mixin,\n infer_missing,\n partial) -> typing.Type[SchemaType]:\n Meta = type('Meta',\n (),\n {'fields': tuple(field.name for field in dc_fields(cls)\n if\n field.name != 'dataclass_json_config' and field.type !=\n typing.Optional[CatchAllVar]),\n # TODO #180\n # 'render_module': global_config.json_module\n })\n\n @post_load\n def make_instance(self, kvs, **kwargs):\n return _decode_dataclass(cls, kvs, partial)\n\n def dumps(self, *args, **kwargs):\n if 'cls' not in kwargs:\n kwargs['cls'] = _ExtendedEncoder\n\n return Schema.dumps(self, *args, **kwargs)\n\n def dump(self, obj, *, many=None):\n dumped = Schema.dump(self, obj, many=many)\n # TODO This is hacky, but the other option I can think of is to generate a different schema\n # depending on dump and load, which is even more hacky\n\n # The only problem is the catch all field, we can't statically create a schema for it\n # so we just update the dumped dict\n if many:\n for i, _obj in enumerate(obj):\n dumped[i].update(\n _handle_undefined_parameters_safe(cls=_obj, kvs={},\n usage=\"dump\"))\n else:\n dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={},\n usage=\"dump\"))\n return dumped\n\n schema_ = schema(cls, mixin, infer_missing)\n DataClassSchema: typing.Type[SchemaType] = type(\n f'{cls.__name__.capitalize()}Schema',\n (Schema,),\n {'Meta': Meta,\n f'make_{cls.__name__.lower()}': make_instance,\n 'dumps': dumps,\n 'dump': dump,\n **schema_})\n\n return DataClassSchema", "focal_method_lines": [317, 368], "in_stack": false, "globals": ["TYPES", "A", "JsonData", "TEncoded", "TOneOrMulti", "TOneOrMultiEncoded"], "type_context": "import typing\nimport warnings\nimport sys\nfrom copy import deepcopy\nfrom dataclasses import MISSING, is_dataclass, fields as dc_fields\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom uuid import UUID\nfrom enum import Enum\nfrom typing_inspect import is_union_type\nfrom marshmallow import fields, Schema, post_load\nfrom marshmallow_enum import EnumField\nfrom marshmallow.exceptions import ValidationError\nfrom dataclasses_json.core import (_is_supported_generic, _decode_dataclass,\n _ExtendedEncoder, _user_overrides_or_exts)\nfrom dataclasses_json.utils import (_is_collection, _is_optional,\n _issubclass_safe, _timestamp_to_dt_aware,\n _is_new_type, _get_type_origin,\n _handle_undefined_parameters_safe,\n CatchAllVar)\n\nTYPES = {\n typing.Mapping: fields.Mapping,\n typing.MutableMapping: fields.Mapping,\n typing.List: fields.List,\n typing.Dict: fields.Dict,\n typing.Tuple: fields.Tuple,\n typing.Callable: fields.Function,\n typing.Any: fields.Raw,\n dict: fields.Dict,\n list: fields.List,\n str: fields.Str,\n int: fields.Int,\n float: fields.Float,\n bool: fields.Bool,\n datetime: _TimestampField,\n UUID: fields.UUID,\n Decimal: fields.Decimal,\n CatchAllVar: fields.Dict,\n}\nA = typing.TypeVar('A')\nJsonData = typing.Union[str, bytes, bytearray]\nTEncoded = typing.Dict[str, typing.Any]\nTOneOrMulti = typing.Union[typing.List[A], A]\nTOneOrMultiEncoded = typing.Union[typing.List[TEncoded], TEncoded]\n\ndef build_schema(cls: typing.Type[A],\n mixin,\n infer_missing,\n partial) -> typing.Type[SchemaType]:\n Meta = type('Meta',\n (),\n {'fields': tuple(field.name for field in dc_fields(cls)\n if\n field.name != 'dataclass_json_config' and field.type !=\n typing.Optional[CatchAllVar]),\n # TODO #180\n # 'render_module': global_config.json_module\n })\n\n @post_load\n def make_instance(self, kvs, **kwargs):\n return _decode_dataclass(cls, kvs, partial)\n\n def dumps(self, *args, **kwargs):\n if 'cls' not in kwargs:\n kwargs['cls'] = _ExtendedEncoder\n\n return Schema.dumps(self, *args, **kwargs)\n\n def dump(self, obj, *, many=None):\n dumped = Schema.dump(self, obj, many=many)\n # TODO This is hacky, but the other option I can think of is to generate a different schema\n # depending on dump and load, which is even more hacky\n\n # The only problem is the catch all field, we can't statically create a schema for it\n # so we just update the dumped dict\n if many:\n for i, _obj in enumerate(obj):\n dumped[i].update(\n _handle_undefined_parameters_safe(cls=_obj, kvs={},\n usage=\"dump\"))\n else:\n dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={},\n usage=\"dump\"))\n return dumped\n\n schema_ = schema(cls, mixin, infer_missing)\n DataClassSchema: typing.Type[SchemaType] = type(\n f'{cls.__name__.capitalize()}Schema',\n (Schema,),\n {'Meta': Meta,\n f'make_{cls.__name__.lower()}': make_instance,\n 'dumps': dumps,\n 'dump': dump,\n **schema_})\n\n return DataClassSchema", "has_branch": true, "total_branches": 2} {"prompt_id": 37, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_UndefinedParameterAction", "method": "handle_from_dict", "focal_method_txt": " @staticmethod\n @abc.abstractmethod\n def handle_from_dict(cls, kvs: Dict[Any, Any]) -> Dict[str, Any]:\n \"\"\"\n Return the parameters to initialize the class with.\n \"\"\"\n pass", "focal_method_lines": [19, 23], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _UndefinedParameterAction(abc.ABC):\n\n @staticmethod\n @abc.abstractmethod\n def handle_from_dict(cls, kvs: Dict[Any, Any]) -> Dict[str, Any]:\n \"\"\"\n Return the parameters to initialize the class with.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 38, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_UndefinedParameterAction", "method": "handle_to_dict", "focal_method_txt": " @staticmethod\n def handle_to_dict(obj, kvs: Dict[Any, Any]) -> Dict[Any, Any]:\n \"\"\"\n Return the parameters that will be written to the output dict\n \"\"\"\n return kvs", "focal_method_lines": [26, 30], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _UndefinedParameterAction(abc.ABC):\n\n @staticmethod\n def handle_to_dict(obj, kvs: Dict[Any, Any]) -> Dict[Any, Any]:\n \"\"\"\n Return the parameters that will be written to the output dict\n \"\"\"\n return kvs", "has_branch": false, "total_branches": 0} {"prompt_id": 39, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_UndefinedParameterAction", "method": "handle_dump", "focal_method_txt": " @staticmethod\n def handle_dump(obj) -> Dict[Any, Any]:\n \"\"\"\n Return the parameters that will be added to the schema dump.\n \"\"\"\n return {}", "focal_method_lines": [33, 37], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _UndefinedParameterAction(abc.ABC):\n\n @staticmethod\n def handle_dump(obj) -> Dict[Any, Any]:\n \"\"\"\n Return the parameters that will be added to the schema dump.\n \"\"\"\n return {}", "has_branch": false, "total_branches": 0} {"prompt_id": 40, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_UndefinedParameterAction", "method": "create_init", "focal_method_txt": " @staticmethod\n def create_init(obj) -> Callable:\n return obj.__init__", "focal_method_lines": [40, 41], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _UndefinedParameterAction(abc.ABC):\n\n @staticmethod\n def create_init(obj) -> Callable:\n return obj.__init__", "has_branch": false, "total_branches": 0} {"prompt_id": 41, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_RaiseUndefinedParameters", "method": "handle_from_dict", "focal_method_txt": " @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known, unknown = \\\n _UndefinedParameterAction._separate_defined_undefined_kvs(\n cls=cls, kvs=kvs)\n if len(unknown) > 0:\n raise UndefinedParameterError(\n f\"Received undefined initialization arguments {unknown}\")\n return known", "focal_method_lines": [65, 72], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _RaiseUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known, unknown = \\\n _UndefinedParameterAction._separate_defined_undefined_kvs(\n cls=cls, kvs=kvs)\n if len(unknown) > 0:\n raise UndefinedParameterError(\n f\"Received undefined initialization arguments {unknown}\")\n return known", "has_branch": true, "total_branches": 2} {"prompt_id": 42, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_IgnoreUndefinedParameters", "method": "handle_from_dict", "focal_method_txt": " @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known_given_parameters, _ = \\\n _UndefinedParameterAction._separate_defined_undefined_kvs(\n cls=cls, kvs=kvs)\n return known_given_parameters", "focal_method_lines": [86, 90], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _IgnoreUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known_given_parameters, _ = \\\n _UndefinedParameterAction._separate_defined_undefined_kvs(\n cls=cls, kvs=kvs)\n return known_given_parameters", "has_branch": false, "total_branches": 0} {"prompt_id": 43, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_IgnoreUndefinedParameters", "method": "create_init", "focal_method_txt": " @staticmethod\n def create_init(obj) -> Callable:\n original_init = obj.__init__\n init_signature = inspect.signature(original_init)\n\n @functools.wraps(obj.__init__)\n def _ignore_init(self, *args, **kwargs):\n known_kwargs, _ = \\\n _CatchAllUndefinedParameters._separate_defined_undefined_kvs(\n obj, kwargs)\n num_params_takeable = len(\n init_signature.parameters) - 1 # don't count self\n num_args_takeable = num_params_takeable - len(known_kwargs)\n\n args = args[:num_args_takeable]\n bound_parameters = init_signature.bind_partial(self, *args,\n **known_kwargs)\n bound_parameters.apply_defaults()\n\n arguments = bound_parameters.arguments\n arguments.pop(\"self\", None)\n final_parameters = \\\n _IgnoreUndefinedParameters.handle_from_dict(obj, arguments)\n original_init(self, **final_parameters)\n\n return _ignore_init", "focal_method_lines": [93, 117], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _IgnoreUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def create_init(obj) -> Callable:\n original_init = obj.__init__\n init_signature = inspect.signature(original_init)\n\n @functools.wraps(obj.__init__)\n def _ignore_init(self, *args, **kwargs):\n known_kwargs, _ = \\\n _CatchAllUndefinedParameters._separate_defined_undefined_kvs(\n obj, kwargs)\n num_params_takeable = len(\n init_signature.parameters) - 1 # don't count self\n num_args_takeable = num_params_takeable - len(known_kwargs)\n\n args = args[:num_args_takeable]\n bound_parameters = init_signature.bind_partial(self, *args,\n **known_kwargs)\n bound_parameters.apply_defaults()\n\n arguments = bound_parameters.arguments\n arguments.pop(\"self\", None)\n final_parameters = \\\n _IgnoreUndefinedParameters.handle_from_dict(obj, arguments)\n original_init(self, **final_parameters)\n\n return _ignore_init", "has_branch": false, "total_branches": 0} {"prompt_id": 44, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_CatchAllUndefinedParameters", "method": "handle_from_dict", "focal_method_txt": " @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known, unknown = _UndefinedParameterAction \\\n ._separate_defined_undefined_kvs(cls=cls, kvs=kvs)\n catch_all_field = _CatchAllUndefinedParameters._get_catch_all_field(\n cls=cls)\n\n if catch_all_field.name in known:\n\n already_parsed = isinstance(known[catch_all_field.name], dict)\n default_value = _CatchAllUndefinedParameters._get_default(\n catch_all_field=catch_all_field)\n received_default = default_value == known[catch_all_field.name]\n\n value_to_write: Any\n if received_default and len(unknown) == 0:\n value_to_write = default_value\n elif received_default and len(unknown) > 0:\n value_to_write = unknown\n elif already_parsed:\n # Did not receive default\n value_to_write = known[catch_all_field.name]\n if len(unknown) > 0:\n value_to_write.update(unknown)\n else:\n error_message = f\"Received input field with \" \\\n f\"same name as catch-all field: \" \\\n f\"'{catch_all_field.name}': \" \\\n f\"'{known[catch_all_field.name]}'\"\n raise UndefinedParameterError(error_message)\n else:\n value_to_write = unknown\n\n known[catch_all_field.name] = value_to_write\n return known", "focal_method_lines": [133, 166], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _CatchAllUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def handle_from_dict(cls, kvs: Dict) -> Dict[str, Any]:\n known, unknown = _UndefinedParameterAction \\\n ._separate_defined_undefined_kvs(cls=cls, kvs=kvs)\n catch_all_field = _CatchAllUndefinedParameters._get_catch_all_field(\n cls=cls)\n\n if catch_all_field.name in known:\n\n already_parsed = isinstance(known[catch_all_field.name], dict)\n default_value = _CatchAllUndefinedParameters._get_default(\n catch_all_field=catch_all_field)\n received_default = default_value == known[catch_all_field.name]\n\n value_to_write: Any\n if received_default and len(unknown) == 0:\n value_to_write = default_value\n elif received_default and len(unknown) > 0:\n value_to_write = unknown\n elif already_parsed:\n # Did not receive default\n value_to_write = known[catch_all_field.name]\n if len(unknown) > 0:\n value_to_write.update(unknown)\n else:\n error_message = f\"Received input field with \" \\\n f\"same name as catch-all field: \" \\\n f\"'{catch_all_field.name}': \" \\\n f\"'{known[catch_all_field.name]}'\"\n raise UndefinedParameterError(error_message)\n else:\n value_to_write = unknown\n\n known[catch_all_field.name] = value_to_write\n return known", "has_branch": true, "total_branches": 2} {"prompt_id": 45, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_CatchAllUndefinedParameters", "method": "handle_to_dict", "focal_method_txt": " @staticmethod\n def handle_to_dict(obj, kvs: Dict[Any, Any]) -> Dict[Any, Any]:\n catch_all_field = \\\n _CatchAllUndefinedParameters._get_catch_all_field(obj)\n undefined_parameters = kvs.pop(catch_all_field.name)\n if isinstance(undefined_parameters, dict):\n kvs.update(\n undefined_parameters) # If desired handle letter case here\n return kvs", "focal_method_lines": [193, 200], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _CatchAllUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def handle_to_dict(obj, kvs: Dict[Any, Any]) -> Dict[Any, Any]:\n catch_all_field = \\\n _CatchAllUndefinedParameters._get_catch_all_field(obj)\n undefined_parameters = kvs.pop(catch_all_field.name)\n if isinstance(undefined_parameters, dict):\n kvs.update(\n undefined_parameters) # If desired handle letter case here\n return kvs", "has_branch": true, "total_branches": 2} {"prompt_id": 46, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_CatchAllUndefinedParameters", "method": "handle_dump", "focal_method_txt": " @staticmethod\n def handle_dump(obj) -> Dict[Any, Any]:\n catch_all_field = _CatchAllUndefinedParameters._get_catch_all_field(\n cls=obj)\n return getattr(obj, catch_all_field.name)", "focal_method_lines": [203, 206], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _CatchAllUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def handle_dump(obj) -> Dict[Any, Any]:\n catch_all_field = _CatchAllUndefinedParameters._get_catch_all_field(\n cls=obj)\n return getattr(obj, catch_all_field.name)", "has_branch": false, "total_branches": 0} {"prompt_id": 47, "project": "dataclasses_json", "module": "dataclasses_json.undefined", "class": "_CatchAllUndefinedParameters", "method": "create_init", "focal_method_txt": " @staticmethod\n def create_init(obj) -> Callable:\n original_init = obj.__init__\n init_signature = inspect.signature(original_init)\n\n @functools.wraps(obj.__init__)\n def _catch_all_init(self, *args, **kwargs):\n known_kwargs, unknown_kwargs = \\\n _CatchAllUndefinedParameters._separate_defined_undefined_kvs(\n obj, kwargs)\n num_params_takeable = len(\n init_signature.parameters) - 1 # don't count self\n if _CatchAllUndefinedParameters._get_catch_all_field(\n obj).name not in known_kwargs:\n num_params_takeable -= 1\n num_args_takeable = num_params_takeable - len(known_kwargs)\n\n args, unknown_args = args[:num_args_takeable], args[\n num_args_takeable:]\n bound_parameters = init_signature.bind_partial(self, *args,\n **known_kwargs)\n\n unknown_args = {f\"_UNKNOWN{i}\": v for i, v in\n enumerate(unknown_args)}\n arguments = bound_parameters.arguments\n arguments.update(unknown_args)\n arguments.update(unknown_kwargs)\n arguments.pop(\"self\", None)\n final_parameters = _CatchAllUndefinedParameters.handle_from_dict(\n obj, arguments)\n original_init(self, **final_parameters)\n\n return _catch_all_init", "focal_method_lines": [209, 240], "in_stack": false, "globals": ["KnownParameters", "UnknownParameters", "CatchAll"], "type_context": "import abc\nimport dataclasses\nimport functools\nimport inspect\nfrom dataclasses import Field, fields\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom enum import Enum\nfrom marshmallow import ValidationError\nfrom dataclasses_json.utils import CatchAllVar\n\nKnownParameters = Dict[str, Any]\nUnknownParameters = Dict[str, Any]\nCatchAll = Optional[CatchAllVar]\n\nclass _CatchAllUndefinedParameters(_UndefinedParameterAction):\n\n @staticmethod\n def create_init(obj) -> Callable:\n original_init = obj.__init__\n init_signature = inspect.signature(original_init)\n\n @functools.wraps(obj.__init__)\n def _catch_all_init(self, *args, **kwargs):\n known_kwargs, unknown_kwargs = \\\n _CatchAllUndefinedParameters._separate_defined_undefined_kvs(\n obj, kwargs)\n num_params_takeable = len(\n init_signature.parameters) - 1 # don't count self\n if _CatchAllUndefinedParameters._get_catch_all_field(\n obj).name not in known_kwargs:\n num_params_takeable -= 1\n num_args_takeable = num_params_takeable - len(known_kwargs)\n\n args, unknown_args = args[:num_args_takeable], args[\n num_args_takeable:]\n bound_parameters = init_signature.bind_partial(self, *args,\n **known_kwargs)\n\n unknown_args = {f\"_UNKNOWN{i}\": v for i, v in\n enumerate(unknown_args)}\n arguments = bound_parameters.arguments\n arguments.update(unknown_args)\n arguments.update(unknown_kwargs)\n arguments.pop(\"self\", None)\n final_parameters = _CatchAllUndefinedParameters.handle_from_dict(\n obj, arguments)\n original_init(self, **final_parameters)\n\n return _catch_all_init", "has_branch": true, "total_branches": 2} {"prompt_id": 48, "project": "docstring_parser", "module": "docstring_parser.common", "class": "DocstringMeta", "method": "__init__", "focal_method_txt": " def __init__(self, args: T.List[str], description: str) -> None:\n \"\"\"Initialize self.\n\n :param args: list of arguments. The exact content of this variable is\n dependent on the kind of docstring; it's used to distinguish between\n custom docstring meta information items.\n :param description: associated docstring description.\n \"\"\"\n self.args = args\n self.description = description", "focal_method_lines": [32, 41], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass DocstringMeta:\n\n def __init__(self, args: T.List[str], description: str) -> None:\n \"\"\"Initialize self.\n\n :param args: list of arguments. The exact content of this variable is\n dependent on the kind of docstring; it's used to distinguish between\n custom docstring meta information items.\n :param description: associated docstring description.\n \"\"\"\n self.args = args\n self.description = description", "has_branch": false, "total_branches": 0} {"prompt_id": 49, "project": "docstring_parser", "module": "docstring_parser.common", "class": "DocstringParam", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n arg_name: str,\n type_name: T.Optional[str],\n is_optional: T.Optional[bool],\n default: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.arg_name = arg_name\n self.type_name = type_name\n self.is_optional = is_optional\n self.default = default", "focal_method_lines": [47, 61], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass DocstringParam(DocstringMeta):\n\n def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n arg_name: str,\n type_name: T.Optional[str],\n is_optional: T.Optional[bool],\n default: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.arg_name = arg_name\n self.type_name = type_name\n self.is_optional = is_optional\n self.default = default", "has_branch": false, "total_branches": 0} {"prompt_id": 50, "project": "docstring_parser", "module": "docstring_parser.common", "class": "DocstringReturns", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n type_name: T.Optional[str],\n is_generator: bool,\n return_name: T.Optional[str] = None,\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.type_name = type_name\n self.is_generator = is_generator\n self.return_name = return_name", "focal_method_lines": [67, 79], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass DocstringReturns(DocstringMeta):\n\n def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n type_name: T.Optional[str],\n is_generator: bool,\n return_name: T.Optional[str] = None,\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.type_name = type_name\n self.is_generator = is_generator\n self.return_name = return_name", "has_branch": false, "total_branches": 0} {"prompt_id": 51, "project": "docstring_parser", "module": "docstring_parser.common", "class": "DocstringRaises", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n type_name: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.type_name = type_name\n self.description = description", "focal_method_lines": [85, 94], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass DocstringRaises(DocstringMeta):\n\n def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n type_name: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.type_name = type_name\n self.description = description", "has_branch": false, "total_branches": 0} {"prompt_id": 52, "project": "docstring_parser", "module": "docstring_parser.common", "class": "DocstringDeprecated", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n version: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.version = version\n self.description = description", "focal_method_lines": [100, 109], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass DocstringDeprecated(DocstringMeta):\n\n def __init__(\n self,\n args: T.List[str],\n description: T.Optional[str],\n version: T.Optional[str],\n ) -> None:\n \"\"\"Initialize self.\"\"\"\n super().__init__(args, description)\n self.version = version\n self.description = description", "has_branch": false, "total_branches": 0} {"prompt_id": 53, "project": "docstring_parser", "module": "docstring_parser.common", "class": "Docstring", "method": "__init__", "focal_method_txt": " def __init__(self) -> None:\n \"\"\"Initialize self.\"\"\"\n self.short_description = None # type: T.Optional[str]\n self.long_description = None # type: T.Optional[str]\n self.blank_after_short_description = False\n self.blank_after_long_description = False\n self.meta = []", "focal_method_lines": [115, 121], "in_stack": false, "globals": ["PARAM_KEYWORDS", "RAISES_KEYWORDS", "RETURNS_KEYWORDS", "YIELDS_KEYWORDS"], "type_context": "import typing as T\n\nPARAM_KEYWORDS = {\n \"param\",\n \"parameter\",\n \"arg\",\n \"argument\",\n \"attribute\",\n \"key\",\n \"keyword\",\n}\nRAISES_KEYWORDS = {\"raises\", \"raise\", \"except\", \"exception\"}\nRETURNS_KEYWORDS = {\"return\", \"returns\"}\nYIELDS_KEYWORDS = {\"yield\", \"yields\"}\n\nclass Docstring:\n\n def __init__(self) -> None:\n \"\"\"Initialize self.\"\"\"\n self.short_description = None # type: T.Optional[str]\n self.long_description = None # type: T.Optional[str]\n self.blank_after_short_description = False\n self.blank_after_long_description = False\n self.meta = []", "has_branch": false, "total_branches": 0} {"prompt_id": 54, "project": "docstring_parser", "module": "docstring_parser.google", "class": "GoogleParser", "method": "add_section", "focal_method_txt": " def add_section(self, section: Section):\n \"\"\"Add or replace a section.\n\n :param section: The new section.\n \"\"\"\n\n self.sections[section.title] = section\n self._setup()", "focal_method_lines": [174, 181], "in_stack": false, "globals": ["GOOGLE_TYPED_ARG_REGEX", "GOOGLE_ARG_DESC_REGEX", "MULTIPLE_PATTERN", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport re\nimport typing as T\nfrom collections import namedtuple, OrderedDict\nfrom enum import IntEnum\nfrom .common import (\n PARAM_KEYWORDS,\n RAISES_KEYWORDS,\n RETURNS_KEYWORDS,\n YIELDS_KEYWORDS,\n Docstring,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n ParseError,\n)\n\nGOOGLE_TYPED_ARG_REGEX = re.compile(r\"\\s*(.+?)\\s*\\(\\s*(.*[^\\s]+)\\s*\\)\")\nGOOGLE_ARG_DESC_REGEX = re.compile(r\".*\\. Defaults to (.+)\\.\")\nMULTIPLE_PATTERN = re.compile(r\"(\\s*[^:\\s]+:)|([^:]*\\]:.*)\")\nDEFAULT_SECTIONS = [\n Section(\"Arguments\", \"param\", SectionType.MULTIPLE),\n Section(\"Args\", \"param\", SectionType.MULTIPLE),\n Section(\"Parameters\", \"param\", SectionType.MULTIPLE),\n Section(\"Params\", \"param\", SectionType.MULTIPLE),\n Section(\"Raises\", \"raises\", SectionType.MULTIPLE),\n Section(\"Exceptions\", \"raises\", SectionType.MULTIPLE),\n Section(\"Except\", \"raises\", SectionType.MULTIPLE),\n Section(\"Attributes\", \"attribute\", SectionType.MULTIPLE),\n Section(\"Example\", \"examples\", SectionType.SINGULAR),\n Section(\"Examples\", \"examples\", SectionType.SINGULAR),\n Section(\"Returns\", \"returns\", SectionType.SINGULAR_OR_MULTIPLE),\n Section(\"Yields\", \"yields\", SectionType.SINGULAR_OR_MULTIPLE),\n]\n\nclass GoogleParser:\n\n def __init__(\n self, sections: T.Optional[T.List[Section]] = None, title_colon=True\n ):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n :param title_colon: require colon after section title.\n \"\"\"\n if not sections:\n sections = DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self.title_colon = title_colon\n self._setup()\n\n def add_section(self, section: Section):\n \"\"\"Add or replace a section.\n\n :param section: The new section.\n \"\"\"\n\n self.sections[section.title] = section\n self._setup()", "has_branch": false, "total_branches": 0} {"prompt_id": 55, "project": "docstring_parser", "module": "docstring_parser.google", "class": "GoogleParser", "method": "parse", "focal_method_txt": " def parse(self, text: str) -> Docstring:\n \"\"\"Parse the Google-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n # Clean according to PEP-0257\n text = inspect.cleandoc(text)\n\n # Find first title and split on its position\n match = self.titles_re.search(text)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n # Break description into short and long parts\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\n \"\\n\"\n )\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n # Split by sections determined by titles\n matches = list(self.titles_re.finditer(meta_chunk))\n if not matches:\n return ret\n splits = []\n for j in range(len(matches) - 1):\n splits.append((matches[j].end(), matches[j + 1].start()))\n splits.append((matches[-1].end(), len(meta_chunk)))\n\n chunks = OrderedDict()\n for j, (start, end) in enumerate(splits):\n title = matches[j].group(1)\n if title not in self.sections:\n continue\n chunks[title] = meta_chunk[start:end].strip(\"\\n\")\n if not chunks:\n return ret\n\n # Add elements from each chunk\n for title, chunk in chunks.items():\n # Determine indent\n indent_match = re.search(r\"^\\s+\", chunk)\n if not indent_match:\n raise ParseError('Can\\'t infer indent from \"{}\"'.format(chunk))\n indent = indent_match.group()\n\n # Check for singular elements\n if self.sections[title].type in [\n SectionType.SINGULAR,\n SectionType.SINGULAR_OR_MULTIPLE,\n ]:\n part = inspect.cleandoc(chunk)\n ret.meta.append(self._build_meta(part, title))\n continue\n\n # Split based on lines which have exactly that indent\n _re = \"^\" + indent + r\"(?=\\S)\"\n c_matches = list(re.finditer(_re, chunk, flags=re.M))\n if not c_matches:\n raise ParseError(\n 'No specification for \"{}\": \"{}\"'.format(title, chunk)\n )\n c_splits = []\n for j in range(len(c_matches) - 1):\n c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))\n c_splits.append((c_matches[-1].end(), len(chunk)))\n for j, (start, end) in enumerate(c_splits):\n part = chunk[start:end].strip(\"\\n\")\n ret.meta.append(self._build_meta(part, title))\n\n return ret", "focal_method_lines": [183, 265], "in_stack": false, "globals": ["GOOGLE_TYPED_ARG_REGEX", "GOOGLE_ARG_DESC_REGEX", "MULTIPLE_PATTERN", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport re\nimport typing as T\nfrom collections import namedtuple, OrderedDict\nfrom enum import IntEnum\nfrom .common import (\n PARAM_KEYWORDS,\n RAISES_KEYWORDS,\n RETURNS_KEYWORDS,\n YIELDS_KEYWORDS,\n Docstring,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n ParseError,\n)\n\nGOOGLE_TYPED_ARG_REGEX = re.compile(r\"\\s*(.+?)\\s*\\(\\s*(.*[^\\s]+)\\s*\\)\")\nGOOGLE_ARG_DESC_REGEX = re.compile(r\".*\\. Defaults to (.+)\\.\")\nMULTIPLE_PATTERN = re.compile(r\"(\\s*[^:\\s]+:)|([^:]*\\]:.*)\")\nDEFAULT_SECTIONS = [\n Section(\"Arguments\", \"param\", SectionType.MULTIPLE),\n Section(\"Args\", \"param\", SectionType.MULTIPLE),\n Section(\"Parameters\", \"param\", SectionType.MULTIPLE),\n Section(\"Params\", \"param\", SectionType.MULTIPLE),\n Section(\"Raises\", \"raises\", SectionType.MULTIPLE),\n Section(\"Exceptions\", \"raises\", SectionType.MULTIPLE),\n Section(\"Except\", \"raises\", SectionType.MULTIPLE),\n Section(\"Attributes\", \"attribute\", SectionType.MULTIPLE),\n Section(\"Example\", \"examples\", SectionType.SINGULAR),\n Section(\"Examples\", \"examples\", SectionType.SINGULAR),\n Section(\"Returns\", \"returns\", SectionType.SINGULAR_OR_MULTIPLE),\n Section(\"Yields\", \"yields\", SectionType.SINGULAR_OR_MULTIPLE),\n]\n\nclass GoogleParser:\n\n def __init__(\n self, sections: T.Optional[T.List[Section]] = None, title_colon=True\n ):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n :param title_colon: require colon after section title.\n \"\"\"\n if not sections:\n sections = DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self.title_colon = title_colon\n self._setup()\n\n def parse(self, text: str) -> Docstring:\n \"\"\"Parse the Google-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n # Clean according to PEP-0257\n text = inspect.cleandoc(text)\n\n # Find first title and split on its position\n match = self.titles_re.search(text)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n # Break description into short and long parts\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\n \"\\n\"\n )\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n # Split by sections determined by titles\n matches = list(self.titles_re.finditer(meta_chunk))\n if not matches:\n return ret\n splits = []\n for j in range(len(matches) - 1):\n splits.append((matches[j].end(), matches[j + 1].start()))\n splits.append((matches[-1].end(), len(meta_chunk)))\n\n chunks = OrderedDict()\n for j, (start, end) in enumerate(splits):\n title = matches[j].group(1)\n if title not in self.sections:\n continue\n chunks[title] = meta_chunk[start:end].strip(\"\\n\")\n if not chunks:\n return ret\n\n # Add elements from each chunk\n for title, chunk in chunks.items():\n # Determine indent\n indent_match = re.search(r\"^\\s+\", chunk)\n if not indent_match:\n raise ParseError('Can\\'t infer indent from \"{}\"'.format(chunk))\n indent = indent_match.group()\n\n # Check for singular elements\n if self.sections[title].type in [\n SectionType.SINGULAR,\n SectionType.SINGULAR_OR_MULTIPLE,\n ]:\n part = inspect.cleandoc(chunk)\n ret.meta.append(self._build_meta(part, title))\n continue\n\n # Split based on lines which have exactly that indent\n _re = \"^\" + indent + r\"(?=\\S)\"\n c_matches = list(re.finditer(_re, chunk, flags=re.M))\n if not c_matches:\n raise ParseError(\n 'No specification for \"{}\": \"{}\"'.format(title, chunk)\n )\n c_splits = []\n for j in range(len(c_matches) - 1):\n c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))\n c_splits.append((c_matches[-1].end(), len(chunk)))\n for j, (start, end) in enumerate(c_splits):\n part = chunk[start:end].strip(\"\\n\")\n ret.meta.append(self._build_meta(part, title))\n\n return ret", "has_branch": true, "total_branches": 2} {"prompt_id": 56, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "", "method": "parse", "focal_method_txt": "def parse(text: str) -> Docstring:\n \"\"\"Parse the numpy-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n return NumpydocParser().parse(text)", "focal_method_lines": [325, 330], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass NumpydocParser:\n\n def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n \"\"\"\n sections = sections or DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self._setup()\n\ndef parse(text: str) -> Docstring:\n \"\"\"Parse the numpy-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n return NumpydocParser().parse(text)", "has_branch": false, "total_branches": 0} {"prompt_id": 57, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "Section", "method": "__init__", "focal_method_txt": " def __init__(self, title: str, key: str) -> None:\n self.title = title\n self.key = key", "focal_method_lines": [57, 59], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass Section:\n\n def __init__(self, title: str, key: str) -> None:\n self.title = title\n self.key = key", "has_branch": false, "total_branches": 0} {"prompt_id": 58, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "Section", "method": "parse", "focal_method_txt": " def parse(self, text: str) -> T.Iterable[DocstringMeta]:\n \"\"\"Parse ``DocstringMeta`` objects from the body of this section.\n\n :param text: section body text. Should be cleaned with\n ``inspect.cleandoc`` before parsing.\n \"\"\"\n yield DocstringMeta([self.key], description=_clean_str(text))", "focal_method_lines": [70, 76], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass Section:\n\n def __init__(self, title: str, key: str) -> None:\n self.title = title\n self.key = key\n\n def parse(self, text: str) -> T.Iterable[DocstringMeta]:\n \"\"\"Parse ``DocstringMeta`` objects from the body of this section.\n\n :param text: section body text. Should be cleaned with\n ``inspect.cleandoc`` before parsing.\n \"\"\"\n yield DocstringMeta([self.key], description=_clean_str(text))", "has_branch": false, "total_branches": 0} {"prompt_id": 59, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "_KVSection", "method": "parse", "focal_method_txt": " def parse(self, text: str) -> T.Iterable[DocstringMeta]:\n for match, next_match in _pairwise(KV_REGEX.finditer(text)):\n start = match.end()\n end = next_match.start() if next_match is not None else None\n value = text[start:end]\n yield self._parse_item(\n key=match.group(), value=inspect.cleandoc(value)\n )", "focal_method_lines": [93, 98], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass _KVSection(Section):\n\n def parse(self, text: str) -> T.Iterable[DocstringMeta]:\n for match, next_match in _pairwise(KV_REGEX.finditer(text)):\n start = match.end()\n end = next_match.start() if next_match is not None else None\n value = text[start:end]\n yield self._parse_item(\n key=match.group(), value=inspect.cleandoc(value)\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 60, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "DeprecationSection", "method": "parse", "focal_method_txt": " def parse(self, text: str) -> T.Iterable[DocstringDeprecated]:\n version, desc, *_ = text.split(sep=\"\\n\", maxsplit=1) + [None, None]\n\n if desc is not None:\n desc = _clean_str(inspect.cleandoc(desc))\n\n yield DocstringDeprecated(\n args=[self.key], description=desc, version=_clean_str(version)\n )", "focal_method_lines": [209, 215], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass DeprecationSection(_SphinxSection):\n\n def parse(self, text: str) -> T.Iterable[DocstringDeprecated]:\n version, desc, *_ = text.split(sep=\"\\n\", maxsplit=1) + [None, None]\n\n if desc is not None:\n desc = _clean_str(inspect.cleandoc(desc))\n\n yield DocstringDeprecated(\n args=[self.key], description=desc, version=_clean_str(version)\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 61, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "NumpydocParser", "method": "__init__", "focal_method_txt": " def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n \"\"\"\n sections = sections or DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self._setup()", "focal_method_lines": [256, 263], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass Section:\n\n def __init__(self, title: str, key: str) -> None:\n self.title = title\n self.key = key\n\nclass NumpydocParser:\n\n def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n \"\"\"\n sections = sections or DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self._setup()", "has_branch": false, "total_branches": 0} {"prompt_id": 62, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "NumpydocParser", "method": "add_section", "focal_method_txt": " def add_section(self, section: Section):\n \"\"\"Add or replace a section.\n\n :param section: The new section.\n \"\"\"\n\n self.sections[section.title] = section\n self._setup()", "focal_method_lines": [271, 278], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass Section:\n\n def __init__(self, title: str, key: str) -> None:\n self.title = title\n self.key = key\n\nclass NumpydocParser:\n\n def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n \"\"\"\n sections = sections or DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self._setup()\n\n def add_section(self, section: Section):\n \"\"\"Add or replace a section.\n\n :param section: The new section.\n \"\"\"\n\n self.sections[section.title] = section\n self._setup()", "has_branch": false, "total_branches": 0} {"prompt_id": 63, "project": "docstring_parser", "module": "docstring_parser.numpydoc", "class": "NumpydocParser", "method": "parse", "focal_method_txt": " def parse(self, text: str) -> Docstring:\n \"\"\"Parse the numpy-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n # Clean according to PEP-0257\n text = inspect.cleandoc(text)\n\n # Find first title and split on its position\n match = self.titles_re.search(text)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n # Break description into short and long parts\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\n \"\\n\"\n )\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n for match, nextmatch in _pairwise(self.titles_re.finditer(meta_chunk)):\n title = next(g for g in match.groups() if g is not None)\n factory = self.sections[title]\n\n # section chunk starts after the header,\n # ends at the start of the next header\n start = match.end()\n end = nextmatch.start() if nextmatch is not None else None\n ret.meta.extend(factory.parse(meta_chunk[start:end]))\n\n return ret", "focal_method_lines": [280, 322], "in_stack": false, "globals": ["KV_REGEX", "PARAM_KEY_REGEX", "PARAM_OPTIONAL_REGEX", "PARAM_DEFAULT_REGEX", "RETURN_KEY_REGEX", "DEFAULT_SECTIONS"], "type_context": "import inspect\nimport itertools\nimport re\nimport typing as T\nfrom .common import (\n Docstring,\n DocstringDeprecated,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n)\n\nKV_REGEX = re.compile(r\"^[^\\s].*$\", flags=re.M)\nPARAM_KEY_REGEX = re.compile(r\"^(?P.*?)(?:\\s*:\\s*(?P.*?))?$\")\nPARAM_OPTIONAL_REGEX = re.compile(r\"(?P.*?)(?:, optional|\\(optional\\))$\")\nPARAM_DEFAULT_REGEX = re.compile(\n r\"[Dd]efault(?: is | = |: |s to |)\\s*(?P[\\w\\-\\.]+)\"\n)\nRETURN_KEY_REGEX = re.compile(r\"^(?:(?P.*?)\\s*:\\s*)?(?P.*?)$\")\nDEFAULT_SECTIONS = [\n ParamSection(\"Parameters\", \"param\"),\n ParamSection(\"Params\", \"param\"),\n ParamSection(\"Arguments\", \"param\"),\n ParamSection(\"Args\", \"param\"),\n ParamSection(\"Other Parameters\", \"other_param\"),\n ParamSection(\"Other Params\", \"other_param\"),\n ParamSection(\"Other Arguments\", \"other_param\"),\n ParamSection(\"Other Args\", \"other_param\"),\n ParamSection(\"Receives\", \"receives\"),\n ParamSection(\"Receive\", \"receives\"),\n RaisesSection(\"Raises\", \"raises\"),\n RaisesSection(\"Raise\", \"raises\"),\n RaisesSection(\"Warns\", \"warns\"),\n RaisesSection(\"Warn\", \"warns\"),\n ParamSection(\"Attributes\", \"attribute\"),\n ParamSection(\"Attribute\", \"attribute\"),\n ReturnsSection(\"Returns\", \"returns\"),\n ReturnsSection(\"Return\", \"returns\"),\n YieldsSection(\"Yields\", \"yields\"),\n YieldsSection(\"Yield\", \"yields\"),\n Section(\"Examples\", \"examples\"),\n Section(\"Example\", \"examples\"),\n Section(\"Warnings\", \"warnings\"),\n Section(\"Warning\", \"warnings\"),\n Section(\"See Also\", \"see_also\"),\n Section(\"Related\", \"see_also\"),\n Section(\"Notes\", \"notes\"),\n Section(\"Note\", \"notes\"),\n Section(\"References\", \"references\"),\n Section(\"Reference\", \"references\"),\n DeprecationSection(\"deprecated\", \"deprecation\"),\n]\n\nclass NumpydocParser:\n\n def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n \"\"\"\n sections = sections or DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self._setup()\n\n def parse(self, text: str) -> Docstring:\n \"\"\"Parse the numpy-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n # Clean according to PEP-0257\n text = inspect.cleandoc(text)\n\n # Find first title and split on its position\n match = self.titles_re.search(text)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n # Break description into short and long parts\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\n \"\\n\"\n )\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n for match, nextmatch in _pairwise(self.titles_re.finditer(meta_chunk)):\n title = next(g for g in match.groups() if g is not None)\n factory = self.sections[title]\n\n # section chunk starts after the header,\n # ends at the start of the next header\n start = match.end()\n end = nextmatch.start() if nextmatch is not None else None\n ret.meta.extend(factory.parse(meta_chunk[start:end]))\n\n return ret", "has_branch": true, "total_branches": 2} {"prompt_id": 64, "project": "docstring_parser", "module": "docstring_parser.parser", "class": "", "method": "parse", "focal_method_txt": "def parse(text: str, style: Style = Style.auto) -> Docstring:\n \"\"\"Parse the docstring into its components.\n\n :param text: docstring text to parse\n :param style: docstring style\n :returns: parsed docstring representation\n \"\"\"\n\n if style != Style.auto:\n return STYLES[style](text)\n rets = []\n for parse_ in STYLES.values():\n try:\n rets.append(parse_(text))\n except ParseError as e:\n exc = e\n if not rets:\n raise exc\n return sorted(rets, key=lambda d: len(d.meta), reverse=True)[0]", "focal_method_lines": [6, 24], "in_stack": false, "globals": [], "type_context": "from docstring_parser.common import Docstring, ParseError\nfrom docstring_parser.styles import STYLES, Style\n\n\n\ndef parse(text: str, style: Style = Style.auto) -> Docstring:\n \"\"\"Parse the docstring into its components.\n\n :param text: docstring text to parse\n :param style: docstring style\n :returns: parsed docstring representation\n \"\"\"\n\n if style != Style.auto:\n return STYLES[style](text)\n rets = []\n for parse_ in STYLES.values():\n try:\n rets.append(parse_(text))\n except ParseError as e:\n exc = e\n if not rets:\n raise exc\n return sorted(rets, key=lambda d: len(d.meta), reverse=True)[0]", "has_branch": true, "total_branches": 2} {"prompt_id": 65, "project": "docstring_parser", "module": "docstring_parser.rest", "class": "", "method": "parse", "focal_method_txt": "def parse(text: str) -> Docstring:\n \"\"\"Parse the ReST-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n text = inspect.cleandoc(text)\n match = re.search(\"^:\", text, flags=re.M)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\"\\n\")\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n for match in re.finditer(\n r\"(^:.*?)(?=^:|\\Z)\", meta_chunk, flags=re.S | re.M\n ):\n chunk = match.group(0)\n if not chunk:\n continue\n try:\n args_chunk, desc_chunk = chunk.lstrip(\":\").split(\":\", 1)\n except ValueError:\n raise ParseError(\n 'Error parsing meta information near \"{}\".'.format(chunk)\n )\n args = args_chunk.split()\n desc = desc_chunk.strip()\n if \"\\n\" in desc:\n first_line, rest = desc.split(\"\\n\", 1)\n desc = first_line + \"\\n\" + inspect.cleandoc(rest)\n\n ret.meta.append(_build_meta(args, desc))\n\n return ret", "focal_method_lines": [85, 131], "in_stack": false, "globals": [], "type_context": "import inspect\nimport re\nimport typing as T\nfrom .common import (\n PARAM_KEYWORDS,\n RAISES_KEYWORDS,\n RETURNS_KEYWORDS,\n YIELDS_KEYWORDS,\n Docstring,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n ParseError,\n)\n\n\n\ndef parse(text: str) -> Docstring:\n \"\"\"Parse the ReST-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring()\n if not text:\n return ret\n\n text = inspect.cleandoc(text)\n match = re.search(\"^:\", text, flags=re.M)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\"\\n\")\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n for match in re.finditer(\n r\"(^:.*?)(?=^:|\\Z)\", meta_chunk, flags=re.S | re.M\n ):\n chunk = match.group(0)\n if not chunk:\n continue\n try:\n args_chunk, desc_chunk = chunk.lstrip(\":\").split(\":\", 1)\n except ValueError:\n raise ParseError(\n 'Error parsing meta information near \"{}\".'.format(chunk)\n )\n args = args_chunk.split()\n desc = desc_chunk.strip()\n if \"\\n\" in desc:\n first_line, rest = desc.split(\"\\n\", 1)\n desc = first_line + \"\\n\" + inspect.cleandoc(rest)\n\n ret.meta.append(_build_meta(args, desc))\n\n return ret", "has_branch": true, "total_branches": 2} {"prompt_id": 66, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "chunk", "focal_method_txt": "def chunk(n: int, iterable: Iterable[T]) -> Iterator[List[T]]:\n r\"\"\"Split the iterable into chunks, with each chunk containing no more than ``n`` elements.\n\n .. code:: python\n\n >>> list(chunk(3, range(10)))\n [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n :param n: The maximum number of elements in one chunk.\n :param iterable: The iterable.\n :return: An iterator over chunks.\n \"\"\"\n if n <= 0:\n raise ValueError(\"`n` should be positive\")\n group = []\n for x in iterable:\n group.append(x)\n if len(group) == n:\n yield group\n group = []\n if len(group) > 0:\n yield group", "focal_method_lines": [22, 43], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef chunk(n: int, iterable: Iterable[T]) -> Iterator[List[T]]:\n r\"\"\"Split the iterable into chunks, with each chunk containing no more than ``n`` elements.\n\n .. code:: python\n\n >>> list(chunk(3, range(10)))\n [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n :param n: The maximum number of elements in one chunk.\n :param iterable: The iterable.\n :return: An iterator over chunks.\n \"\"\"\n if n <= 0:\n raise ValueError(\"`n` should be positive\")\n group = []\n for x in iterable:\n group.append(x)\n if len(group) == n:\n yield group\n group = []\n if len(group) > 0:\n yield group", "has_branch": true, "total_branches": 2} {"prompt_id": 67, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "take", "focal_method_txt": "def take(n: int, iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Take the first :attr:`n` elements from an iterable.\n\n .. code:: python\n\n >>> list(take(5, range(1000000)))\n [0, 1, 2, 3, 4]\n\n :param n: The number of elements to take.\n :param iterable: The iterable.\n :return: An iterator returning the first :attr:`n` elements from the iterable.\n \"\"\"\n if n < 0:\n raise ValueError(\"`n` should be non-negative\")\n try:\n it = iter(iterable)\n for _ in range(n):\n yield next(it)\n except StopIteration:\n pass", "focal_method_lines": [46, 65], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef take(n: int, iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Take the first :attr:`n` elements from an iterable.\n\n .. code:: python\n\n >>> list(take(5, range(1000000)))\n [0, 1, 2, 3, 4]\n\n :param n: The number of elements to take.\n :param iterable: The iterable.\n :return: An iterator returning the first :attr:`n` elements from the iterable.\n \"\"\"\n if n < 0:\n raise ValueError(\"`n` should be non-negative\")\n try:\n it = iter(iterable)\n for _ in range(n):\n yield next(it)\n except StopIteration:\n pass", "has_branch": true, "total_branches": 2} {"prompt_id": 68, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "drop", "focal_method_txt": "def drop(n: int, iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Drop the first :attr:`n` elements from an iterable, and return the rest as an iterator.\n\n .. code:: python\n\n >>> next(drop(5, range(1000000)))\n 5\n\n :param n: The number of elements to drop.\n :param iterable: The iterable.\n :return: An iterator returning the remaining part of the iterable after the first :attr:`n` elements.\n \"\"\"\n if n < 0:\n raise ValueError(\"`n` should be non-negative\")\n try:\n it = iter(iterable)\n for _ in range(n):\n next(it)\n yield from it\n except StopIteration:\n pass", "focal_method_lines": [68, 88], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef drop(n: int, iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Drop the first :attr:`n` elements from an iterable, and return the rest as an iterator.\n\n .. code:: python\n\n >>> next(drop(5, range(1000000)))\n 5\n\n :param n: The number of elements to drop.\n :param iterable: The iterable.\n :return: An iterator returning the remaining part of the iterable after the first :attr:`n` elements.\n \"\"\"\n if n < 0:\n raise ValueError(\"`n` should be non-negative\")\n try:\n it = iter(iterable)\n for _ in range(n):\n next(it)\n yield from it\n except StopIteration:\n pass", "has_branch": true, "total_branches": 2} {"prompt_id": 69, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "drop_until", "focal_method_txt": "def drop_until(pred_fn: Callable[[T], bool], iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Drop elements from the iterable until an element that satisfies the predicate is encountered. Similar to the\n built-in :py:func:`filter` function, but only applied to a prefix of the iterable.\n\n .. code:: python\n\n >>> list(drop_until(lambda x: x > 5, range(10)))\n [6, 7, 8, 9]\n\n :param pred_fn: The predicate that returned elements should satisfy.\n :param iterable: The iterable.\n :return: The iterator after dropping elements.\n \"\"\"\n iterator = iter(iterable)\n for item in iterator:\n if not pred_fn(item):\n continue\n yield item\n break\n yield from iterator", "focal_method_lines": [91, 110], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef drop_until(pred_fn: Callable[[T], bool], iterable: Iterable[T]) -> Iterator[T]:\n r\"\"\"Drop elements from the iterable until an element that satisfies the predicate is encountered. Similar to the\n built-in :py:func:`filter` function, but only applied to a prefix of the iterable.\n\n .. code:: python\n\n >>> list(drop_until(lambda x: x > 5, range(10)))\n [6, 7, 8, 9]\n\n :param pred_fn: The predicate that returned elements should satisfy.\n :param iterable: The iterable.\n :return: The iterator after dropping elements.\n \"\"\"\n iterator = iter(iterable)\n for item in iterator:\n if not pred_fn(item):\n continue\n yield item\n break\n yield from iterator", "has_branch": true, "total_branches": 2} {"prompt_id": 70, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "split_by", "focal_method_txt": "def split_by(iterable: Iterable[A], empty_segments: bool = False, *, criterion=None, separator=None) \\\n -> Iterator[List[A]]:\n r\"\"\"Split a list into sub-lists by dropping certain elements. Exactly one of ``criterion`` and ``separator`` must be\n specified. For example:\n\n .. code:: python\n\n >>> list(split_by(range(10), criterion=lambda x: x % 3 == 0))\n [[1, 2], [4, 5], [7, 8]]\n\n >>> list(split_by(\" Split by: \", empty_segments=True, separator='.'))\n [[], ['S', 'p', 'l', 'i', 't'], ['b', 'y', ':'], []]\n\n :param iterable: The list to split.\n :param empty_segments: If ``True``, include an empty list in cases where two adjacent elements satisfy\n the criterion.\n :param criterion: The criterion to decide whether to drop an element.\n :param separator: The separator for sub-lists. An element is dropped if it is equal to ``parameter``.\n :return: List of sub-lists.\n \"\"\"\n if not ((criterion is None) ^ (separator is None)):\n raise ValueError(\"Exactly one of `criterion` and `separator` should be specified\")\n if criterion is None:\n criterion = lambda x: x == separator\n group = []\n for x in iterable:\n if not criterion(x):\n group.append(x)\n else:\n if len(group) > 0 or empty_segments:\n yield group\n group = []\n if len(group) > 0 or empty_segments:\n yield group", "focal_method_lines": [123, 156], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef split_by(iterable: Iterable[A], empty_segments: bool = False, *, criterion=None, separator=None) \\\n -> Iterator[List[A]]:\n r\"\"\"Split a list into sub-lists by dropping certain elements. Exactly one of ``criterion`` and ``separator`` must be\n specified. For example:\n\n .. code:: python\n\n >>> list(split_by(range(10), criterion=lambda x: x % 3 == 0))\n [[1, 2], [4, 5], [7, 8]]\n\n >>> list(split_by(\" Split by: \", empty_segments=True, separator='.'))\n [[], ['S', 'p', 'l', 'i', 't'], ['b', 'y', ':'], []]\n\n :param iterable: The list to split.\n :param empty_segments: If ``True``, include an empty list in cases where two adjacent elements satisfy\n the criterion.\n :param criterion: The criterion to decide whether to drop an element.\n :param separator: The separator for sub-lists. An element is dropped if it is equal to ``parameter``.\n :return: List of sub-lists.\n \"\"\"\n if not ((criterion is None) ^ (separator is None)):\n raise ValueError(\"Exactly one of `criterion` and `separator` should be specified\")\n if criterion is None:\n criterion = lambda x: x == separator\n group = []\n for x in iterable:\n if not criterion(x):\n group.append(x)\n else:\n if len(group) > 0 or empty_segments:\n yield group\n group = []\n if len(group) > 0 or empty_segments:\n yield group", "has_branch": true, "total_branches": 2} {"prompt_id": 71, "project": "flutes", "module": "flutes.iterator", "class": "", "method": "scanl", "focal_method_txt": "def scanl(func, iterable, *args):\n r\"\"\"Computes the intermediate results of :py:func:`~functools.reduce`. Equivalent to Haskell's ``scanl``. For\n example:\n\n .. code:: python\n\n >>> list(scanl(operator.add, [1, 2, 3, 4], 0))\n [0, 1, 3, 6, 10]\n >>> list(scanl(lambda s, x: x + s, ['a', 'b', 'c', 'd']))\n ['a', 'ba', 'cba', 'dcba']\n\n Learn more at `Learn You a Haskell: Higher Order Functions `_.\n\n :param func: The function to apply. This should be a binary function where the arguments are: the accumulator,\n and the current element.\n :param iterable: The list of elements to iteratively apply the function to.\n :param initial: The initial value for the accumulator. If not supplied, the first element in the list is used.\n :return: The intermediate results at each step.\n \"\"\"\n iterable = iter(iterable)\n if len(args) == 1:\n acc = args[0]\n elif len(args) == 0:\n acc = next(iterable)\n else:\n raise ValueError(\"Too many arguments\")\n yield acc\n for x in iterable:\n acc = func(acc, x)\n yield acc", "focal_method_lines": [167, 196], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\ndef scanl(func, iterable, *args):\n r\"\"\"Computes the intermediate results of :py:func:`~functools.reduce`. Equivalent to Haskell's ``scanl``. For\n example:\n\n .. code:: python\n\n >>> list(scanl(operator.add, [1, 2, 3, 4], 0))\n [0, 1, 3, 6, 10]\n >>> list(scanl(lambda s, x: x + s, ['a', 'b', 'c', 'd']))\n ['a', 'ba', 'cba', 'dcba']\n\n Learn more at `Learn You a Haskell: Higher Order Functions `_.\n\n :param func: The function to apply. This should be a binary function where the arguments are: the accumulator,\n and the current element.\n :param iterable: The list of elements to iteratively apply the function to.\n :param initial: The initial value for the accumulator. If not supplied, the first element in the list is used.\n :return: The intermediate results at each step.\n \"\"\"\n iterable = iter(iterable)\n if len(args) == 1:\n acc = args[0]\n elif len(args) == 0:\n acc = next(iterable)\n else:\n raise ValueError(\"Too many arguments\")\n yield acc\n for x in iterable:\n acc = func(acc, x)\n yield acc", "has_branch": true, "total_branches": 2} {"prompt_id": 72, "project": "flutes", "module": "flutes.iterator", "class": "LazyList", "method": "__iter__", "focal_method_txt": " def __iter__(self):\n if self.exhausted:\n return iter(self.list)\n return self.LazyListIterator(self)", "focal_method_lines": [257, 260], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass LazyList(Generic[T], Sequence[T]):\n\n def __init__(self, iterable: Iterable[T]):\n self.iter = iter(iterable)\n self.exhausted = False\n self.list: List[T] = []\n\n def __iter__(self):\n if self.exhausted:\n return iter(self.list)\n return self.LazyListIterator(self)", "has_branch": true, "total_branches": 2} {"prompt_id": 73, "project": "flutes", "module": "flutes.iterator", "class": "LazyList", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, idx):\n if isinstance(idx, slice):\n self._fetch_until(idx.stop)\n else:\n self._fetch_until(idx)\n return self.list[idx]", "focal_method_lines": [280, 285], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass LazyList(Generic[T], Sequence[T]):\n\n def __init__(self, iterable: Iterable[T]):\n self.iter = iter(iterable)\n self.exhausted = False\n self.list: List[T] = []\n\n def __getitem__(self, idx):\n if isinstance(idx, slice):\n self._fetch_until(idx.stop)\n else:\n self._fetch_until(idx)\n return self.list[idx]", "has_branch": true, "total_branches": 2} {"prompt_id": 74, "project": "flutes", "module": "flutes.iterator", "class": "LazyList", "method": "__len__", "focal_method_txt": " def __len__(self):\n if self.exhausted:\n return len(self.list)\n else:\n raise TypeError(\"__len__ is not available before the iterable is depleted\")", "focal_method_lines": [287, 291], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass LazyList(Generic[T], Sequence[T]):\n\n def __init__(self, iterable: Iterable[T]):\n self.iter = iter(iterable)\n self.exhausted = False\n self.list: List[T] = []\n\n def __len__(self):\n if self.exhausted:\n return len(self.list)\n else:\n raise TypeError(\"__len__ is not available before the iterable is depleted\")", "has_branch": true, "total_branches": 2} {"prompt_id": 75, "project": "flutes", "module": "flutes.iterator", "class": "Range", "method": "__next__", "focal_method_txt": " def __next__(self) -> int:\n if self.val >= self.r:\n raise StopIteration\n result = self.val\n self.val += self.step\n return result", "focal_method_lines": [332, 337], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass Range(Sequence[int]):\n\n def __init__(self, *args):\n if len(args) == 0 or len(args) > 3:\n raise ValueError(\"Range should be called the same way as the builtin `range`\")\n if len(args) == 1:\n self.l = 0\n self.r = args[0]\n self.step = 1\n else:\n self.l = args[0]\n self.r = args[1]\n self.step = 1 if len(args) == 2 else args[2]\n self.val = self.l\n self.length = (self.r - self.l) // self.step\n\n def __next__(self) -> int:\n if self.val >= self.r:\n raise StopIteration\n result = self.val\n self.val += self.step\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 76, "project": "flutes", "module": "flutes.iterator", "class": "Range", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, item):\n if isinstance(item, slice):\n return [self._get_idx(idx) for idx in range(*item.indices(self.length))]\n if item < 0:\n item = self.length + item\n return self._get_idx(item)", "focal_method_lines": [351, 356], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass Range(Sequence[int]):\n\n def __init__(self, *args):\n if len(args) == 0 or len(args) > 3:\n raise ValueError(\"Range should be called the same way as the builtin `range`\")\n if len(args) == 1:\n self.l = 0\n self.r = args[0]\n self.step = 1\n else:\n self.l = args[0]\n self.r = args[1]\n self.step = 1 if len(args) == 2 else args[2]\n self.val = self.l\n self.length = (self.r - self.l) // self.step\n\n def __getitem__(self, item):\n if isinstance(item, slice):\n return [self._get_idx(idx) for idx in range(*item.indices(self.length))]\n if item < 0:\n item = self.length + item\n return self._get_idx(item)", "has_branch": true, "total_branches": 2} {"prompt_id": 77, "project": "flutes", "module": "flutes.iterator", "class": "MapList", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, item):\n if isinstance(item, int):\n return self.func(self.list[item])\n return [self.func(x) for x in self.list[item]]", "focal_method_lines": [391, 394], "in_stack": false, "globals": ["__all__", "T", "A", "B", "R"], "type_context": "import weakref\nfrom typing import Callable, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar, overload\n\n__all__ = [\n \"chunk\",\n \"take\",\n \"drop\",\n \"drop_until\",\n \"split_by\",\n \"scanl\",\n \"scanr\",\n \"LazyList\",\n \"Range\",\n \"MapList\",\n]\nT = TypeVar('T')\nA = TypeVar('A')\nB = TypeVar('B')\nR = TypeVar('R')\n\nclass MapList(Generic[R], Sequence[R]):\n\n def __init__(self, func: Callable[[T], R], lst: Sequence[T]):\n self.func = func\n self.list = lst\n\n def __getitem__(self, item):\n if isinstance(item, int):\n return self.func(self.list[item])\n return [self.func(x) for x in self.list[item]]", "has_branch": true, "total_branches": 2} {"prompt_id": 78, "project": "flutils", "module": "flutils.codecs.b64", "class": "", "method": "encode", "focal_method_txt": "def encode(\n text: _STR,\n errors: _STR = 'strict'\n) -> Tuple[bytes, int]:\n \"\"\"Convert the given ``text`` of base64 characters into the base64\n decoded bytes.\n\n Args:\n text (str): The string input. The given string input can span\n across many lines and be indented any number of spaces.\n errors (str): Not used. This argument exists to meet the\n interface requirements. Any value given to this argument\n is ignored.\n\n Returns:\n bytes: The given ``text`` converted into base64 bytes.\n int: The length of the returned bytes.\n \"\"\"\n # Convert the given 'text', that are of type UserString into a str.\n text_input = str(text)\n\n # Cleanup whitespace.\n text_str = text_input.strip()\n text_str = '\\n'.join(\n filter(\n lambda x: len(x) > 0,\n map(lambda x: x.strip(), text_str.strip().splitlines())\n )\n )\n\n # Convert the cleaned text into utf8 bytes\n text_bytes = text_str.encode('utf-8')\n try:\n out = base64.decodebytes(text_bytes)\n except Error as e:\n raise UnicodeEncodeError(\n 'b64',\n text_input,\n 0,\n len(text),\n (\n f'{text_str!r} is not a proper bas64 character string: '\n f'{e}'\n )\n )\n return out, len(text)", "focal_method_lines": [16, 61], "in_stack": true, "globals": ["_STR", "NAME"], "type_context": "import base64\nimport codecs\nfrom binascii import Error\nfrom collections import UserString\nfrom typing import ByteString as _ByteString\nfrom typing import (\n Optional,\n Tuple,\n Union,\n)\n\n_STR = Union[str, UserString]\nNAME = __name__.split('.')[-1]\n\ndef encode(\n text: _STR,\n errors: _STR = 'strict'\n) -> Tuple[bytes, int]:\n \"\"\"Convert the given ``text`` of base64 characters into the base64\n decoded bytes.\n\n Args:\n text (str): The string input. The given string input can span\n across many lines and be indented any number of spaces.\n errors (str): Not used. This argument exists to meet the\n interface requirements. Any value given to this argument\n is ignored.\n\n Returns:\n bytes: The given ``text`` converted into base64 bytes.\n int: The length of the returned bytes.\n \"\"\"\n # Convert the given 'text', that are of type UserString into a str.\n text_input = str(text)\n\n # Cleanup whitespace.\n text_str = text_input.strip()\n text_str = '\\n'.join(\n filter(\n lambda x: len(x) > 0,\n map(lambda x: x.strip(), text_str.strip().splitlines())\n )\n )\n\n # Convert the cleaned text into utf8 bytes\n text_bytes = text_str.encode('utf-8')\n try:\n out = base64.decodebytes(text_bytes)\n except Error as e:\n raise UnicodeEncodeError(\n 'b64',\n text_input,\n 0,\n len(text),\n (\n f'{text_str!r} is not a proper bas64 character string: '\n f'{e}'\n )\n )\n return out, len(text)", "has_branch": false, "total_branches": 0} {"prompt_id": 79, "project": "flutils", "module": "flutils.codecs.b64", "class": "", "method": "register", "focal_method_txt": "def register() -> None:\n \"\"\"Register the ``b64`` codec with Python.\"\"\"\n try:\n codecs.getdecoder(NAME)\n except LookupError:\n codecs.register(_get_codec_info)", "focal_method_lines": [109, 114], "in_stack": true, "globals": ["_STR", "NAME"], "type_context": "import base64\nimport codecs\nfrom binascii import Error\nfrom collections import UserString\nfrom typing import ByteString as _ByteString\nfrom typing import (\n Optional,\n Tuple,\n Union,\n)\n\n_STR = Union[str, UserString]\nNAME = __name__.split('.')[-1]\n\ndef register() -> None:\n \"\"\"Register the ``b64`` codec with Python.\"\"\"\n try:\n codecs.getdecoder(NAME)\n except LookupError:\n codecs.register(_get_codec_info)", "has_branch": false, "total_branches": 0} {"prompt_id": 80, "project": "flutils", "module": "flutils.codecs.raw_utf8_escape", "class": "", "method": "decode", "focal_method_txt": "def decode(\n data: _ByteString,\n errors: _Str = 'strict'\n) -> Tuple[str, int]:\n \"\"\"Convert a bytes type of escaped utf8 hexadecimal to a string.\n\n Args:\n data (bytes or bytearray or memoryview): The escaped utf8\n hexadecimal bytes.\n errors (str or :obj:`~UserString`): The error checking level.\n\n Returns:\n str: The given ``data`` (of escaped utf8 hexadecimal bytes)\n converted into a :obj:`str`.\n int: The number of the given ``data`` bytes consumed.\n\n Raises:\n UnicodeDecodeError: if the given ``data`` contains escaped\n utf8 hexadecimal that references invalid utf8 bytes.\n\n\n \"\"\"\n # Convert memoryview and bytearray objects to bytes.\n data_bytes = bytes(data)\n\n # Convert the given 'errors', that are of type UserString into a str.\n errors_input = str(errors)\n\n # Convert the utf8 bytes into a string of latin-1 characters.\n # This basically maps the exact utf8 bytes to the string. Also,\n # this converts any escaped hexadecimal sequences \\\\xHH into\n # \\xHH bytes.\n text_str_latin1 = data_bytes.decode('unicode_escape')\n\n # Convert the string of latin-1 characters (which are actually\n # utf8 characters) into bytes.\n text_bytes_utf8 = text_str_latin1.encode('latin1')\n\n # Convert the utf8 bytes into a string.\n try:\n out = text_bytes_utf8.decode('utf-8', errors=errors_input)\n except UnicodeDecodeError as e:\n raise UnicodeDecodeError(\n 'eutf8h',\n data_bytes,\n e.start,\n e.end,\n e.reason\n )\n return out, len(data)", "focal_method_lines": [90, 139], "in_stack": true, "globals": ["_Str", "NAME"], "type_context": "import codecs\nfrom collections import UserString\nfrom functools import reduce\nfrom typing import ByteString as _ByteString\nfrom typing import (\n Generator,\n Optional,\n Tuple,\n Union,\n cast,\n)\n\n_Str = Union[str, UserString]\nNAME = __name__.split('.')[-1]\n\ndef decode(\n data: _ByteString,\n errors: _Str = 'strict'\n) -> Tuple[str, int]:\n \"\"\"Convert a bytes type of escaped utf8 hexadecimal to a string.\n\n Args:\n data (bytes or bytearray or memoryview): The escaped utf8\n hexadecimal bytes.\n errors (str or :obj:`~UserString`): The error checking level.\n\n Returns:\n str: The given ``data`` (of escaped utf8 hexadecimal bytes)\n converted into a :obj:`str`.\n int: The number of the given ``data`` bytes consumed.\n\n Raises:\n UnicodeDecodeError: if the given ``data`` contains escaped\n utf8 hexadecimal that references invalid utf8 bytes.\n\n\n \"\"\"\n # Convert memoryview and bytearray objects to bytes.\n data_bytes = bytes(data)\n\n # Convert the given 'errors', that are of type UserString into a str.\n errors_input = str(errors)\n\n # Convert the utf8 bytes into a string of latin-1 characters.\n # This basically maps the exact utf8 bytes to the string. Also,\n # this converts any escaped hexadecimal sequences \\\\xHH into\n # \\xHH bytes.\n text_str_latin1 = data_bytes.decode('unicode_escape')\n\n # Convert the string of latin-1 characters (which are actually\n # utf8 characters) into bytes.\n text_bytes_utf8 = text_str_latin1.encode('latin1')\n\n # Convert the utf8 bytes into a string.\n try:\n out = text_bytes_utf8.decode('utf-8', errors=errors_input)\n except UnicodeDecodeError as e:\n raise UnicodeDecodeError(\n 'eutf8h',\n data_bytes,\n e.start,\n e.end,\n e.reason\n )\n return out, len(data)", "has_branch": false, "total_branches": 0} {"prompt_id": 81, "project": "flutils", "module": "flutils.codecs.raw_utf8_escape", "class": "", "method": "register", "focal_method_txt": "def register() -> None:\n try:\n codecs.getdecoder(NAME)\n except LookupError:\n codecs.register(_get_codec_info)", "focal_method_lines": [157, 161], "in_stack": true, "globals": ["_Str", "NAME"], "type_context": "import codecs\nfrom collections import UserString\nfrom functools import reduce\nfrom typing import ByteString as _ByteString\nfrom typing import (\n Generator,\n Optional,\n Tuple,\n Union,\n cast,\n)\n\n_Str = Union[str, UserString]\nNAME = __name__.split('.')[-1]\n\ndef register() -> None:\n try:\n codecs.getdecoder(NAME)\n except LookupError:\n codecs.register(_get_codec_info)", "has_branch": false, "total_branches": 0} {"prompt_id": 82, "project": "flutils", "module": "flutils.decorators", "class": "cached_property", "method": "__get__", "focal_method_txt": " def __get__(self, obj: Any, cls):\n if obj is None:\n return self\n\n if asyncio.iscoroutinefunction(self.func):\n return self._wrap_in_coroutine(obj)\n\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n return value", "focal_method_lines": [60, 68], "in_stack": true, "globals": ["__all__"], "type_context": "import asyncio\nfrom typing import Any\n\n__all__ = ['cached_property']\n\nclass cached_property:\n\n def __init__(self, func):\n self.__doc__ = getattr(func, \"__doc__\")\n self.func = func\n\n def __get__(self, obj: Any, cls):\n if obj is None:\n return self\n\n if asyncio.iscoroutinefunction(self.func):\n return self._wrap_in_coroutine(obj)\n\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 83, "project": "flutils", "module": "flutils.namedtupleutils", "class": "", "method": "to_namedtuple", "focal_method_txt": "def to_namedtuple(obj: _AllowedTypes) -> Union[NamedTuple, Tuple, List]:\n \"\"\"Convert particular objects into a namedtuple.\n\n Args:\n obj: The object to be converted (or have it's contents converted) to\n a :obj:`NamedTuple `.\n\n If the given type is of :obj:`list` or :obj:`tuple`, each item will be\n recursively converted to a :obj:`NamedTuple `\n provided the items can be converted. Items that cannot be converted\n will still exist in the returned object.\n\n If the given type is of :obj:`list` the return value will be a new\n :obj:`list`. This means the items are not changed in the given\n ``obj``.\n\n If the given type is of :obj:`Mapping `\n (:obj:`dict`), keys that can be proper identifiers will become attributes\n on the returned :obj:`NamedTuple `. Additionally,\n the attributes of the returned :obj:`NamedTuple `\n are sorted alphabetically.\n\n If the given type is of :obj:`OrderedDict `,\n the attributes of the returned :obj:`NamedTuple `\n keep the same order as the given\n :obj:`OrderedDict ` keys.\n\n If the given type is of :obj:`SimpleNamespace `,\n The attributes are sorted alphabetically in the returned\n :obj:`NamedTuple `.\n\n Any identifier (key or attribute name) that starts with an underscore\n cannot be used as a :obj:`NamedTuple ` attribute.\n\n All values are recursively converted. This means a dictionary that\n contains another dictionary, as one of it's values, will be converted\n to a :obj:`NamedTuple ` with the attribute's\n value also converted to a :obj:`NamedTuple `.\n\n :rtype:\n :obj:`list`\n\n A list with any of it's values converted to a\n :obj:`NamedTuple `.\n\n :obj:`tuple`\n\n A tuple with any of it's values converted to a\n :obj:`NamedTuple `.\n\n :obj:`NamedTuple `.\n\n Example:\n >>> from flutils.namedtupleutils import to_namedtuple\n >>> dic = {'a': 1, 'b': 2}\n >>> to_namedtuple(dic)\n NamedTuple(a=1, b=2)\n \"\"\"\n return _to_namedtuple(obj)", "focal_method_lines": [31, 89], "in_stack": true, "globals": ["__all__", "_AllowedTypes"], "type_context": "from collections import (\n OrderedDict,\n namedtuple,\n)\nfrom collections.abc import (\n Mapping,\n Sequence,\n)\nfrom functools import singledispatch\nfrom types import SimpleNamespace\nfrom typing import (\n Any,\n List,\n NamedTuple,\n Tuple,\n Union,\n cast,\n)\nfrom flutils.validators import validate_identifier\n\n__all__ = ['to_namedtuple']\n_AllowedTypes = Union[\n List,\n Mapping,\n NamedTuple,\n SimpleNamespace,\n Tuple,\n]\n\ndef to_namedtuple(obj: _AllowedTypes) -> Union[NamedTuple, Tuple, List]:\n \"\"\"Convert particular objects into a namedtuple.\n\n Args:\n obj: The object to be converted (or have it's contents converted) to\n a :obj:`NamedTuple `.\n\n If the given type is of :obj:`list` or :obj:`tuple`, each item will be\n recursively converted to a :obj:`NamedTuple `\n provided the items can be converted. Items that cannot be converted\n will still exist in the returned object.\n\n If the given type is of :obj:`list` the return value will be a new\n :obj:`list`. This means the items are not changed in the given\n ``obj``.\n\n If the given type is of :obj:`Mapping `\n (:obj:`dict`), keys that can be proper identifiers will become attributes\n on the returned :obj:`NamedTuple `. Additionally,\n the attributes of the returned :obj:`NamedTuple `\n are sorted alphabetically.\n\n If the given type is of :obj:`OrderedDict `,\n the attributes of the returned :obj:`NamedTuple `\n keep the same order as the given\n :obj:`OrderedDict ` keys.\n\n If the given type is of :obj:`SimpleNamespace `,\n The attributes are sorted alphabetically in the returned\n :obj:`NamedTuple `.\n\n Any identifier (key or attribute name) that starts with an underscore\n cannot be used as a :obj:`NamedTuple ` attribute.\n\n All values are recursively converted. This means a dictionary that\n contains another dictionary, as one of it's values, will be converted\n to a :obj:`NamedTuple ` with the attribute's\n value also converted to a :obj:`NamedTuple `.\n\n :rtype:\n :obj:`list`\n\n A list with any of it's values converted to a\n :obj:`NamedTuple `.\n\n :obj:`tuple`\n\n A tuple with any of it's values converted to a\n :obj:`NamedTuple `.\n\n :obj:`NamedTuple `.\n\n Example:\n >>> from flutils.namedtupleutils import to_namedtuple\n >>> dic = {'a': 1, 'b': 2}\n >>> to_namedtuple(dic)\n NamedTuple(a=1, b=2)\n \"\"\"\n return _to_namedtuple(obj)", "has_branch": false, "total_branches": 0} {"prompt_id": 84, "project": "flutils", "module": "flutils.objutils", "class": "", "method": "has_any_attrs", "focal_method_txt": "def has_any_attrs(obj: _Any, *attrs: str) -> bool:\n \"\"\"Check if the given ``obj`` has **ANY** of the given ``*attrs``.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if any of the given ``*attrs`` exist on the given\n ``obj``;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_any_attrs\n >>> has_any_attrs(dict(),'get','keys','items','values','something')\n True\n \"\"\"\n for attr in attrs:\n if hasattr(obj, attr) is True:\n return True\n return False", "focal_method_lines": [35, 57], "in_stack": true, "globals": ["__all__", "_LIST_LIKE"], "type_context": "from collections import (\n UserList,\n deque,\n)\nfrom collections.abc import (\n Iterator,\n KeysView,\n ValuesView,\n)\nfrom typing import Any as _Any\n\n__all__ = [\n 'has_any_attrs',\n 'has_any_callables',\n 'has_attrs',\n 'has_callables',\n 'is_list_like',\n 'is_subclass_of_any',\n]\n_LIST_LIKE = (\n list,\n set,\n frozenset,\n tuple,\n deque,\n Iterator,\n ValuesView,\n KeysView,\n UserList\n)\n\ndef has_any_attrs(obj: _Any, *attrs: str) -> bool:\n \"\"\"Check if the given ``obj`` has **ANY** of the given ``*attrs``.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if any of the given ``*attrs`` exist on the given\n ``obj``;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_any_attrs\n >>> has_any_attrs(dict(),'get','keys','items','values','something')\n True\n \"\"\"\n for attr in attrs:\n if hasattr(obj, attr) is True:\n return True\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 85, "project": "flutils", "module": "flutils.objutils", "class": "", "method": "has_any_callables", "focal_method_txt": "def has_any_callables(obj: _Any, *attrs: str) -> bool:\n \"\"\"Check if the given ``obj`` has **ANY** of the given ``attrs`` and are\n callable.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if ANY of the given ``*attrs`` exist on the given ``obj``\n and ANY are callable;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_any_callables\n >>> has_any_callables(dict(),'get','keys','items','values','foo')\n True\n \"\"\"\n if has_any_attrs(obj, *attrs) is True:\n for attr in attrs:\n if callable(getattr(obj, attr)) is True:\n return True\n return False", "focal_method_lines": [60, 84], "in_stack": true, "globals": ["__all__", "_LIST_LIKE"], "type_context": "from collections import (\n UserList,\n deque,\n)\nfrom collections.abc import (\n Iterator,\n KeysView,\n ValuesView,\n)\nfrom typing import Any as _Any\n\n__all__ = [\n 'has_any_attrs',\n 'has_any_callables',\n 'has_attrs',\n 'has_callables',\n 'is_list_like',\n 'is_subclass_of_any',\n]\n_LIST_LIKE = (\n list,\n set,\n frozenset,\n tuple,\n deque,\n Iterator,\n ValuesView,\n KeysView,\n UserList\n)\n\ndef has_any_callables(obj: _Any, *attrs: str) -> bool:\n \"\"\"Check if the given ``obj`` has **ANY** of the given ``attrs`` and are\n callable.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if ANY of the given ``*attrs`` exist on the given ``obj``\n and ANY are callable;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_any_callables\n >>> has_any_callables(dict(),'get','keys','items','values','foo')\n True\n \"\"\"\n if has_any_attrs(obj, *attrs) is True:\n for attr in attrs:\n if callable(getattr(obj, attr)) is True:\n return True\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 86, "project": "flutils", "module": "flutils.objutils", "class": "", "method": "has_attrs", "focal_method_txt": "def has_attrs(\n obj: _Any,\n *attrs: str\n) -> bool:\n \"\"\"Check if given ``obj`` has all the given ``*attrs``.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if all the given ``*attrs`` exist on the given ``obj``;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_attrs\n >>> has_attrs(dict(),'get','keys','items','values')\n True\n \"\"\"\n for attr in attrs:\n if hasattr(obj, attr) is False:\n return False\n return True", "focal_method_lines": [87, 111], "in_stack": true, "globals": ["__all__", "_LIST_LIKE"], "type_context": "from collections import (\n UserList,\n deque,\n)\nfrom collections.abc import (\n Iterator,\n KeysView,\n ValuesView,\n)\nfrom typing import Any as _Any\n\n__all__ = [\n 'has_any_attrs',\n 'has_any_callables',\n 'has_attrs',\n 'has_callables',\n 'is_list_like',\n 'is_subclass_of_any',\n]\n_LIST_LIKE = (\n list,\n set,\n frozenset,\n tuple,\n deque,\n Iterator,\n ValuesView,\n KeysView,\n UserList\n)\n\ndef has_attrs(\n obj: _Any,\n *attrs: str\n) -> bool:\n \"\"\"Check if given ``obj`` has all the given ``*attrs``.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if all the given ``*attrs`` exist on the given ``obj``;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_attrs\n >>> has_attrs(dict(),'get','keys','items','values')\n True\n \"\"\"\n for attr in attrs:\n if hasattr(obj, attr) is False:\n return False\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 87, "project": "flutils", "module": "flutils.objutils", "class": "", "method": "has_callables", "focal_method_txt": "def has_callables(\n obj: _Any,\n *attrs: str\n) -> bool:\n \"\"\"Check if given ``obj`` has all the given ``attrs`` and are callable.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if all the given ``*attrs`` exist on the given ``obj``\n and all are callable;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_callables\n >>> has_callables(dict(),'get','keys','items','values')\n True\n \"\"\"\n if has_attrs(obj, *attrs) is True:\n for attr in attrs:\n if callable(getattr(obj, attr)) is False:\n return False\n return True\n return False", "focal_method_lines": [115, 142], "in_stack": true, "globals": ["__all__", "_LIST_LIKE"], "type_context": "from collections import (\n UserList,\n deque,\n)\nfrom collections.abc import (\n Iterator,\n KeysView,\n ValuesView,\n)\nfrom typing import Any as _Any\n\n__all__ = [\n 'has_any_attrs',\n 'has_any_callables',\n 'has_attrs',\n 'has_callables',\n 'is_list_like',\n 'is_subclass_of_any',\n]\n_LIST_LIKE = (\n list,\n set,\n frozenset,\n tuple,\n deque,\n Iterator,\n ValuesView,\n KeysView,\n UserList\n)\n\ndef has_callables(\n obj: _Any,\n *attrs: str\n) -> bool:\n \"\"\"Check if given ``obj`` has all the given ``attrs`` and are callable.\n\n Args:\n obj (:obj:`Any `): The object to check.\n *attrs (:obj:`str`): The names of the attributes to check.\n\n :rtype:\n :obj:`bool`\n\n * :obj:`True` if all the given ``*attrs`` exist on the given ``obj``\n and all are callable;\n * :obj:`False` otherwise.\n\n Example:\n >>> from flutils.objutils import has_callables\n >>> has_callables(dict(),'get','keys','items','values')\n True\n \"\"\"\n if has_attrs(obj, *attrs) is True:\n for attr in attrs:\n if callable(getattr(obj, attr)) is False:\n return False\n return True\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 88, "project": "flutils", "module": "flutils.packages", "class": "", "method": "bump_version", "focal_method_txt": "def bump_version(\n version: str,\n position: int = 2,\n pre_release: Optional[str] = None\n) -> str:\n \"\"\"Increase the version number from a version number string.\n\n *New in version 0.3*\n\n Args:\n version (str): The version number to be bumped.\n position (int, optional): The position (starting with zero) of the\n version number component to be increased. Defaults to: ``2``\n pre_release (str, Optional): A value of ``a`` or ``alpha`` will\n create or increase an alpha version number. A value of ``b`` or\n ``beta`` will create or increase a beta version number.\n\n Raises:\n ValueError: if the given ``version`` is an invalid version number.\n ValueError: if the given ``position`` does not exist.\n ValueError: if the given ``prerelease`` is not in:\n ``a, alpha, b, beta``\n ValueError: if trying to 'major' part, of a version number, to\n a pre-release version.\n\n :rtype:\n :obj:`str`\n\n * The increased version number.\n\n Examples:\n >>> from flutils.packages import bump_version\n >>> bump_version('1.2.2')\n '1.2.3'\n >>> bump_version('1.2.3', position=1)\n '1.3'\n >>> bump_version('1.3.4', position=0)\n '2.0'\n >>> bump_version('1.2.3', prerelease='a')\n '1.2.4a0'\n >>> bump_version('1.2.4a0', pre_release='a')\n '1.2.4a1'\n >>> bump_version('1.2.4a1', pre_release='b')\n '1.2.4b0'\n >>> bump_version('1.2.4a1')\n '1.2.4'\n >>> bump_version('1.2.4b0')\n '1.2.4'\n >>> bump_version('2.1.3', position=1, pre_release='a')\n '2.2a0'\n >>> bump_version('1.2b0', position=2)\n '1.2.1'\n\n \"\"\"\n ver_info = _build_version_info(version)\n position = _build_version_bump_position(position)\n bump_type = _build_version_bump_type(position, pre_release)\n # noinspection PyUnusedLocal\n hold: List[Union[int, str]] = []\n if bump_type == _BUMP_VERSION_MAJOR:\n hold = [ver_info.major.num + 1, 0]\n elif bump_type in _BUMP_VERSION_MINORS:\n if bump_type == _BUMP_VERSION_MINOR:\n if ver_info.minor.pre_txt:\n hold = [ver_info.major.num, ver_info.minor.num]\n else:\n hold = [ver_info.major.num, ver_info.minor.num + 1]\n else:\n if bump_type == _BUMP_VERSION_MINOR_ALPHA:\n if ver_info.minor.pre_txt == 'a':\n part = '%sa%s' % (\n ver_info.minor.num,\n ver_info.minor.pre_num + 1\n )\n else:\n part = '{}a0'.format(ver_info.minor.num + 1)\n else:\n if ver_info.minor.pre_txt == 'a':\n part = '{}b0'.format(ver_info.minor.num)\n elif ver_info.minor.pre_txt == 'b':\n part = '%sb%s' % (\n ver_info.minor.num,\n ver_info.minor.pre_num + 1\n )\n else:\n part = '{}b0'.format(ver_info.minor.num + 1)\n hold = [ver_info.major.num, part]\n else:\n if bump_type == _BUMP_VERSION_PATCH:\n if ver_info.patch.pre_txt:\n hold = [\n ver_info.major.num,\n ver_info.minor.num,\n ver_info.patch.num\n ]\n else:\n hold = [\n ver_info.major.num,\n ver_info.minor.num,\n ver_info.patch.num + 1\n ]\n else:\n if bump_type == _BUMP_VERSION_PATCH_ALPHA:\n if ver_info.patch.pre_txt == 'a':\n part = '%sa%s' % (\n ver_info.patch.num,\n ver_info.patch.pre_num + 1\n )\n else:\n part = '{}a0'.format(ver_info.patch.num + 1)\n else:\n if ver_info.patch.pre_txt == 'a':\n part = '{}b0'.format(ver_info.patch.num)\n\n elif ver_info.patch.pre_txt == 'b':\n part = '%sb%s' % (\n ver_info.patch.num,\n ver_info.patch.pre_num + 1\n )\n else:\n part = '{}b0'.format(ver_info.patch.num + 1)\n hold = [ver_info.major.num, ver_info.minor.num, part]\n out = '.'.join(map(str, hold))\n return out", "focal_method_lines": [168, 291], "in_stack": true, "globals": ["__all__", "_BUMP_VERSION_MAJOR", "_BUMP_VERSION_MINOR", "_BUMP_VERSION_PATCH", "_BUMP_VERSION_MINOR_ALPHA", "_BUMP_VERSION_MINOR_BETA", "_BUMP_VERSION_MINORS", "_BUMP_VERSION_PATCH_ALPHA", "_BUMP_VERSION_PATCH_BETA", "_BUMP_VERSION_PATCHES", "_BUMP_VERSION_POSITION_NAMES"], "type_context": "from typing import (\n Any,\n Dict,\n Generator,\n List,\n NamedTuple,\n Optional,\n Tuple,\n Union,\n cast,\n)\nfrom distutils.version import StrictVersion\n\n__all__ = ['bump_version']\n_BUMP_VERSION_MAJOR: int = 0\n_BUMP_VERSION_MINOR: int = 1\n_BUMP_VERSION_PATCH: int = 2\n_BUMP_VERSION_MINOR_ALPHA: int = 3\n_BUMP_VERSION_MINOR_BETA: int = 4\n_BUMP_VERSION_MINORS: Tuple[int, ...] = (\n _BUMP_VERSION_MINOR,\n _BUMP_VERSION_MINOR_ALPHA,\n _BUMP_VERSION_MINOR_BETA,\n)\n_BUMP_VERSION_PATCH_ALPHA: int = 5\n_BUMP_VERSION_PATCH_BETA: int = 6\n_BUMP_VERSION_PATCHES: Tuple[int, ...] = (\n _BUMP_VERSION_PATCH,\n _BUMP_VERSION_PATCH_ALPHA,\n _BUMP_VERSION_PATCH_BETA,\n)\n_BUMP_VERSION_POSITION_NAMES: Dict[int, str] = {\n _BUMP_VERSION_MAJOR: 'major',\n _BUMP_VERSION_MINOR: 'minor',\n _BUMP_VERSION_PATCH: 'patch',\n}\n\ndef bump_version(\n version: str,\n position: int = 2,\n pre_release: Optional[str] = None\n) -> str:\n \"\"\"Increase the version number from a version number string.\n\n *New in version 0.3*\n\n Args:\n version (str): The version number to be bumped.\n position (int, optional): The position (starting with zero) of the\n version number component to be increased. Defaults to: ``2``\n pre_release (str, Optional): A value of ``a`` or ``alpha`` will\n create or increase an alpha version number. A value of ``b`` or\n ``beta`` will create or increase a beta version number.\n\n Raises:\n ValueError: if the given ``version`` is an invalid version number.\n ValueError: if the given ``position`` does not exist.\n ValueError: if the given ``prerelease`` is not in:\n ``a, alpha, b, beta``\n ValueError: if trying to 'major' part, of a version number, to\n a pre-release version.\n\n :rtype:\n :obj:`str`\n\n * The increased version number.\n\n Examples:\n >>> from flutils.packages import bump_version\n >>> bump_version('1.2.2')\n '1.2.3'\n >>> bump_version('1.2.3', position=1)\n '1.3'\n >>> bump_version('1.3.4', position=0)\n '2.0'\n >>> bump_version('1.2.3', prerelease='a')\n '1.2.4a0'\n >>> bump_version('1.2.4a0', pre_release='a')\n '1.2.4a1'\n >>> bump_version('1.2.4a1', pre_release='b')\n '1.2.4b0'\n >>> bump_version('1.2.4a1')\n '1.2.4'\n >>> bump_version('1.2.4b0')\n '1.2.4'\n >>> bump_version('2.1.3', position=1, pre_release='a')\n '2.2a0'\n >>> bump_version('1.2b0', position=2)\n '1.2.1'\n\n \"\"\"\n ver_info = _build_version_info(version)\n position = _build_version_bump_position(position)\n bump_type = _build_version_bump_type(position, pre_release)\n # noinspection PyUnusedLocal\n hold: List[Union[int, str]] = []\n if bump_type == _BUMP_VERSION_MAJOR:\n hold = [ver_info.major.num + 1, 0]\n elif bump_type in _BUMP_VERSION_MINORS:\n if bump_type == _BUMP_VERSION_MINOR:\n if ver_info.minor.pre_txt:\n hold = [ver_info.major.num, ver_info.minor.num]\n else:\n hold = [ver_info.major.num, ver_info.minor.num + 1]\n else:\n if bump_type == _BUMP_VERSION_MINOR_ALPHA:\n if ver_info.minor.pre_txt == 'a':\n part = '%sa%s' % (\n ver_info.minor.num,\n ver_info.minor.pre_num + 1\n )\n else:\n part = '{}a0'.format(ver_info.minor.num + 1)\n else:\n if ver_info.minor.pre_txt == 'a':\n part = '{}b0'.format(ver_info.minor.num)\n elif ver_info.minor.pre_txt == 'b':\n part = '%sb%s' % (\n ver_info.minor.num,\n ver_info.minor.pre_num + 1\n )\n else:\n part = '{}b0'.format(ver_info.minor.num + 1)\n hold = [ver_info.major.num, part]\n else:\n if bump_type == _BUMP_VERSION_PATCH:\n if ver_info.patch.pre_txt:\n hold = [\n ver_info.major.num,\n ver_info.minor.num,\n ver_info.patch.num\n ]\n else:\n hold = [\n ver_info.major.num,\n ver_info.minor.num,\n ver_info.patch.num + 1\n ]\n else:\n if bump_type == _BUMP_VERSION_PATCH_ALPHA:\n if ver_info.patch.pre_txt == 'a':\n part = '%sa%s' % (\n ver_info.patch.num,\n ver_info.patch.pre_num + 1\n )\n else:\n part = '{}a0'.format(ver_info.patch.num + 1)\n else:\n if ver_info.patch.pre_txt == 'a':\n part = '{}b0'.format(ver_info.patch.num)\n\n elif ver_info.patch.pre_txt == 'b':\n part = '%sb%s' % (\n ver_info.patch.num,\n ver_info.patch.pre_num + 1\n )\n else:\n part = '{}b0'.format(ver_info.patch.num + 1)\n hold = [ver_info.major.num, ver_info.minor.num, part]\n out = '.'.join(map(str, hold))\n return out", "has_branch": true, "total_branches": 2} {"prompt_id": 89, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "chmod", "focal_method_txt": "def chmod(\n path: _PATH,\n mode_file: Optional[int] = None,\n mode_dir: Optional[int] = None,\n include_parent: bool = False\n) -> None:\n \"\"\"Change the mode of a path.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does NOT exist, nothing will be done.\n\n This function will **NOT** change the mode of:\n\n - symlinks (symlink targets that are files or directories will be changed)\n - sockets\n - fifo\n - block devices\n - char devices\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the file or directory to have it's mode changed. This\n value can be a :term:`glob pattern`.\n mode_file (:obj:`int`, optional): The mode applied to the given\n ``path`` that is a file or a symlink target that is a file.\n Defaults to ``0o600``.\n mode_dir (:obj:`int`, optional): The mode applied to the given\n ``path`` that is a directory or a symlink target that is a\n directory. Defaults to ``0o700``.\n include_parent (:obj:`bool`, optional): A value of :obj:`True`` will\n chmod the parent directory of the given ``path`` that contains a\n a :term:`glob pattern`. Defaults to :obj:`False`.\n\n :rtype: :obj:`None`\n\n Examples:\n >>> from flutils.pathutils import chmod\n >>> chmod('~/tmp/flutils.tests.osutils.txt', 0o660)\n\n Supports a :term:`glob pattern`. So to recursively change the mode\n of a directory just do:\n\n >>> chmod('~/tmp/**', mode_file=0o644, mode_dir=0o770)\n\n To change the mode of a directory's immediate contents:\n\n >>> chmod('~/tmp/*')\n\n \"\"\"\n\n path = normalize_path(path)\n\n if mode_file is None:\n mode_file = 0o600\n\n if mode_dir is None:\n mode_dir = 0o700\n\n if '*' in path.as_posix():\n try:\n for sub_path in Path().glob(path.as_posix()):\n if sub_path.is_dir() is True:\n sub_path.chmod(mode_dir)\n elif sub_path.is_file():\n sub_path.chmod(mode_file)\n\n # Path().glob() returns an iterator that will\n # raise NotImplementedError if there\n # are no results from the glob pattern.\n except NotImplementedError:\n pass\n\n else:\n if include_parent is True:\n parent = path.parent\n if parent.is_dir():\n parent.chmod(mode_dir)\n else:\n if path.exists() is True:\n if path.is_dir():\n path.chmod(mode_dir)\n elif path.is_file():\n path.chmod(mode_file)", "focal_method_lines": [50, 134], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef chmod(\n path: _PATH,\n mode_file: Optional[int] = None,\n mode_dir: Optional[int] = None,\n include_parent: bool = False\n) -> None:\n \"\"\"Change the mode of a path.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does NOT exist, nothing will be done.\n\n This function will **NOT** change the mode of:\n\n - symlinks (symlink targets that are files or directories will be changed)\n - sockets\n - fifo\n - block devices\n - char devices\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the file or directory to have it's mode changed. This\n value can be a :term:`glob pattern`.\n mode_file (:obj:`int`, optional): The mode applied to the given\n ``path`` that is a file or a symlink target that is a file.\n Defaults to ``0o600``.\n mode_dir (:obj:`int`, optional): The mode applied to the given\n ``path`` that is a directory or a symlink target that is a\n directory. Defaults to ``0o700``.\n include_parent (:obj:`bool`, optional): A value of :obj:`True`` will\n chmod the parent directory of the given ``path`` that contains a\n a :term:`glob pattern`. Defaults to :obj:`False`.\n\n :rtype: :obj:`None`\n\n Examples:\n >>> from flutils.pathutils import chmod\n >>> chmod('~/tmp/flutils.tests.osutils.txt', 0o660)\n\n Supports a :term:`glob pattern`. So to recursively change the mode\n of a directory just do:\n\n >>> chmod('~/tmp/**', mode_file=0o644, mode_dir=0o770)\n\n To change the mode of a directory's immediate contents:\n\n >>> chmod('~/tmp/*')\n\n \"\"\"\n\n path = normalize_path(path)\n\n if mode_file is None:\n mode_file = 0o600\n\n if mode_dir is None:\n mode_dir = 0o700\n\n if '*' in path.as_posix():\n try:\n for sub_path in Path().glob(path.as_posix()):\n if sub_path.is_dir() is True:\n sub_path.chmod(mode_dir)\n elif sub_path.is_file():\n sub_path.chmod(mode_file)\n\n # Path().glob() returns an iterator that will\n # raise NotImplementedError if there\n # are no results from the glob pattern.\n except NotImplementedError:\n pass\n\n else:\n if include_parent is True:\n parent = path.parent\n if parent.is_dir():\n parent.chmod(mode_dir)\n else:\n if path.exists() is True:\n if path.is_dir():\n path.chmod(mode_dir)\n elif path.is_file():\n path.chmod(mode_file)", "has_branch": true, "total_branches": 2} {"prompt_id": 90, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "chown", "focal_method_txt": "def chown(\n path: _PATH,\n user: Optional[str] = None,\n group: Optional[str] = None,\n include_parent: bool = False\n) -> None:\n \"\"\"Change ownership of a path.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does NOT exist, nothing will be done.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the file or directory that will have it's ownership\n changed. This value can be a :term:`glob pattern`.\n user (:obj:`str` or :obj:`int`, optional): The \"login name\" used to set\n the owner of ``path``. A value of ``'-1'`` will leave the\n owner unchanged. Defaults to the \"login name\" of the current user.\n group (:obj:`str` or :obj:`int`, optional): The group name used to set\n the group of ``path``. A value of ``'-1'`` will leave the\n group unchanged. Defaults to the current user's group.\n include_parent (:obj:`bool`, optional): A value of :obj:`True` will\n chown the parent directory of the given ``path`` that contains\n a :term:`glob pattern`. Defaults to :obj:`False`.\n\n Raises:\n OSError: If the given :obj:`user` does not exist as a \"login\n name\" for this operating system.\n OSError: If the given :obj:`group` does not exist as a \"group\n name\" for this operating system.\n\n :rtype: :obj:`None`\n\n Examples:\n >>> from flutils.pathutils import chown\n >>> chown('~/tmp/flutils.tests.osutils.txt')\n\n Supports a :term:`glob pattern`. So to recursively change the\n ownership of a directory just do:\n\n >>> chown('~/tmp/**')\n\n\n To change ownership of all the directory's immediate contents:\n\n >>> chown('~/tmp/*', user='foo', group='bar')\n\n \"\"\"\n path = normalize_path(path)\n if isinstance(user, str) and user == '-1':\n uid = -1\n else:\n uid = get_os_user(user).pw_uid\n\n if isinstance(user, str) and group == '-1':\n gid = -1\n else:\n gid = get_os_group(group).gr_gid\n\n if '*' in path.as_posix():\n try:\n for sub_path in Path().glob(path.as_posix()):\n if sub_path.is_dir() or sub_path.is_file():\n os.chown(sub_path.as_posix(), uid, gid)\n except NotImplementedError:\n # Path().glob() returns an iterator that will\n # raise NotImplementedError if there\n # are no results from the glob pattern.\n pass\n else:\n if include_parent is True:\n path = path.parent\n if path.is_dir() is True:\n os.chown(path.as_posix(), uid, gid)\n else:\n if path.exists() is True:\n os.chown(path.as_posix(), uid, gid)", "focal_method_lines": [137, 215], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef chown(\n path: _PATH,\n user: Optional[str] = None,\n group: Optional[str] = None,\n include_parent: bool = False\n) -> None:\n \"\"\"Change ownership of a path.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does NOT exist, nothing will be done.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the file or directory that will have it's ownership\n changed. This value can be a :term:`glob pattern`.\n user (:obj:`str` or :obj:`int`, optional): The \"login name\" used to set\n the owner of ``path``. A value of ``'-1'`` will leave the\n owner unchanged. Defaults to the \"login name\" of the current user.\n group (:obj:`str` or :obj:`int`, optional): The group name used to set\n the group of ``path``. A value of ``'-1'`` will leave the\n group unchanged. Defaults to the current user's group.\n include_parent (:obj:`bool`, optional): A value of :obj:`True` will\n chown the parent directory of the given ``path`` that contains\n a :term:`glob pattern`. Defaults to :obj:`False`.\n\n Raises:\n OSError: If the given :obj:`user` does not exist as a \"login\n name\" for this operating system.\n OSError: If the given :obj:`group` does not exist as a \"group\n name\" for this operating system.\n\n :rtype: :obj:`None`\n\n Examples:\n >>> from flutils.pathutils import chown\n >>> chown('~/tmp/flutils.tests.osutils.txt')\n\n Supports a :term:`glob pattern`. So to recursively change the\n ownership of a directory just do:\n\n >>> chown('~/tmp/**')\n\n\n To change ownership of all the directory's immediate contents:\n\n >>> chown('~/tmp/*', user='foo', group='bar')\n\n \"\"\"\n path = normalize_path(path)\n if isinstance(user, str) and user == '-1':\n uid = -1\n else:\n uid = get_os_user(user).pw_uid\n\n if isinstance(user, str) and group == '-1':\n gid = -1\n else:\n gid = get_os_group(group).gr_gid\n\n if '*' in path.as_posix():\n try:\n for sub_path in Path().glob(path.as_posix()):\n if sub_path.is_dir() or sub_path.is_file():\n os.chown(sub_path.as_posix(), uid, gid)\n except NotImplementedError:\n # Path().glob() returns an iterator that will\n # raise NotImplementedError if there\n # are no results from the glob pattern.\n pass\n else:\n if include_parent is True:\n path = path.parent\n if path.is_dir() is True:\n os.chown(path.as_posix(), uid, gid)\n else:\n if path.exists() is True:\n os.chown(path.as_posix(), uid, gid)", "has_branch": true, "total_branches": 2} {"prompt_id": 91, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "directory_present", "focal_method_txt": "def directory_present(\n path: _PATH,\n mode: Optional[int] = None,\n user: Optional[str] = None,\n group: Optional[str] = None,\n) -> Path:\n \"\"\"Ensure the state of the given :obj:`path` is present and a directory.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does **NOT** exist, it will be created as a\n directory.\n\n If the parent paths of the given ``path`` do not exist, they will also be\n created with the ``mode``, ``user`` and ``group``.\n\n If the given ``path`` does exist as a directory, the ``mode``, ``user``,\n and :``group`` will be applied.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the directory.\n mode (:obj:`int`, optional): The mode applied to the ``path``.\n Defaults to ``0o700``.\n user (:obj:`str` or :obj:`int`, optional): The \"login name\" used to\n set the owner of the given ``path``. A value of ``'-1'`` will\n leave the owner unchanged. Defaults to the \"login name\" of the\n current user.\n group (:obj:`str` or :obj:`int`, optional): The group name used to set\n the group of the given ``path``. A value of ``'-1'`` will leave\n the group unchanged. Defaults to the current user's group.\n\n Raises:\n ValueError: if the given ``path`` contains a glob pattern.\n ValueError: if the given ``path`` is not an absolute path.\n FileExistsError: if the given ``path`` exists and is not a directory.\n FileExistsError: if a parent of the given ``path`` exists and is\n not a directory.\n\n :rtype: :obj:`Path `\n\n * :obj:`PosixPath ` or\n :obj:`WindowsPath ` depending on the system.\n\n .. Note:: :obj:`Path ` objects are immutable. Therefore,\n any given ``path`` of type :obj:`Path ` will not be\n the same object returned.\n\n Example:\n >>> from flutils.pathutils import directory_present\n >>> directory_present('~/tmp/test_path')\n PosixPath('/Users/len/tmp/test_path')\n\n \"\"\"\n path = normalize_path(path)\n\n if '*' in path.as_posix():\n raise ValueError(\n 'The path: %r must NOT contain any glob patterns.'\n % path.as_posix()\n )\n if path.is_absolute() is False:\n raise ValueError(\n 'The path: %r must be an absolute path. A path is considered '\n 'absolute if it has both a root and (if the flavour allows) a '\n 'drive.'\n % path.as_posix()\n )\n\n # Create a queue of paths to be created as directories.\n paths: Deque = deque()\n\n path_exists_as = exists_as(path)\n if path_exists_as == '':\n paths.append(path)\n elif path_exists_as != 'directory':\n raise FileExistsError(\n 'The path: %r can NOT be created as a directory because it '\n 'already exists as a %s.' % (path.as_posix(), path_exists_as)\n )\n\n parent = path.parent\n child = path\n\n # Traverse the path backwards and add any directories that\n # do no exist to the path queue.\n while child.as_posix() != parent.as_posix():\n parent_exists_as = exists_as(parent)\n if parent_exists_as == '':\n paths.appendleft(parent)\n child = parent\n parent = parent.parent\n elif parent_exists_as == 'directory':\n break\n else:\n raise FileExistsError(\n 'Unable to create the directory: %r because the'\n 'parent path: %r exists as a %s.'\n % (path.as_posix, parent.as_posix(), parent_exists_as)\n )\n\n if mode is None:\n mode = 0o700\n\n if paths:\n for build_path in paths:\n build_path.mkdir(mode=mode)\n chown(build_path, user=user, group=group)\n else:\n # The given path already existed only need to do a chown.\n chmod(path, mode_dir=mode)\n chown(path, user=user, group=group)\n\n return path", "focal_method_lines": [218, 332], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef directory_present(\n path: _PATH,\n mode: Optional[int] = None,\n user: Optional[str] = None,\n group: Optional[str] = None,\n) -> Path:\n \"\"\"Ensure the state of the given :obj:`path` is present and a directory.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n If the given ``path`` does **NOT** exist, it will be created as a\n directory.\n\n If the parent paths of the given ``path`` do not exist, they will also be\n created with the ``mode``, ``user`` and ``group``.\n\n If the given ``path`` does exist as a directory, the ``mode``, ``user``,\n and :``group`` will be applied.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path of the directory.\n mode (:obj:`int`, optional): The mode applied to the ``path``.\n Defaults to ``0o700``.\n user (:obj:`str` or :obj:`int`, optional): The \"login name\" used to\n set the owner of the given ``path``. A value of ``'-1'`` will\n leave the owner unchanged. Defaults to the \"login name\" of the\n current user.\n group (:obj:`str` or :obj:`int`, optional): The group name used to set\n the group of the given ``path``. A value of ``'-1'`` will leave\n the group unchanged. Defaults to the current user's group.\n\n Raises:\n ValueError: if the given ``path`` contains a glob pattern.\n ValueError: if the given ``path`` is not an absolute path.\n FileExistsError: if the given ``path`` exists and is not a directory.\n FileExistsError: if a parent of the given ``path`` exists and is\n not a directory.\n\n :rtype: :obj:`Path `\n\n * :obj:`PosixPath ` or\n :obj:`WindowsPath ` depending on the system.\n\n .. Note:: :obj:`Path ` objects are immutable. Therefore,\n any given ``path`` of type :obj:`Path ` will not be\n the same object returned.\n\n Example:\n >>> from flutils.pathutils import directory_present\n >>> directory_present('~/tmp/test_path')\n PosixPath('/Users/len/tmp/test_path')\n\n \"\"\"\n path = normalize_path(path)\n\n if '*' in path.as_posix():\n raise ValueError(\n 'The path: %r must NOT contain any glob patterns.'\n % path.as_posix()\n )\n if path.is_absolute() is False:\n raise ValueError(\n 'The path: %r must be an absolute path. A path is considered '\n 'absolute if it has both a root and (if the flavour allows) a '\n 'drive.'\n % path.as_posix()\n )\n\n # Create a queue of paths to be created as directories.\n paths: Deque = deque()\n\n path_exists_as = exists_as(path)\n if path_exists_as == '':\n paths.append(path)\n elif path_exists_as != 'directory':\n raise FileExistsError(\n 'The path: %r can NOT be created as a directory because it '\n 'already exists as a %s.' % (path.as_posix(), path_exists_as)\n )\n\n parent = path.parent\n child = path\n\n # Traverse the path backwards and add any directories that\n # do no exist to the path queue.\n while child.as_posix() != parent.as_posix():\n parent_exists_as = exists_as(parent)\n if parent_exists_as == '':\n paths.appendleft(parent)\n child = parent\n parent = parent.parent\n elif parent_exists_as == 'directory':\n break\n else:\n raise FileExistsError(\n 'Unable to create the directory: %r because the'\n 'parent path: %r exists as a %s.'\n % (path.as_posix, parent.as_posix(), parent_exists_as)\n )\n\n if mode is None:\n mode = 0o700\n\n if paths:\n for build_path in paths:\n build_path.mkdir(mode=mode)\n chown(build_path, user=user, group=group)\n else:\n # The given path already existed only need to do a chown.\n chmod(path, mode_dir=mode)\n chown(path, user=user, group=group)\n\n return path", "has_branch": true, "total_branches": 2} {"prompt_id": 92, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "exists_as", "focal_method_txt": "def exists_as(path: _PATH) -> str:\n \"\"\"Return a string describing the file type if it exists.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to check for existence.\n\n :rtype:\n :obj:`str`\n\n * ``''`` (empty string): if the given ``path`` does NOT exist; or,\n is a broken symbolic link; or, other errors (such as permission\n errors) are propagated.\n * ``'directory'``: if the given ``path`` points to a directory or\n is a symbolic link pointing to a directory.\n * ``'file'``: if the given ``path`` points to a regular file or is a\n symbolic link pointing to a regular file.\n * ``'block device'``: if the given ``path`` points to a block device or\n is a symbolic link pointing to a block device.\n * ``'char device'``: if the given ``path`` points to a character device\n or is a symbolic link pointing to a character device.\n * ``'FIFO'``: if the given ``path`` points to a FIFO or is a symbolic\n link pointing to a FIFO.\n * ``'socket'``: if the given ``path`` points to a Unix socket or is a\n symbolic link pointing to a Unix socket.\n\n Example:\n >>> from flutils.pathutils import exists_as\n >>> exists_as('~/tmp')\n 'directory'\n \"\"\"\n path = normalize_path(path)\n\n if path.is_dir():\n return 'directory'\n if path.is_file():\n return 'file'\n if path.is_block_device():\n return 'block device'\n if path.is_char_device():\n return 'char device'\n if path.is_fifo():\n return 'FIFO'\n if path.is_socket():\n return 'socket'\n return ''", "focal_method_lines": [335, 383], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef exists_as(path: _PATH) -> str:\n \"\"\"Return a string describing the file type if it exists.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to check for existence.\n\n :rtype:\n :obj:`str`\n\n * ``''`` (empty string): if the given ``path`` does NOT exist; or,\n is a broken symbolic link; or, other errors (such as permission\n errors) are propagated.\n * ``'directory'``: if the given ``path`` points to a directory or\n is a symbolic link pointing to a directory.\n * ``'file'``: if the given ``path`` points to a regular file or is a\n symbolic link pointing to a regular file.\n * ``'block device'``: if the given ``path`` points to a block device or\n is a symbolic link pointing to a block device.\n * ``'char device'``: if the given ``path`` points to a character device\n or is a symbolic link pointing to a character device.\n * ``'FIFO'``: if the given ``path`` points to a FIFO or is a symbolic\n link pointing to a FIFO.\n * ``'socket'``: if the given ``path`` points to a Unix socket or is a\n symbolic link pointing to a Unix socket.\n\n Example:\n >>> from flutils.pathutils import exists_as\n >>> exists_as('~/tmp')\n 'directory'\n \"\"\"\n path = normalize_path(path)\n\n if path.is_dir():\n return 'directory'\n if path.is_file():\n return 'file'\n if path.is_block_device():\n return 'block device'\n if path.is_char_device():\n return 'char device'\n if path.is_fifo():\n return 'FIFO'\n if path.is_socket():\n return 'socket'\n return ''", "has_branch": true, "total_branches": 2} {"prompt_id": 93, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "find_paths", "focal_method_txt": "def find_paths(\n pattern: _PATH\n) -> Generator[Path, None, None]:\n \"\"\"Find all paths that match the given :term:`glob pattern`.\n\n This function pre-processes the given ``pattern`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n pattern (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to find; which may contain a :term:`glob pattern`.\n\n :rtype:\n :obj:`Generator `\n\n Yields:\n :obj:`pathlib.PosixPath` or :obj:`pathlib.WindowsPath`\n\n Example:\n >>> from flutils.pathutils import find_paths\n >>> list(find_paths('~/tmp/*'))\n [PosixPath('/home/test_user/tmp/file_one'),\n PosixPath('/home/test_user/tmp/dir_one')]\n\n \"\"\"\n pattern = normalize_path(pattern)\n search = pattern.as_posix()[len(pattern.anchor):]\n yield from Path(pattern.anchor).glob(search)", "focal_method_lines": [386, 413], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef find_paths(\n pattern: _PATH\n) -> Generator[Path, None, None]:\n \"\"\"Find all paths that match the given :term:`glob pattern`.\n\n This function pre-processes the given ``pattern`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n pattern (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to find; which may contain a :term:`glob pattern`.\n\n :rtype:\n :obj:`Generator `\n\n Yields:\n :obj:`pathlib.PosixPath` or :obj:`pathlib.WindowsPath`\n\n Example:\n >>> from flutils.pathutils import find_paths\n >>> list(find_paths('~/tmp/*'))\n [PosixPath('/home/test_user/tmp/file_one'),\n PosixPath('/home/test_user/tmp/dir_one')]\n\n \"\"\"\n pattern = normalize_path(pattern)\n search = pattern.as_posix()[len(pattern.anchor):]\n yield from Path(pattern.anchor).glob(search)", "has_branch": false, "total_branches": 0} {"prompt_id": 94, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "get_os_group", "focal_method_txt": "def get_os_group(name: _STR_OR_INT_OR_NONE = None) -> grp.struct_group:\n \"\"\"Get an operating system group object.\n\n Args:\n name (:obj:`str` or :obj:`int`, optional): The \"group name\" or ``gid``.\n Defaults to the current users's group.\n\n Raises:\n OSError: If the given ``name`` does not exist as a \"group\n name\" for this operating system.\n OSError: If the given ``name`` is a ``gid`` and it does not\n exist.\n\n :rtype:\n :obj:`struct_group `\n\n * A tuple like object.\n\n Example:\n >>> from flutils.pathutils import get_os_group\n >>> get_os_group('bar')\n grp.struct_group(gr_name='bar', gr_passwd='*', gr_gid=2001,\n gr_mem=['foo'])\n \"\"\"\n if name is None:\n name = get_os_user().pw_gid\n name = cast(int, name)\n if isinstance(name, int):\n try:\n return grp.getgrgid(name)\n except KeyError:\n raise OSError(\n 'The given gid: %r, is not a valid gid for this operating '\n 'system.' % name\n )\n try:\n return grp.getgrnam(name)\n except KeyError:\n raise OSError(\n 'The given name: %r, is not a valid \"group name\" '\n 'for this operating system.' % name\n )", "focal_method_lines": [416, 454], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef get_os_group(name: _STR_OR_INT_OR_NONE = None) -> grp.struct_group:\n \"\"\"Get an operating system group object.\n\n Args:\n name (:obj:`str` or :obj:`int`, optional): The \"group name\" or ``gid``.\n Defaults to the current users's group.\n\n Raises:\n OSError: If the given ``name`` does not exist as a \"group\n name\" for this operating system.\n OSError: If the given ``name`` is a ``gid`` and it does not\n exist.\n\n :rtype:\n :obj:`struct_group `\n\n * A tuple like object.\n\n Example:\n >>> from flutils.pathutils import get_os_group\n >>> get_os_group('bar')\n grp.struct_group(gr_name='bar', gr_passwd='*', gr_gid=2001,\n gr_mem=['foo'])\n \"\"\"\n if name is None:\n name = get_os_user().pw_gid\n name = cast(int, name)\n if isinstance(name, int):\n try:\n return grp.getgrgid(name)\n except KeyError:\n raise OSError(\n 'The given gid: %r, is not a valid gid for this operating '\n 'system.' % name\n )\n try:\n return grp.getgrnam(name)\n except KeyError:\n raise OSError(\n 'The given name: %r, is not a valid \"group name\" '\n 'for this operating system.' % name\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 95, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "get_os_user", "focal_method_txt": "def get_os_user(name: _STR_OR_INT_OR_NONE = None) -> pwd.struct_passwd:\n \"\"\"Return an user object representing an operating system user.\n\n Args:\n name (:obj:`str` or :obj:`int`, optional): The \"login name\" or\n ``uid``. Defaults to the current user's \"login name\".\n Raises:\n OSError: If the given ``name`` does not exist as a \"login\n name\" for this operating system.\n OSError: If the given ``name`` is an ``uid`` and it does not\n exist.\n\n :rtype:\n :obj:`struct_passwd `\n\n * A tuple like object.\n\n Example:\n >>> from flutils.pathutils import get_os_user\n >>> get_os_user('foo')\n pwd.struct_passwd(pw_name='foo', pw_passwd='********', pw_uid=1001,\n pw_gid=2001, pw_gecos='Foo Bar', pw_dir='/home/foo',\n pw_shell='/usr/local/bin/bash')\n \"\"\"\n if isinstance(name, int):\n try:\n return pwd.getpwuid(name)\n except KeyError:\n raise OSError(\n 'The given uid: %r, is not a valid uid for this operating '\n 'system.' % name\n )\n if name is None:\n name = getpass.getuser()\n try:\n return pwd.getpwnam(name)\n except KeyError:\n raise OSError(\n 'The given name: %r, is not a valid \"login name\" '\n 'for this operating system.' % name\n )", "focal_method_lines": [460, 497], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef get_os_user(name: _STR_OR_INT_OR_NONE = None) -> pwd.struct_passwd:\n \"\"\"Return an user object representing an operating system user.\n\n Args:\n name (:obj:`str` or :obj:`int`, optional): The \"login name\" or\n ``uid``. Defaults to the current user's \"login name\".\n Raises:\n OSError: If the given ``name`` does not exist as a \"login\n name\" for this operating system.\n OSError: If the given ``name`` is an ``uid`` and it does not\n exist.\n\n :rtype:\n :obj:`struct_passwd `\n\n * A tuple like object.\n\n Example:\n >>> from flutils.pathutils import get_os_user\n >>> get_os_user('foo')\n pwd.struct_passwd(pw_name='foo', pw_passwd='********', pw_uid=1001,\n pw_gid=2001, pw_gecos='Foo Bar', pw_dir='/home/foo',\n pw_shell='/usr/local/bin/bash')\n \"\"\"\n if isinstance(name, int):\n try:\n return pwd.getpwuid(name)\n except KeyError:\n raise OSError(\n 'The given uid: %r, is not a valid uid for this operating '\n 'system.' % name\n )\n if name is None:\n name = getpass.getuser()\n try:\n return pwd.getpwnam(name)\n except KeyError:\n raise OSError(\n 'The given name: %r, is not a valid \"login name\" '\n 'for this operating system.' % name\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 96, "project": "flutils", "module": "flutils.pathutils", "class": "", "method": "path_absent", "focal_method_txt": "def path_absent(\n path: _PATH,\n) -> None:\n \"\"\"Ensure the given ``path`` does **NOT** exist.\n\n *New in version 0.4.*\n\n If the given ``path`` does exist, it will be deleted.\n\n If the given ``path`` is a directory, this function will\n recursively delete all of the directory's contents.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to remove.\n\n :rtype: :obj:`None`\n\n Example:\n >>> from flutils.pathutils import path_absent\n >>> path_absent('~/tmp/test_path')\n\n \"\"\"\n path = normalize_path(path)\n path = path.as_posix()\n path = cast(str, path)\n if os.path.exists(path):\n if os.path.islink(path):\n os.unlink(path)\n elif os.path.isdir(path):\n for root, dirs, files in os.walk(path, topdown=False):\n for name in files:\n p = os.path.join(root, name)\n if os.path.isfile(p) or os.path.islink(p):\n os.unlink(p)\n for name in dirs:\n p = os.path.join(root, name)\n if os.path.islink(p):\n os.unlink(p)\n else:\n os.rmdir(p)\n if os.path.isdir(path):\n os.rmdir(path)\n else:\n os.unlink(path)", "focal_method_lines": [573, 620], "in_stack": true, "globals": ["__all__", "_PATH", "_STR_OR_INT_OR_NONE"], "type_context": "import functools\nimport getpass\nimport grp\nimport os\nimport pwd\nimport sys\nfrom collections import deque\nfrom os import PathLike\nfrom pathlib import (\n Path,\n PosixPath,\n WindowsPath,\n)\nfrom typing import (\n Deque,\n Generator,\n Optional,\n Union,\n cast,\n)\n\n__all__ = [\n 'chmod',\n 'chown',\n 'directory_present',\n 'exists_as',\n 'find_paths',\n 'get_os_group',\n 'get_os_user',\n 'normalize_path',\n 'path_absent',\n]\n_PATH = Union[\n PathLike,\n PosixPath,\n WindowsPath,\n bytes,\n str,\n]\n_STR_OR_INT_OR_NONE = Union[\n str,\n int,\n None\n]\n\ndef path_absent(\n path: _PATH,\n) -> None:\n \"\"\"Ensure the given ``path`` does **NOT** exist.\n\n *New in version 0.4.*\n\n If the given ``path`` does exist, it will be deleted.\n\n If the given ``path`` is a directory, this function will\n recursively delete all of the directory's contents.\n\n This function processes the given ``path`` with\n :obj:`~flutils.normalize_path`.\n\n Args:\n path (:obj:`str`, :obj:`bytes` or :obj:`Path `):\n The path to remove.\n\n :rtype: :obj:`None`\n\n Example:\n >>> from flutils.pathutils import path_absent\n >>> path_absent('~/tmp/test_path')\n\n \"\"\"\n path = normalize_path(path)\n path = path.as_posix()\n path = cast(str, path)\n if os.path.exists(path):\n if os.path.islink(path):\n os.unlink(path)\n elif os.path.isdir(path):\n for root, dirs, files in os.walk(path, topdown=False):\n for name in files:\n p = os.path.join(root, name)\n if os.path.isfile(p) or os.path.islink(p):\n os.unlink(p)\n for name in dirs:\n p = os.path.join(root, name)\n if os.path.islink(p):\n os.unlink(p)\n else:\n os.rmdir(p)\n if os.path.isdir(path):\n os.rmdir(path)\n else:\n os.unlink(path)", "has_branch": true, "total_branches": 2} {"prompt_id": 97, "project": "flutils", "module": "flutils.setuputils.cfg", "class": "", "method": "each_sub_command_config", "focal_method_txt": "def each_sub_command_config(\n setup_dir: Optional[Union[os.PathLike, str]] = None\n) -> Generator[SetupCfgCommandConfig, None, None]:\n format_kwargs: Dict[str, str] = {\n 'setup_dir': _prep_setup_dir(setup_dir),\n 'home': os.path.expanduser('~')\n }\n setup_cfg_path = os.path.join(format_kwargs['setup_dir'], 'setup.cfg')\n parser = ConfigParser()\n parser.read(setup_cfg_path)\n format_kwargs['name'] = _get_name(parser, setup_cfg_path)\n path = os.path.join(format_kwargs['setup_dir'], 'setup_commands.cfg')\n if os.path.isfile(path):\n parser = ConfigParser()\n parser.read(path)\n yield from _each_setup_cfg_command(parser, format_kwargs)", "focal_method_lines": [156, 171], "in_stack": true, "globals": [], "type_context": "import os\nfrom configparser import (\n ConfigParser,\n NoOptionError,\n NoSectionError,\n)\nfrom traceback import (\n FrameSummary,\n extract_stack,\n)\nfrom typing import (\n Dict,\n Generator,\n List,\n NamedTuple,\n Optional,\n Tuple,\n Union,\n cast,\n)\nfrom flutils.strutils import underscore_to_camel\n\n\n\ndef each_sub_command_config(\n setup_dir: Optional[Union[os.PathLike, str]] = None\n) -> Generator[SetupCfgCommandConfig, None, None]:\n format_kwargs: Dict[str, str] = {\n 'setup_dir': _prep_setup_dir(setup_dir),\n 'home': os.path.expanduser('~')\n }\n setup_cfg_path = os.path.join(format_kwargs['setup_dir'], 'setup.cfg')\n parser = ConfigParser()\n parser.read(setup_cfg_path)\n format_kwargs['name'] = _get_name(parser, setup_cfg_path)\n path = os.path.join(format_kwargs['setup_dir'], 'setup_commands.cfg')\n if os.path.isfile(path):\n parser = ConfigParser()\n parser.read(path)\n yield from _each_setup_cfg_command(parser, format_kwargs)", "has_branch": true, "total_branches": 2} {"prompt_id": 98, "project": "flutils", "module": "flutils.txtutils", "class": "", "method": "len_without_ansi", "focal_method_txt": "def len_without_ansi(seq: Sequence) -> int:\n \"\"\"Return the character length of the given\n :obj:`Sequence ` without counting any ANSI codes.\n\n *New in version 0.6*\n\n Args:\n seq (:obj:`Sequence `): A string or a list/tuple\n of strings.\n\n :rtype:\n :obj:`int`\n\n Example:\n >>> from flutils.txtutils import len_without_ansi\n >>> text = '\\\\x1b[38;5;209mfoobar\\\\x1b[0m'\n >>> len_without_ansi(text)\n 6\n \"\"\"\n if hasattr(seq, 'capitalize'):\n _text: str = cast(str, seq)\n seq = [c for c in _ANSI_RE.split(_text) if c]\n seq = [c for c in chain(*map(_ANSI_RE.split, seq)) if c]\n seq = cast(Sequence[str], seq)\n out = 0\n for text in seq:\n if hasattr(text, 'capitalize'):\n if text.startswith('\\x1b[') and text.endswith('m'):\n continue\n else:\n out += len(text)\n return out", "focal_method_lines": [24, 55], "in_stack": true, "globals": ["__all__", "_ANSI_RE"], "type_context": "import re\nfrom itertools import chain\nfrom sys import hexversion\nfrom textwrap import TextWrapper\nfrom typing import (\n List,\n Optional,\n Sequence,\n cast,\n)\n\n__all__ = ['len_without_ansi', 'AnsiTextWrapper']\n_ANSI_RE = re.compile('(\\x1b\\\\[[0-9;:]+[ABCDEFGHJKSTfhilmns])')\n\ndef len_without_ansi(seq: Sequence) -> int:\n \"\"\"Return the character length of the given\n :obj:`Sequence ` without counting any ANSI codes.\n\n *New in version 0.6*\n\n Args:\n seq (:obj:`Sequence `): A string or a list/tuple\n of strings.\n\n :rtype:\n :obj:`int`\n\n Example:\n >>> from flutils.txtutils import len_without_ansi\n >>> text = '\\\\x1b[38;5;209mfoobar\\\\x1b[0m'\n >>> len_without_ansi(text)\n 6\n \"\"\"\n if hasattr(seq, 'capitalize'):\n _text: str = cast(str, seq)\n seq = [c for c in _ANSI_RE.split(_text) if c]\n seq = [c for c in chain(*map(_ANSI_RE.split, seq)) if c]\n seq = cast(Sequence[str], seq)\n out = 0\n for text in seq:\n if hasattr(text, 'capitalize'):\n if text.startswith('\\x1b[') and text.endswith('m'):\n continue\n else:\n out += len(text)\n return out", "has_branch": true, "total_branches": 2} {"prompt_id": 99, "project": "httpie", "module": "httpie.cli.argparser", "class": "HTTPieArgumentParser", "method": "parse_args", "focal_method_txt": " def parse_args(\n self,\n env: Environment,\n args=None,\n namespace=None\n ) -> argparse.Namespace:\n self.env = env\n self.args, no_options = super().parse_known_args(args, namespace)\n if self.args.debug:\n self.args.traceback = True\n self.has_stdin_data = (\n self.env.stdin\n and not self.args.ignore_stdin\n and not self.env.stdin_isatty\n )\n # Arguments processing and environment setup.\n self._apply_no_options(no_options)\n self._process_request_type()\n self._process_download_options()\n self._setup_standard_streams()\n self._process_output_options()\n self._process_pretty_options()\n self._process_format_options()\n self._guess_method()\n self._parse_items()\n if self.has_stdin_data:\n self._body_from_file(self.env.stdin)\n self._process_url()\n self._process_auth()\n\n if self.args.compress:\n # TODO: allow --compress with --chunked / --multipart\n if self.args.chunked:\n self.error('cannot combine --compress and --chunked')\n if self.args.multipart:\n self.error('cannot combine --compress and --multipart')\n\n return self.args", "focal_method_lines": [68, 105], "in_stack": false, "globals": [], "type_context": "import argparse\nimport errno\nimport os\nimport re\nimport sys\nfrom argparse import RawDescriptionHelpFormatter\nfrom textwrap import dedent\nfrom urllib.parse import urlsplit\nfrom requests.utils import get_netrc_auth\nfrom httpie.cli.argtypes import (\n AuthCredentials, KeyValueArgType, PARSED_DEFAULT_FORMAT_OPTIONS,\n parse_auth,\n parse_format_options,\n)\nfrom httpie.cli.constants import (\n HTTP_GET, HTTP_POST, OUTPUT_OPTIONS, OUTPUT_OPTIONS_DEFAULT,\n OUTPUT_OPTIONS_DEFAULT_OFFLINE, OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED,\n OUT_RESP_BODY, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY, RequestType,\n SEPARATOR_CREDENTIALS,\n SEPARATOR_GROUP_ALL_ITEMS, SEPARATOR_GROUP_DATA_ITEMS, URL_SCHEME_RE,\n)\nfrom httpie.cli.exceptions import ParseError\nfrom httpie.cli.requestitems import RequestItems\nfrom httpie.context import Environment\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.utils import ExplicitNullAuth, get_content_type\n\n\n\nclass HTTPieArgumentParser(argparse.ArgumentParser):\n\n def __init__(self, *args, formatter_class=HTTPieHelpFormatter, **kwargs):\n kwargs['add_help'] = False\n super().__init__(*args, formatter_class=formatter_class, **kwargs)\n self.env = None\n self.args = None\n self.has_stdin_data = False\n\n def parse_args(\n self,\n env: Environment,\n args=None,\n namespace=None\n ) -> argparse.Namespace:\n self.env = env\n self.args, no_options = super().parse_known_args(args, namespace)\n if self.args.debug:\n self.args.traceback = True\n self.has_stdin_data = (\n self.env.stdin\n and not self.args.ignore_stdin\n and not self.env.stdin_isatty\n )\n # Arguments processing and environment setup.\n self._apply_no_options(no_options)\n self._process_request_type()\n self._process_download_options()\n self._setup_standard_streams()\n self._process_output_options()\n self._process_pretty_options()\n self._process_format_options()\n self._guess_method()\n self._parse_items()\n if self.has_stdin_data:\n self._body_from_file(self.env.stdin)\n self._process_url()\n self._process_auth()\n\n if self.args.compress:\n # TODO: allow --compress with --chunked / --multipart\n if self.args.chunked:\n self.error('cannot combine --compress and --chunked')\n if self.args.multipart:\n self.error('cannot combine --compress and --multipart')\n\n return self.args", "has_branch": true, "total_branches": 2} {"prompt_id": 100, "project": "httpie", "module": "httpie.cli.definition", "class": "_AuthTypeLazyChoices", "method": "__contains__", "focal_method_txt": " def __contains__(self, item):\n return item in plugin_manager.get_auth_plugin_mapping()", "focal_method_lines": [522, 523], "in_stack": false, "globals": ["parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting"], "type_context": "from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE)\nfrom textwrap import dedent, wrap\nfrom httpie import __doc__, __version__\nfrom httpie.cli.argparser import HTTPieArgumentParser\nfrom httpie.cli.argtypes import (\n KeyValueArgType, SessionNameValidator,\n readable_file_arg,\n)\nfrom httpie.cli.constants import (\n DEFAULT_FORMAT_OPTIONS, OUTPUT_OPTIONS,\n OUTPUT_OPTIONS_DEFAULT, OUT_REQ_BODY, OUT_REQ_HEAD,\n OUT_RESP_BODY, OUT_RESP_HEAD, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY,\n RequestType, SEPARATOR_GROUP_ALL_ITEMS, SEPARATOR_PROXY,\n SORTED_FORMAT_OPTIONS_STRING,\n UNSORTED_FORMAT_OPTIONS_STRING,\n)\nfrom httpie.output.formatters.colors import (\n AUTO_STYLE, AVAILABLE_STYLES, DEFAULT_STYLE,\n)\nfrom httpie.plugins.builtin import BuiltinAuthPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import DEFAULT_SESSIONS_DIR\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, DEFAULT_SSL_CIPHERS\n\nparser = HTTPieArgumentParser(\n prog='http',\n description='%s ' % __doc__.strip(),\n epilog=dedent('''\n For every --OPTION there is also a --no-OPTION that reverts OPTION\n to its default value.\n\n Suggestions and bug reports are greatly appreciated:\n\n https://github.com/httpie/httpie/issues\n\n '''),\n)\npositional = parser.add_argument_group(\n title='Positional Arguments',\n description=dedent('''\n These arguments come after any flags and in the order they are listed here.\n Only URL is required.\n\n ''')\n)\ncontent_type = parser.add_argument_group(\n title='Predefined Content Types',\n description=None\n)\ncontent_processing = parser.add_argument_group(\n title='Content Processing Options',\n description=None\n)\noutput_processing = parser.add_argument_group(title='Output Processing')\n_sorted_kwargs = {\n 'action': 'append_const',\n 'const': SORTED_FORMAT_OPTIONS_STRING,\n 'dest': 'format_options'\n}\n_unsorted_kwargs = {\n 'action': 'append_const',\n 'const': UNSORTED_FORMAT_OPTIONS_STRING,\n 'dest': 'format_options'\n}\noutput_options = parser.add_argument_group(title='Output Options')\nsessions = parser.add_argument_group(title='Sessions') \\\n .add_mutually_exclusive_group(required=False)\nsession_name_validator = SessionNameValidator(\n 'Session name contains invalid characters.'\n)\nauth = parser.add_argument_group(title='Authentication')\n_auth_plugins = plugin_manager.get_auth_plugins()\nnetwork = parser.add_argument_group(title='Network')\nssl = parser.add_argument_group(title='SSL')\ntroubleshooting = parser.add_argument_group(title='Troubleshooting')\n\nclass _AuthTypeLazyChoices:\n # Needed for plugin testing\n\n def __contains__(self, item):\n return item in plugin_manager.get_auth_plugin_mapping()", "has_branch": false, "total_branches": 0} {"prompt_id": 101, "project": "httpie", "module": "httpie.cli.definition", "class": "_AuthTypeLazyChoices", "method": "__iter__", "focal_method_txt": " def __iter__(self):\n return iter(sorted(plugin_manager.get_auth_plugin_mapping().keys()))", "focal_method_lines": [525, 526], "in_stack": false, "globals": ["parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting"], "type_context": "from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE)\nfrom textwrap import dedent, wrap\nfrom httpie import __doc__, __version__\nfrom httpie.cli.argparser import HTTPieArgumentParser\nfrom httpie.cli.argtypes import (\n KeyValueArgType, SessionNameValidator,\n readable_file_arg,\n)\nfrom httpie.cli.constants import (\n DEFAULT_FORMAT_OPTIONS, OUTPUT_OPTIONS,\n OUTPUT_OPTIONS_DEFAULT, OUT_REQ_BODY, OUT_REQ_HEAD,\n OUT_RESP_BODY, OUT_RESP_HEAD, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY,\n RequestType, SEPARATOR_GROUP_ALL_ITEMS, SEPARATOR_PROXY,\n SORTED_FORMAT_OPTIONS_STRING,\n UNSORTED_FORMAT_OPTIONS_STRING,\n)\nfrom httpie.output.formatters.colors import (\n AUTO_STYLE, AVAILABLE_STYLES, DEFAULT_STYLE,\n)\nfrom httpie.plugins.builtin import BuiltinAuthPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import DEFAULT_SESSIONS_DIR\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, DEFAULT_SSL_CIPHERS\n\nparser = HTTPieArgumentParser(\n prog='http',\n description='%s ' % __doc__.strip(),\n epilog=dedent('''\n For every --OPTION there is also a --no-OPTION that reverts OPTION\n to its default value.\n\n Suggestions and bug reports are greatly appreciated:\n\n https://github.com/httpie/httpie/issues\n\n '''),\n)\npositional = parser.add_argument_group(\n title='Positional Arguments',\n description=dedent('''\n These arguments come after any flags and in the order they are listed here.\n Only URL is required.\n\n ''')\n)\ncontent_type = parser.add_argument_group(\n title='Predefined Content Types',\n description=None\n)\ncontent_processing = parser.add_argument_group(\n title='Content Processing Options',\n description=None\n)\noutput_processing = parser.add_argument_group(title='Output Processing')\n_sorted_kwargs = {\n 'action': 'append_const',\n 'const': SORTED_FORMAT_OPTIONS_STRING,\n 'dest': 'format_options'\n}\n_unsorted_kwargs = {\n 'action': 'append_const',\n 'const': UNSORTED_FORMAT_OPTIONS_STRING,\n 'dest': 'format_options'\n}\noutput_options = parser.add_argument_group(title='Output Options')\nsessions = parser.add_argument_group(title='Sessions') \\\n .add_mutually_exclusive_group(required=False)\nsession_name_validator = SessionNameValidator(\n 'Session name contains invalid characters.'\n)\nauth = parser.add_argument_group(title='Authentication')\n_auth_plugins = plugin_manager.get_auth_plugins()\nnetwork = parser.add_argument_group(title='Network')\nssl = parser.add_argument_group(title='SSL')\ntroubleshooting = parser.add_argument_group(title='Troubleshooting')\n\nclass _AuthTypeLazyChoices:\n # Needed for plugin testing\n\n def __iter__(self):\n return iter(sorted(plugin_manager.get_auth_plugin_mapping().keys()))", "has_branch": false, "total_branches": 0} {"prompt_id": 102, "project": "httpie", "module": "httpie.cli.requestitems", "class": "", "method": "process_file_upload_arg", "focal_method_txt": "def process_file_upload_arg(arg: KeyValueArg) -> Tuple[str, IO, str]:\n parts = arg.value.split(SEPARATOR_FILE_UPLOAD_TYPE)\n filename = parts[0]\n mime_type = parts[1] if len(parts) > 1 else None\n try:\n f = open(os.path.expanduser(filename), 'rb')\n except IOError as e:\n raise ParseError('\"%s\": %s' % (arg.orig, e))\n return (\n os.path.basename(filename),\n f,\n mime_type or get_content_type(filename),\n )", "focal_method_lines": [104, 112], "in_stack": false, "globals": ["JSONType"], "type_context": "import os\nfrom typing import Callable, Dict, IO, List, Optional, Tuple, Union\nfrom httpie.cli.argtypes import KeyValueArg\nfrom httpie.cli.constants import (\n SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS,\n SEPARATOR_DATA_EMBED_RAW_JSON_FILE,\n SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD,\n SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY,\n SEPARATOR_QUERY_PARAM,\n)\nfrom httpie.cli.dicts import (\n MultipartRequestDataDict, RequestDataDict, RequestFilesDict,\n RequestHeadersDict, RequestJSONDataDict,\n RequestQueryParamsDict,\n)\nfrom httpie.cli.exceptions import ParseError\nfrom httpie.utils import (get_content_type, load_json_preserve_order)\n\nJSONType = Union[str, bool, int, list, dict]\n\ndef process_file_upload_arg(arg: KeyValueArg) -> Tuple[str, IO, str]:\n parts = arg.value.split(SEPARATOR_FILE_UPLOAD_TYPE)\n filename = parts[0]\n mime_type = parts[1] if len(parts) > 1 else None\n try:\n f = open(os.path.expanduser(filename), 'rb')\n except IOError as e:\n raise ParseError('\"%s\": %s' % (arg.orig, e))\n return (\n os.path.basename(filename),\n f,\n mime_type or get_content_type(filename),\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 103, "project": "httpie", "module": "httpie.cli.requestitems", "class": "", "method": "process_data_embed_raw_json_file_arg", "focal_method_txt": "def process_data_embed_raw_json_file_arg(arg: KeyValueArg) -> JSONType:\n contents = load_text_file(arg)\n value = load_json(arg, contents)\n return value", "focal_method_lines": [127, 130], "in_stack": false, "globals": ["JSONType"], "type_context": "import os\nfrom typing import Callable, Dict, IO, List, Optional, Tuple, Union\nfrom httpie.cli.argtypes import KeyValueArg\nfrom httpie.cli.constants import (\n SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS,\n SEPARATOR_DATA_EMBED_RAW_JSON_FILE,\n SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD,\n SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY,\n SEPARATOR_QUERY_PARAM,\n)\nfrom httpie.cli.dicts import (\n MultipartRequestDataDict, RequestDataDict, RequestFilesDict,\n RequestHeadersDict, RequestJSONDataDict,\n RequestQueryParamsDict,\n)\nfrom httpie.cli.exceptions import ParseError\nfrom httpie.utils import (get_content_type, load_json_preserve_order)\n\nJSONType = Union[str, bool, int, list, dict]\n\ndef process_data_embed_raw_json_file_arg(arg: KeyValueArg) -> JSONType:\n contents = load_text_file(arg)\n value = load_json(arg, contents)\n return value", "has_branch": false, "total_branches": 0} {"prompt_id": 104, "project": "httpie", "module": "httpie.cli.requestitems", "class": "", "method": "process_data_raw_json_embed_arg", "focal_method_txt": "def process_data_raw_json_embed_arg(arg: KeyValueArg) -> JSONType:\n value = load_json(arg, arg.value)\n return value", "focal_method_lines": [133, 135], "in_stack": false, "globals": ["JSONType"], "type_context": "import os\nfrom typing import Callable, Dict, IO, List, Optional, Tuple, Union\nfrom httpie.cli.argtypes import KeyValueArg\nfrom httpie.cli.constants import (\n SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS,\n SEPARATOR_DATA_EMBED_RAW_JSON_FILE,\n SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD,\n SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY,\n SEPARATOR_QUERY_PARAM,\n)\nfrom httpie.cli.dicts import (\n MultipartRequestDataDict, RequestDataDict, RequestFilesDict,\n RequestHeadersDict, RequestJSONDataDict,\n RequestQueryParamsDict,\n)\nfrom httpie.cli.exceptions import ParseError\nfrom httpie.utils import (get_content_type, load_json_preserve_order)\n\nJSONType = Union[str, bool, int, list, dict]\n\ndef process_data_raw_json_embed_arg(arg: KeyValueArg) -> JSONType:\n value = load_json(arg, arg.value)\n return value", "has_branch": false, "total_branches": 0} {"prompt_id": 105, "project": "httpie", "module": "httpie.cli.requestitems", "class": "", "method": "load_text_file", "focal_method_txt": "def load_text_file(item: KeyValueArg) -> str:\n path = item.value\n try:\n with open(os.path.expanduser(path), 'rb') as f:\n return f.read().decode()\n except IOError as e:\n raise ParseError('\"%s\": %s' % (item.orig, e))\n except UnicodeDecodeError:\n raise ParseError(\n '\"%s\": cannot embed the content of \"%s\",'\n ' not a UTF8 or ASCII-encoded text file'\n % (item.orig, item.value)\n )", "focal_method_lines": [138, 146], "in_stack": false, "globals": ["JSONType"], "type_context": "import os\nfrom typing import Callable, Dict, IO, List, Optional, Tuple, Union\nfrom httpie.cli.argtypes import KeyValueArg\nfrom httpie.cli.constants import (\n SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS,\n SEPARATOR_DATA_EMBED_RAW_JSON_FILE,\n SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEPARATOR_FILE_UPLOAD,\n SEPARATOR_FILE_UPLOAD_TYPE, SEPARATOR_HEADER, SEPARATOR_HEADER_EMPTY,\n SEPARATOR_QUERY_PARAM,\n)\nfrom httpie.cli.dicts import (\n MultipartRequestDataDict, RequestDataDict, RequestFilesDict,\n RequestHeadersDict, RequestJSONDataDict,\n RequestQueryParamsDict,\n)\nfrom httpie.cli.exceptions import ParseError\nfrom httpie.utils import (get_content_type, load_json_preserve_order)\n\nJSONType = Union[str, bool, int, list, dict]\n\ndef load_text_file(item: KeyValueArg) -> str:\n path = item.value\n try:\n with open(os.path.expanduser(path), 'rb') as f:\n return f.read().decode()\n except IOError as e:\n raise ParseError('\"%s\": %s' % (item.orig, e))\n except UnicodeDecodeError:\n raise ParseError(\n '\"%s\": cannot embed the content of \"%s\",'\n ' not a UTF8 or ASCII-encoded text file'\n % (item.orig, item.value)\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 106, "project": "httpie", "module": "httpie.client", "class": "", "method": "collect_messages", "focal_method_txt": "def collect_messages(\n args: argparse.Namespace,\n config_dir: Path,\n request_body_read_callback: Callable[[bytes], None] = None,\n) -> Iterable[Union[requests.PreparedRequest, requests.Response]]:\n httpie_session = None\n httpie_session_headers = None\n if args.session or args.session_read_only:\n httpie_session = get_httpie_session(\n config_dir=config_dir,\n session_name=args.session or args.session_read_only,\n host=args.headers.get('Host'),\n url=args.url,\n )\n httpie_session_headers = httpie_session.headers\n\n request_kwargs = make_request_kwargs(\n args=args,\n base_headers=httpie_session_headers,\n request_body_read_callback=request_body_read_callback\n )\n send_kwargs = make_send_kwargs(args)\n send_kwargs_mergeable_from_env = make_send_kwargs_mergeable_from_env(args)\n requests_session = build_requests_session(\n ssl_version=args.ssl_version,\n ciphers=args.ciphers,\n verify=bool(send_kwargs_mergeable_from_env['verify'])\n )\n\n if httpie_session:\n httpie_session.update_headers(request_kwargs['headers'])\n requests_session.cookies = httpie_session.cookies\n if args.auth_plugin:\n # Save auth from CLI to HTTPie session.\n httpie_session.auth = {\n 'type': args.auth_plugin.auth_type,\n 'raw_auth': args.auth_plugin.raw_auth,\n }\n elif httpie_session.auth:\n # Apply auth from HTTPie session\n request_kwargs['auth'] = httpie_session.auth\n\n if args.debug:\n # TODO: reflect the split between request and send kwargs.\n dump_request(request_kwargs)\n\n request = requests.Request(**request_kwargs)\n prepared_request = requests_session.prepare_request(request)\n if args.path_as_is:\n prepared_request.url = ensure_path_as_is(\n orig_url=args.url,\n prepped_url=prepared_request.url,\n )\n if args.compress and prepared_request.body:\n compress_request(\n request=prepared_request,\n always=args.compress > 1,\n )\n response_count = 0\n expired_cookies = []\n while prepared_request:\n yield prepared_request\n if not args.offline:\n send_kwargs_merged = requests_session.merge_environment_settings(\n url=prepared_request.url,\n **send_kwargs_mergeable_from_env,\n )\n with max_headers(args.max_headers):\n response = requests_session.send(\n request=prepared_request,\n **send_kwargs_merged,\n **send_kwargs,\n )\n\n # noinspection PyProtectedMember\n expired_cookies += get_expired_cookies(\n headers=response.raw._original_response.msg._headers\n )\n\n response_count += 1\n if response.next:\n if args.max_redirects and response_count == args.max_redirects:\n raise requests.TooManyRedirects\n if args.follow:\n prepared_request = response.next\n if args.all:\n yield response\n continue\n yield response\n break\n\n if httpie_session:\n if httpie_session.is_new() or not args.session_read_only:\n httpie_session.cookies = requests_session.cookies\n httpie_session.remove_cookies(\n # TODO: take path & domain into account?\n cookie['name'] for cookie in expired_cookies\n )\n httpie_session.save()", "focal_method_lines": [32, 130], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef collect_messages(\n args: argparse.Namespace,\n config_dir: Path,\n request_body_read_callback: Callable[[bytes], None] = None,\n) -> Iterable[Union[requests.PreparedRequest, requests.Response]]:\n httpie_session = None\n httpie_session_headers = None\n if args.session or args.session_read_only:\n httpie_session = get_httpie_session(\n config_dir=config_dir,\n session_name=args.session or args.session_read_only,\n host=args.headers.get('Host'),\n url=args.url,\n )\n httpie_session_headers = httpie_session.headers\n\n request_kwargs = make_request_kwargs(\n args=args,\n base_headers=httpie_session_headers,\n request_body_read_callback=request_body_read_callback\n )\n send_kwargs = make_send_kwargs(args)\n send_kwargs_mergeable_from_env = make_send_kwargs_mergeable_from_env(args)\n requests_session = build_requests_session(\n ssl_version=args.ssl_version,\n ciphers=args.ciphers,\n verify=bool(send_kwargs_mergeable_from_env['verify'])\n )\n\n if httpie_session:\n httpie_session.update_headers(request_kwargs['headers'])\n requests_session.cookies = httpie_session.cookies\n if args.auth_plugin:\n # Save auth from CLI to HTTPie session.\n httpie_session.auth = {\n 'type': args.auth_plugin.auth_type,\n 'raw_auth': args.auth_plugin.raw_auth,\n }\n elif httpie_session.auth:\n # Apply auth from HTTPie session\n request_kwargs['auth'] = httpie_session.auth\n\n if args.debug:\n # TODO: reflect the split between request and send kwargs.\n dump_request(request_kwargs)\n\n request = requests.Request(**request_kwargs)\n prepared_request = requests_session.prepare_request(request)\n if args.path_as_is:\n prepared_request.url = ensure_path_as_is(\n orig_url=args.url,\n prepped_url=prepared_request.url,\n )\n if args.compress and prepared_request.body:\n compress_request(\n request=prepared_request,\n always=args.compress > 1,\n )\n response_count = 0\n expired_cookies = []\n while prepared_request:\n yield prepared_request\n if not args.offline:\n send_kwargs_merged = requests_session.merge_environment_settings(\n url=prepared_request.url,\n **send_kwargs_mergeable_from_env,\n )\n with max_headers(args.max_headers):\n response = requests_session.send(\n request=prepared_request,\n **send_kwargs_merged,\n **send_kwargs,\n )\n\n # noinspection PyProtectedMember\n expired_cookies += get_expired_cookies(\n headers=response.raw._original_response.msg._headers\n )\n\n response_count += 1\n if response.next:\n if args.max_redirects and response_count == args.max_redirects:\n raise requests.TooManyRedirects\n if args.follow:\n prepared_request = response.next\n if args.all:\n yield response\n continue\n yield response\n break\n\n if httpie_session:\n if httpie_session.is_new() or not args.session_read_only:\n httpie_session.cookies = requests_session.cookies\n httpie_session.remove_cookies(\n # TODO: take path & domain into account?\n cookie['name'] for cookie in expired_cookies\n )\n httpie_session.save()", "has_branch": true, "total_branches": 2} {"prompt_id": 107, "project": "httpie", "module": "httpie.client", "class": "", "method": "build_requests_session", "focal_method_txt": "def build_requests_session(\n verify: bool,\n ssl_version: str = None,\n ciphers: str = None,\n) -> requests.Session:\n requests_session = requests.Session()\n\n # Install our adapter.\n https_adapter = HTTPieHTTPSAdapter(\n ciphers=ciphers,\n verify=verify,\n ssl_version=(\n AVAILABLE_SSL_VERSION_ARG_MAPPING[ssl_version]\n if ssl_version else None\n ),\n )\n requests_session.mount('https://', https_adapter)\n\n # Install adapters from plugins.\n for plugin_cls in plugin_manager.get_transport_plugins():\n transport_plugin = plugin_cls()\n requests_session.mount(\n prefix=transport_plugin.prefix,\n adapter=transport_plugin.get_adapter(),\n )\n\n return requests_session", "focal_method_lines": [146, 172], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef build_requests_session(\n verify: bool,\n ssl_version: str = None,\n ciphers: str = None,\n) -> requests.Session:\n requests_session = requests.Session()\n\n # Install our adapter.\n https_adapter = HTTPieHTTPSAdapter(\n ciphers=ciphers,\n verify=verify,\n ssl_version=(\n AVAILABLE_SSL_VERSION_ARG_MAPPING[ssl_version]\n if ssl_version else None\n ),\n )\n requests_session.mount('https://', https_adapter)\n\n # Install adapters from plugins.\n for plugin_cls in plugin_manager.get_transport_plugins():\n transport_plugin = plugin_cls()\n requests_session.mount(\n prefix=transport_plugin.prefix,\n adapter=transport_plugin.get_adapter(),\n )\n\n return requests_session", "has_branch": true, "total_branches": 2} {"prompt_id": 108, "project": "httpie", "module": "httpie.client", "class": "", "method": "finalize_headers", "focal_method_txt": "def finalize_headers(headers: RequestHeadersDict) -> RequestHeadersDict:\n final_headers = RequestHeadersDict()\n for name, value in headers.items():\n if value is not None:\n # “leading or trailing LWS MAY be removed without\n # changing the semantics of the field value”\n # \n # Also, requests raises `InvalidHeader` for leading spaces.\n value = value.strip()\n if isinstance(value, str):\n # See \n value = value.encode('utf8')\n final_headers[name] = value\n return final_headers", "focal_method_lines": [180, 193], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef finalize_headers(headers: RequestHeadersDict) -> RequestHeadersDict:\n final_headers = RequestHeadersDict()\n for name, value in headers.items():\n if value is not None:\n # “leading or trailing LWS MAY be removed without\n # changing the semantics of the field value”\n # \n # Also, requests raises `InvalidHeader` for leading spaces.\n value = value.strip()\n if isinstance(value, str):\n # See \n value = value.encode('utf8')\n final_headers[name] = value\n return final_headers", "has_branch": true, "total_branches": 2} {"prompt_id": 109, "project": "httpie", "module": "httpie.client", "class": "", "method": "make_default_headers", "focal_method_txt": "def make_default_headers(args: argparse.Namespace) -> RequestHeadersDict:\n default_headers = RequestHeadersDict({\n 'User-Agent': DEFAULT_UA\n })\n\n auto_json = args.data and not args.form\n if args.json or auto_json:\n default_headers['Accept'] = JSON_ACCEPT\n if args.json or (auto_json and args.data):\n default_headers['Content-Type'] = JSON_CONTENT_TYPE\n\n elif args.form and not args.files:\n # If sending files, `requests` will set\n # the `Content-Type` for us.\n default_headers['Content-Type'] = FORM_CONTENT_TYPE\n return default_headers", "focal_method_lines": [196, 211], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef make_default_headers(args: argparse.Namespace) -> RequestHeadersDict:\n default_headers = RequestHeadersDict({\n 'User-Agent': DEFAULT_UA\n })\n\n auto_json = args.data and not args.form\n if args.json or auto_json:\n default_headers['Accept'] = JSON_ACCEPT\n if args.json or (auto_json and args.data):\n default_headers['Content-Type'] = JSON_CONTENT_TYPE\n\n elif args.form and not args.files:\n # If sending files, `requests` will set\n # the `Content-Type` for us.\n default_headers['Content-Type'] = FORM_CONTENT_TYPE\n return default_headers", "has_branch": true, "total_branches": 2} {"prompt_id": 110, "project": "httpie", "module": "httpie.client", "class": "", "method": "make_send_kwargs", "focal_method_txt": "def make_send_kwargs(args: argparse.Namespace) -> dict:\n kwargs = {\n 'timeout': args.timeout or None,\n 'allow_redirects': False,\n }\n return kwargs", "focal_method_lines": [214, 219], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef make_send_kwargs(args: argparse.Namespace) -> dict:\n kwargs = {\n 'timeout': args.timeout or None,\n 'allow_redirects': False,\n }\n return kwargs", "has_branch": false, "total_branches": 0} {"prompt_id": 111, "project": "httpie", "module": "httpie.client", "class": "", "method": "make_send_kwargs_mergeable_from_env", "focal_method_txt": "def make_send_kwargs_mergeable_from_env(args: argparse.Namespace) -> dict:\n cert = None\n if args.cert:\n cert = args.cert\n if args.cert_key:\n cert = cert, args.cert_key\n kwargs = {\n 'proxies': {p.key: p.value for p in args.proxy},\n 'stream': True,\n 'verify': {\n 'yes': True,\n 'true': True,\n 'no': False,\n 'false': False,\n }.get(args.verify.lower(), args.verify),\n 'cert': cert,\n }\n return kwargs", "focal_method_lines": [222, 239], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef make_send_kwargs_mergeable_from_env(args: argparse.Namespace) -> dict:\n cert = None\n if args.cert:\n cert = args.cert\n if args.cert_key:\n cert = cert, args.cert_key\n kwargs = {\n 'proxies': {p.key: p.value for p in args.proxy},\n 'stream': True,\n 'verify': {\n 'yes': True,\n 'true': True,\n 'no': False,\n 'false': False,\n }.get(args.verify.lower(), args.verify),\n 'cert': cert,\n }\n return kwargs", "has_branch": true, "total_branches": 2} {"prompt_id": 112, "project": "httpie", "module": "httpie.client", "class": "", "method": "make_request_kwargs", "focal_method_txt": "def make_request_kwargs(\n args: argparse.Namespace,\n base_headers: RequestHeadersDict = None,\n request_body_read_callback=lambda chunk: chunk\n) -> dict:\n \"\"\"\n Translate our `args` into `requests.Request` keyword arguments.\n\n \"\"\"\n files = args.files\n # Serialize JSON data, if needed.\n data = args.data\n auto_json = data and not args.form\n if (args.json or auto_json) and isinstance(data, dict):\n if data:\n data = json.dumps(data)\n else:\n # We need to set data to an empty string to prevent requests\n # from assigning an empty list to `response.request.data`.\n data = ''\n\n # Finalize headers.\n headers = make_default_headers(args)\n if base_headers:\n headers.update(base_headers)\n headers.update(args.headers)\n if args.offline and args.chunked and 'Transfer-Encoding' not in headers:\n # When online, we let requests set the header instead to be able more\n # easily verify chunking is taking place.\n headers['Transfer-Encoding'] = 'chunked'\n headers = finalize_headers(headers)\n\n if (args.form and files) or args.multipart:\n data, headers['Content-Type'] = get_multipart_data_and_content_type(\n data=args.multipart_data,\n boundary=args.boundary,\n content_type=args.headers.get('Content-Type'),\n )\n\n kwargs = {\n 'method': args.method.lower(),\n 'url': args.url,\n 'headers': headers,\n 'data': prepare_request_body(\n body=data,\n body_read_callback=request_body_read_callback,\n chunked=args.chunked,\n offline=args.offline,\n content_length_header_value=headers.get('Content-Length'),\n ),\n 'auth': args.auth,\n 'params': args.params.items(),\n }\n\n return kwargs", "focal_method_lines": [242, 296], "in_stack": false, "globals": ["FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA"], "type_context": "import argparse\nimport http.client\nimport json\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Callable, Iterable, Union\nfrom urllib.parse import urlparse, urlunparse\nimport requests\nimport urllib3\nfrom httpie import __version__\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.sessions import get_httpie_session\nfrom httpie.ssl import AVAILABLE_SSL_VERSION_ARG_MAPPING, HTTPieHTTPSAdapter\nfrom httpie.uploads import (\n compress_request, prepare_request_body,\n get_multipart_data_and_content_type,\n)\nfrom httpie.utils import get_expired_cookies, repr_dict\n\nFORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8'\nJSON_CONTENT_TYPE = 'application/json'\nJSON_ACCEPT = f'{JSON_CONTENT_TYPE}, */*;q=0.5'\nDEFAULT_UA = f'HTTPie/{__version__}'\n\ndef make_request_kwargs(\n args: argparse.Namespace,\n base_headers: RequestHeadersDict = None,\n request_body_read_callback=lambda chunk: chunk\n) -> dict:\n \"\"\"\n Translate our `args` into `requests.Request` keyword arguments.\n\n \"\"\"\n files = args.files\n # Serialize JSON data, if needed.\n data = args.data\n auto_json = data and not args.form\n if (args.json or auto_json) and isinstance(data, dict):\n if data:\n data = json.dumps(data)\n else:\n # We need to set data to an empty string to prevent requests\n # from assigning an empty list to `response.request.data`.\n data = ''\n\n # Finalize headers.\n headers = make_default_headers(args)\n if base_headers:\n headers.update(base_headers)\n headers.update(args.headers)\n if args.offline and args.chunked and 'Transfer-Encoding' not in headers:\n # When online, we let requests set the header instead to be able more\n # easily verify chunking is taking place.\n headers['Transfer-Encoding'] = 'chunked'\n headers = finalize_headers(headers)\n\n if (args.form and files) or args.multipart:\n data, headers['Content-Type'] = get_multipart_data_and_content_type(\n data=args.multipart_data,\n boundary=args.boundary,\n content_type=args.headers.get('Content-Type'),\n )\n\n kwargs = {\n 'method': args.method.lower(),\n 'url': args.url,\n 'headers': headers,\n 'data': prepare_request_body(\n body=data,\n body_read_callback=request_body_read_callback,\n chunked=args.chunked,\n offline=args.offline,\n content_length_header_value=headers.get('Content-Length'),\n ),\n 'auth': args.auth,\n 'params': args.params.items(),\n }\n\n return kwargs", "has_branch": true, "total_branches": 2} {"prompt_id": 113, "project": "httpie", "module": "httpie.config", "class": "", "method": "get_default_config_dir", "focal_method_txt": "def get_default_config_dir() -> Path:\n \"\"\"\n Return the path to the httpie configuration directory.\n\n This directory isn't guaranteed to exist, and nor are any of its\n ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist).\n\n XDG Base Directory Specification support:\n\n \n\n $XDG_CONFIG_HOME is supported; $XDG_CONFIG_DIRS is not\n\n \"\"\"\n # 1. explicitly set through env\n env_config_dir = os.environ.get(ENV_HTTPIE_CONFIG_DIR)\n if env_config_dir:\n return Path(env_config_dir)\n\n # 2. Windows\n if is_windows:\n return DEFAULT_WINDOWS_CONFIG_DIR\n\n home_dir = Path.home()\n\n # 3. legacy ~/.httpie\n legacy_config_dir = home_dir / DEFAULT_RELATIVE_LEGACY_CONFIG_DIR\n if legacy_config_dir.exists():\n return legacy_config_dir\n\n # 4. XDG\n xdg_config_home_dir = os.environ.get(\n ENV_XDG_CONFIG_HOME, # 4.1. explicit\n home_dir / DEFAULT_RELATIVE_XDG_CONFIG_HOME # 4.2. default\n )\n return Path(xdg_config_home_dir) / DEFAULT_CONFIG_DIRNAME", "focal_method_lines": [19, 54], "in_stack": false, "globals": ["ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR"], "type_context": "import errno\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import Union\nfrom httpie import __version__\nfrom httpie.compat import is_windows\n\nENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME'\nENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR'\nDEFAULT_CONFIG_DIRNAME = 'httpie'\nDEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config')\nDEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie')\nDEFAULT_WINDOWS_CONFIG_DIR = Path(\n os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME\nDEFAULT_CONFIG_DIR = get_default_config_dir()\n\ndef get_default_config_dir() -> Path:\n \"\"\"\n Return the path to the httpie configuration directory.\n\n This directory isn't guaranteed to exist, and nor are any of its\n ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist).\n\n XDG Base Directory Specification support:\n\n \n\n $XDG_CONFIG_HOME is supported; $XDG_CONFIG_DIRS is not\n\n \"\"\"\n # 1. explicitly set through env\n env_config_dir = os.environ.get(ENV_HTTPIE_CONFIG_DIR)\n if env_config_dir:\n return Path(env_config_dir)\n\n # 2. Windows\n if is_windows:\n return DEFAULT_WINDOWS_CONFIG_DIR\n\n home_dir = Path.home()\n\n # 3. legacy ~/.httpie\n legacy_config_dir = home_dir / DEFAULT_RELATIVE_LEGACY_CONFIG_DIR\n if legacy_config_dir.exists():\n return legacy_config_dir\n\n # 4. XDG\n xdg_config_home_dir = os.environ.get(\n ENV_XDG_CONFIG_HOME, # 4.1. explicit\n home_dir / DEFAULT_RELATIVE_XDG_CONFIG_HOME # 4.2. default\n )\n return Path(xdg_config_home_dir) / DEFAULT_CONFIG_DIRNAME", "has_branch": true, "total_branches": 2} {"prompt_id": 114, "project": "httpie", "module": "httpie.config", "class": "BaseConfigDict", "method": "ensure_directory", "focal_method_txt": " def ensure_directory(self):\n try:\n self.path.parent.mkdir(mode=0o700, parents=True)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise", "focal_method_lines": [73, 78], "in_stack": false, "globals": ["ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR"], "type_context": "import errno\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import Union\nfrom httpie import __version__\nfrom httpie.compat import is_windows\n\nENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME'\nENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR'\nDEFAULT_CONFIG_DIRNAME = 'httpie'\nDEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config')\nDEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie')\nDEFAULT_WINDOWS_CONFIG_DIR = Path(\n os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME\nDEFAULT_CONFIG_DIR = get_default_config_dir()\n\nclass BaseConfigDict(dict):\n\n name = None\n\n helpurl = None\n\n about = None\n\n def __init__(self, path: Path):\n super().__init__()\n self.path = path\n\n def ensure_directory(self):\n try:\n self.path.parent.mkdir(mode=0o700, parents=True)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise", "has_branch": true, "total_branches": 2} {"prompt_id": 115, "project": "httpie", "module": "httpie.config", "class": "BaseConfigDict", "method": "load", "focal_method_txt": " def load(self):\n config_type = type(self).__name__.lower()\n try:\n with self.path.open('rt') as f:\n try:\n data = json.load(f)\n except ValueError as e:\n raise ConfigFileError(\n f'invalid {config_type} file: {e} [{self.path}]'\n )\n self.update(data)\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise ConfigFileError(f'cannot read {config_type} file: {e}')", "focal_method_lines": [83, 96], "in_stack": false, "globals": ["ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR"], "type_context": "import errno\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import Union\nfrom httpie import __version__\nfrom httpie.compat import is_windows\n\nENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME'\nENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR'\nDEFAULT_CONFIG_DIRNAME = 'httpie'\nDEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config')\nDEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie')\nDEFAULT_WINDOWS_CONFIG_DIR = Path(\n os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME\nDEFAULT_CONFIG_DIR = get_default_config_dir()\n\nclass Config(BaseConfigDict):\n\n FILENAME = 'config.json'\n\n DEFAULTS = {\n 'default_options': []\n }\n\n def __init__(self, directory: Union[str, Path] = DEFAULT_CONFIG_DIR):\n self.directory = Path(directory)\n super().__init__(path=self.directory / self.FILENAME)\n self.update(self.DEFAULTS)\n\nclass BaseConfigDict(dict):\n\n name = None\n\n helpurl = None\n\n about = None\n\n def __init__(self, path: Path):\n super().__init__()\n self.path = path\n\n def load(self):\n config_type = type(self).__name__.lower()\n try:\n with self.path.open('rt') as f:\n try:\n data = json.load(f)\n except ValueError as e:\n raise ConfigFileError(\n f'invalid {config_type} file: {e} [{self.path}]'\n )\n self.update(data)\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise ConfigFileError(f'cannot read {config_type} file: {e}')", "has_branch": true, "total_branches": 2} {"prompt_id": 116, "project": "httpie", "module": "httpie.config", "class": "BaseConfigDict", "method": "save", "focal_method_txt": " def save(self, fail_silently=False):\n self['__meta__'] = {\n 'httpie': __version__\n }\n if self.helpurl:\n self['__meta__']['help'] = self.helpurl\n\n if self.about:\n self['__meta__']['about'] = self.about\n\n self.ensure_directory()\n\n json_string = json.dumps(\n obj=self,\n indent=4,\n sort_keys=True,\n ensure_ascii=True,\n )\n try:\n self.path.write_text(json_string + '\\n')\n except IOError:\n if not fail_silently:\n raise", "focal_method_lines": [98, 120], "in_stack": false, "globals": ["ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR"], "type_context": "import errno\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import Union\nfrom httpie import __version__\nfrom httpie.compat import is_windows\n\nENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME'\nENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR'\nDEFAULT_CONFIG_DIRNAME = 'httpie'\nDEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config')\nDEFAULT_RELATIVE_LEGACY_CONFIG_DIR = Path('.httpie')\nDEFAULT_WINDOWS_CONFIG_DIR = Path(\n os.path.expandvars('%APPDATA%')) / DEFAULT_CONFIG_DIRNAME\nDEFAULT_CONFIG_DIR = get_default_config_dir()\n\nclass BaseConfigDict(dict):\n\n name = None\n\n helpurl = None\n\n about = None\n\n def __init__(self, path: Path):\n super().__init__()\n self.path = path\n\n def save(self, fail_silently=False):\n self['__meta__'] = {\n 'httpie': __version__\n }\n if self.helpurl:\n self['__meta__']['help'] = self.helpurl\n\n if self.about:\n self['__meta__']['about'] = self.about\n\n self.ensure_directory()\n\n json_string = json.dumps(\n obj=self,\n indent=4,\n sort_keys=True,\n ensure_ascii=True,\n )\n try:\n self.path.write_text(json_string + '\\n')\n except IOError:\n if not fail_silently:\n raise", "has_branch": true, "total_branches": 2} {"prompt_id": 117, "project": "httpie", "module": "httpie.context", "class": "Environment", "method": "__init__", "focal_method_txt": " def __init__(self, devnull=None, **kwargs):\n \"\"\"\n Use keyword arguments to overwrite\n any of the class attributes for this instance.\n\n \"\"\"\n assert all(hasattr(type(self), attr) for attr in kwargs.keys())\n self.__dict__.update(**kwargs)\n\n # The original STDERR unaffected by --quiet’ing.\n self._orig_stderr = self.stderr\n self._devnull = devnull\n\n # Keyword arguments > stream.encoding > default utf8\n if self.stdin and self.stdin_encoding is None:\n self.stdin_encoding = getattr(\n self.stdin, 'encoding', None) or 'utf8'\n if self.stdout_encoding is None:\n actual_stdout = self.stdout\n if is_windows:\n # noinspection PyUnresolvedReferences\n from colorama import AnsiToWin32\n if isinstance(self.stdout, AnsiToWin32):\n # noinspection PyUnresolvedReferences\n actual_stdout = self.stdout.wrapped\n self.stdout_encoding = getattr(\n actual_stdout, 'encoding', None) or 'utf8'", "focal_method_lines": [59, 84], "in_stack": false, "globals": [], "type_context": "import sys\nimport os\nfrom pathlib import Path\nfrom typing import IO, Optional\nfrom httpie.compat import is_windows\nfrom httpie.config import DEFAULT_CONFIG_DIR, Config, ConfigFileError\nfrom httpie.utils import repr_dict\n\n\n\nclass Environment:\n\n is_windows: bool = is_windows\n\n config_dir: Path = DEFAULT_CONFIG_DIR\n\n stdin: Optional[IO] = sys.stdin\n\n stdin_isatty: bool = stdin.isatty() if stdin else False\n\n stdin_encoding: str = None\n\n stdout: IO = sys.stdout\n\n stdout_isatty: bool = stdout.isatty()\n\n stdout_encoding: str = None\n\n stderr: IO = sys.stderr\n\n stderr_isatty: bool = stderr.isatty()\n\n colors = 256\n\n program_name: str = 'http'\n\n _config: Config = None\n\n def __init__(self, devnull=None, **kwargs):\n \"\"\"\n Use keyword arguments to overwrite\n any of the class attributes for this instance.\n\n \"\"\"\n assert all(hasattr(type(self), attr) for attr in kwargs.keys())\n self.__dict__.update(**kwargs)\n\n # The original STDERR unaffected by --quiet’ing.\n self._orig_stderr = self.stderr\n self._devnull = devnull\n\n # Keyword arguments > stream.encoding > default utf8\n if self.stdin and self.stdin_encoding is None:\n self.stdin_encoding = getattr(\n self.stdin, 'encoding', None) or 'utf8'\n if self.stdout_encoding is None:\n actual_stdout = self.stdout\n if is_windows:\n # noinspection PyUnresolvedReferences\n from colorama import AnsiToWin32\n if isinstance(self.stdout, AnsiToWin32):\n # noinspection PyUnresolvedReferences\n actual_stdout = self.stdout.wrapped\n self.stdout_encoding = getattr(\n actual_stdout, 'encoding', None) or 'utf8'", "has_branch": true, "total_branches": 2} {"prompt_id": 118, "project": "httpie", "module": "httpie.core", "class": "", "method": "main", "focal_method_txt": "def main(args: List[Union[str, bytes]] = sys.argv, env=Environment()) -> ExitStatus:\n \"\"\"\n The main function.\n\n Pre-process args, handle some special types of invocations,\n and run the main program with error handling.\n\n Return exit status code.\n\n \"\"\"\n program_name, *args = args\n env.program_name = os.path.basename(program_name)\n args = decode_raw_args(args, env.stdin_encoding)\n plugin_manager.load_installed_plugins()\n\n from httpie.cli.definition import parser\n\n if env.config.default_options:\n args = env.config.default_options + args\n\n include_debug_info = '--debug' in args\n include_traceback = include_debug_info or '--traceback' in args\n\n if include_debug_info:\n print_debug_info(env)\n if args == ['--debug']:\n return ExitStatus.SUCCESS\n\n exit_status = ExitStatus.SUCCESS\n\n try:\n parsed_args = parser.parse_args(\n args=args,\n env=env,\n )\n except KeyboardInterrupt:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR_CTRL_C\n except SystemExit as e:\n if e.code != ExitStatus.SUCCESS:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n else:\n try:\n exit_status = program(\n args=parsed_args,\n env=env,\n )\n except KeyboardInterrupt:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR_CTRL_C\n except SystemExit as e:\n if e.code != ExitStatus.SUCCESS:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n except requests.Timeout:\n exit_status = ExitStatus.ERROR_TIMEOUT\n env.log_error(f'Request timed out ({parsed_args.timeout}s).')\n except requests.TooManyRedirects:\n exit_status = ExitStatus.ERROR_TOO_MANY_REDIRECTS\n env.log_error(\n f'Too many redirects'\n f' (--max-redirects={parsed_args.max_redirects}).'\n )\n except Exception as e:\n # TODO: Further distinction between expected and unexpected errors.\n msg = str(e)\n if hasattr(e, 'request'):\n request = e.request\n if hasattr(request, 'url'):\n msg = (\n f'{msg} while doing a {request.method}'\n f' request to URL: {request.url}'\n )\n env.log_error(f'{type(e).__name__}: {msg}')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n\n return exit_status", "focal_method_lines": [21, 108], "in_stack": false, "globals": [], "type_context": "import argparse\nimport os\nimport platform\nimport sys\nfrom typing import List, Optional, Tuple, Union\nimport requests\nfrom pygments import __version__ as pygments_version\nfrom requests import __version__ as requests_version\nfrom httpie import __version__ as httpie_version\nfrom httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD\nfrom httpie.client import collect_messages\nfrom httpie.context import Environment\nfrom httpie.downloads import Downloader\nfrom httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.status import ExitStatus, http_status_to_exit_status\n\n\n\ndef main(args: List[Union[str, bytes]] = sys.argv, env=Environment()) -> ExitStatus:\n \"\"\"\n The main function.\n\n Pre-process args, handle some special types of invocations,\n and run the main program with error handling.\n\n Return exit status code.\n\n \"\"\"\n program_name, *args = args\n env.program_name = os.path.basename(program_name)\n args = decode_raw_args(args, env.stdin_encoding)\n plugin_manager.load_installed_plugins()\n\n from httpie.cli.definition import parser\n\n if env.config.default_options:\n args = env.config.default_options + args\n\n include_debug_info = '--debug' in args\n include_traceback = include_debug_info or '--traceback' in args\n\n if include_debug_info:\n print_debug_info(env)\n if args == ['--debug']:\n return ExitStatus.SUCCESS\n\n exit_status = ExitStatus.SUCCESS\n\n try:\n parsed_args = parser.parse_args(\n args=args,\n env=env,\n )\n except KeyboardInterrupt:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR_CTRL_C\n except SystemExit as e:\n if e.code != ExitStatus.SUCCESS:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n else:\n try:\n exit_status = program(\n args=parsed_args,\n env=env,\n )\n except KeyboardInterrupt:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR_CTRL_C\n except SystemExit as e:\n if e.code != ExitStatus.SUCCESS:\n env.stderr.write('\\n')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n except requests.Timeout:\n exit_status = ExitStatus.ERROR_TIMEOUT\n env.log_error(f'Request timed out ({parsed_args.timeout}s).')\n except requests.TooManyRedirects:\n exit_status = ExitStatus.ERROR_TOO_MANY_REDIRECTS\n env.log_error(\n f'Too many redirects'\n f' (--max-redirects={parsed_args.max_redirects}).'\n )\n except Exception as e:\n # TODO: Further distinction between expected and unexpected errors.\n msg = str(e)\n if hasattr(e, 'request'):\n request = e.request\n if hasattr(request, 'url'):\n msg = (\n f'{msg} while doing a {request.method}'\n f' request to URL: {request.url}'\n )\n env.log_error(f'{type(e).__name__}: {msg}')\n if include_traceback:\n raise\n exit_status = ExitStatus.ERROR\n\n return exit_status", "has_branch": true, "total_branches": 2} {"prompt_id": 119, "project": "httpie", "module": "httpie.core", "class": "", "method": "get_output_options", "focal_method_txt": "def get_output_options(\n args: argparse.Namespace,\n message: Union[requests.PreparedRequest, requests.Response]\n) -> Tuple[bool, bool]:\n return {\n requests.PreparedRequest: (\n OUT_REQ_HEAD in args.output_options,\n OUT_REQ_BODY in args.output_options,\n ),\n requests.Response: (\n OUT_RESP_HEAD in args.output_options,\n OUT_RESP_BODY in args.output_options,\n ),\n }[type(message)]", "focal_method_lines": [111, 115], "in_stack": false, "globals": [], "type_context": "import argparse\nimport os\nimport platform\nimport sys\nfrom typing import List, Optional, Tuple, Union\nimport requests\nfrom pygments import __version__ as pygments_version\nfrom requests import __version__ as requests_version\nfrom httpie import __version__ as httpie_version\nfrom httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD\nfrom httpie.client import collect_messages\nfrom httpie.context import Environment\nfrom httpie.downloads import Downloader\nfrom httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.status import ExitStatus, http_status_to_exit_status\n\n\n\ndef get_output_options(\n args: argparse.Namespace,\n message: Union[requests.PreparedRequest, requests.Response]\n) -> Tuple[bool, bool]:\n return {\n requests.PreparedRequest: (\n OUT_REQ_HEAD in args.output_options,\n OUT_REQ_BODY in args.output_options,\n ),\n requests.Response: (\n OUT_RESP_HEAD in args.output_options,\n OUT_RESP_BODY in args.output_options,\n ),\n }[type(message)]", "has_branch": false, "total_branches": 0} {"prompt_id": 120, "project": "httpie", "module": "httpie.core", "class": "", "method": "program", "focal_method_txt": "def program(args: argparse.Namespace, env: Environment) -> ExitStatus:\n \"\"\"\n The main program without error handling.\n\n \"\"\"\n # TODO: Refactor and drastically simplify, especially so that the separator logic is elsewhere.\n exit_status = ExitStatus.SUCCESS\n downloader = None\n initial_request: Optional[requests.PreparedRequest] = None\n final_response: Optional[requests.Response] = None\n\n def separate():\n getattr(env.stdout, 'buffer', env.stdout).write(MESSAGE_SEPARATOR_BYTES)\n\n def request_body_read_callback(chunk: bytes):\n should_pipe_to_stdout = bool(\n # Request body output desired\n OUT_REQ_BODY in args.output_options\n # & not `.read()` already pre-request (e.g., for compression)\n and initial_request\n # & non-EOF chunk\n and chunk\n )\n if should_pipe_to_stdout:\n msg = requests.PreparedRequest()\n msg.is_body_upload_chunk = True\n msg.body = chunk\n msg.headers = initial_request.headers\n write_message(requests_message=msg, env=env, args=args, with_body=True, with_headers=False)\n\n try:\n if args.download:\n args.follow = True # --download implies --follow.\n downloader = Downloader(output_file=args.output_file, progress_file=env.stderr, resume=args.download_resume)\n downloader.pre_request(args.headers)\n messages = collect_messages(args=args, config_dir=env.config.directory,\n request_body_read_callback=request_body_read_callback)\n force_separator = False\n prev_with_body = False\n\n # Process messages as they’re generated\n for message in messages:\n is_request = isinstance(message, requests.PreparedRequest)\n with_headers, with_body = get_output_options(args=args, message=message)\n do_write_body = with_body\n if prev_with_body and (with_headers or with_body) and (force_separator or not env.stdout_isatty):\n # Separate after a previous message with body, if needed. See test_tokens.py.\n separate()\n force_separator = False\n if is_request:\n if not initial_request:\n initial_request = message\n is_streamed_upload = not isinstance(message.body, (str, bytes))\n if with_body:\n do_write_body = not is_streamed_upload\n force_separator = is_streamed_upload and env.stdout_isatty\n else:\n final_response = message\n if args.check_status or downloader:\n exit_status = http_status_to_exit_status(http_status=message.status_code, follow=args.follow)\n if exit_status != ExitStatus.SUCCESS and (not env.stdout_isatty or args.quiet):\n env.log_error(f'HTTP {message.raw.status} {message.raw.reason}', level='warning')\n write_message(requests_message=message, env=env, args=args, with_headers=with_headers,\n with_body=do_write_body)\n prev_with_body = with_body\n\n # Cleanup\n if force_separator:\n separate()\n if downloader and exit_status == ExitStatus.SUCCESS:\n # Last response body download.\n download_stream, download_to = downloader.start(\n initial_url=initial_request.url,\n final_response=final_response,\n )\n write_stream(stream=download_stream, outfile=download_to, flush=False)\n downloader.finish()\n if downloader.interrupted:\n exit_status = ExitStatus.ERROR\n env.log_error(\n 'Incomplete download: size=%d; downloaded=%d' % (\n downloader.status.total_size,\n downloader.status.downloaded\n ))\n return exit_status\n\n finally:\n if downloader and not downloader.finished:\n downloader.failed()\n if not isinstance(args, list) and args.output_file and args.output_file_specified:\n args.output_file.close()", "focal_method_lines": [127, 217], "in_stack": false, "globals": [], "type_context": "import argparse\nimport os\nimport platform\nimport sys\nfrom typing import List, Optional, Tuple, Union\nimport requests\nfrom pygments import __version__ as pygments_version\nfrom requests import __version__ as requests_version\nfrom httpie import __version__ as httpie_version\nfrom httpie.cli.constants import OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD\nfrom httpie.client import collect_messages\nfrom httpie.context import Environment\nfrom httpie.downloads import Downloader\nfrom httpie.output.writer import write_message, write_stream, MESSAGE_SEPARATOR_BYTES\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.status import ExitStatus, http_status_to_exit_status\n\n\n\ndef program(args: argparse.Namespace, env: Environment) -> ExitStatus:\n \"\"\"\n The main program without error handling.\n\n \"\"\"\n # TODO: Refactor and drastically simplify, especially so that the separator logic is elsewhere.\n exit_status = ExitStatus.SUCCESS\n downloader = None\n initial_request: Optional[requests.PreparedRequest] = None\n final_response: Optional[requests.Response] = None\n\n def separate():\n getattr(env.stdout, 'buffer', env.stdout).write(MESSAGE_SEPARATOR_BYTES)\n\n def request_body_read_callback(chunk: bytes):\n should_pipe_to_stdout = bool(\n # Request body output desired\n OUT_REQ_BODY in args.output_options\n # & not `.read()` already pre-request (e.g., for compression)\n and initial_request\n # & non-EOF chunk\n and chunk\n )\n if should_pipe_to_stdout:\n msg = requests.PreparedRequest()\n msg.is_body_upload_chunk = True\n msg.body = chunk\n msg.headers = initial_request.headers\n write_message(requests_message=msg, env=env, args=args, with_body=True, with_headers=False)\n\n try:\n if args.download:\n args.follow = True # --download implies --follow.\n downloader = Downloader(output_file=args.output_file, progress_file=env.stderr, resume=args.download_resume)\n downloader.pre_request(args.headers)\n messages = collect_messages(args=args, config_dir=env.config.directory,\n request_body_read_callback=request_body_read_callback)\n force_separator = False\n prev_with_body = False\n\n # Process messages as they’re generated\n for message in messages:\n is_request = isinstance(message, requests.PreparedRequest)\n with_headers, with_body = get_output_options(args=args, message=message)\n do_write_body = with_body\n if prev_with_body and (with_headers or with_body) and (force_separator or not env.stdout_isatty):\n # Separate after a previous message with body, if needed. See test_tokens.py.\n separate()\n force_separator = False\n if is_request:\n if not initial_request:\n initial_request = message\n is_streamed_upload = not isinstance(message.body, (str, bytes))\n if with_body:\n do_write_body = not is_streamed_upload\n force_separator = is_streamed_upload and env.stdout_isatty\n else:\n final_response = message\n if args.check_status or downloader:\n exit_status = http_status_to_exit_status(http_status=message.status_code, follow=args.follow)\n if exit_status != ExitStatus.SUCCESS and (not env.stdout_isatty or args.quiet):\n env.log_error(f'HTTP {message.raw.status} {message.raw.reason}', level='warning')\n write_message(requests_message=message, env=env, args=args, with_headers=with_headers,\n with_body=do_write_body)\n prev_with_body = with_body\n\n # Cleanup\n if force_separator:\n separate()\n if downloader and exit_status == ExitStatus.SUCCESS:\n # Last response body download.\n download_stream, download_to = downloader.start(\n initial_url=initial_request.url,\n final_response=final_response,\n )\n write_stream(stream=download_stream, outfile=download_to, flush=False)\n downloader.finish()\n if downloader.interrupted:\n exit_status = ExitStatus.ERROR\n env.log_error(\n 'Incomplete download: size=%d; downloaded=%d' % (\n downloader.status.total_size,\n downloader.status.downloaded\n ))\n return exit_status\n\n finally:\n if downloader and not downloader.finished:\n downloader.failed()\n if not isinstance(args, list) and args.output_file and args.output_file_specified:\n args.output_file.close()", "has_branch": true, "total_branches": 2} {"prompt_id": 121, "project": "httpie", "module": "httpie.models", "class": "HTTPResponse", "method": "iter_lines", "focal_method_txt": " def iter_lines(self, chunk_size):\n return ((line, b'\\n') for line in self._orig.iter_lines(chunk_size))", "focal_method_lines": [48, 49], "in_stack": false, "globals": [], "type_context": "from typing import Iterable, Optional\nfrom urllib.parse import urlsplit\n\n\n\nclass HTTPResponse(HTTPMessage):\n\n def iter_lines(self, chunk_size):\n return ((line, b'\\n') for line in self._orig.iter_lines(chunk_size))", "has_branch": false, "total_branches": 0} {"prompt_id": 122, "project": "httpie", "module": "httpie.models", "class": "HTTPRequest", "method": "iter_body", "focal_method_txt": " def iter_body(self, chunk_size):\n yield self.body", "focal_method_lines": [91, 92], "in_stack": false, "globals": [], "type_context": "from typing import Iterable, Optional\nfrom urllib.parse import urlsplit\n\n\n\nclass HTTPRequest(HTTPMessage):\n\n def iter_body(self, chunk_size):\n yield self.body", "has_branch": false, "total_branches": 0} {"prompt_id": 123, "project": "httpie", "module": "httpie.models", "class": "HTTPRequest", "method": "iter_lines", "focal_method_txt": " def iter_lines(self, chunk_size):\n yield self.body, b''", "focal_method_lines": [94, 95], "in_stack": false, "globals": [], "type_context": "from typing import Iterable, Optional\nfrom urllib.parse import urlsplit\n\n\n\nclass HTTPRequest(HTTPMessage):\n\n def iter_lines(self, chunk_size):\n yield self.body, b''", "has_branch": false, "total_branches": 0} {"prompt_id": 124, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "", "method": "get_lexer", "focal_method_txt": "def get_lexer(\n mime: str,\n explicit_json=False,\n body=''\n) -> Optional[Type[Lexer]]:\n # Build candidate mime type and lexer names.\n mime_types, lexer_names = [mime], []\n type_, subtype = mime.split('/', 1)\n if '+' not in subtype:\n lexer_names.append(subtype)\n else:\n subtype_name, subtype_suffix = subtype.split('+', 1)\n lexer_names.extend([subtype_name, subtype_suffix])\n mime_types.extend([\n '%s/%s' % (type_, subtype_name),\n '%s/%s' % (type_, subtype_suffix)\n ])\n\n # As a last resort, if no lexer feels responsible, and\n # the subtype contains 'json', take the JSON lexer\n if 'json' in subtype:\n lexer_names.append('json')\n\n # Try to resolve the right lexer.\n lexer = None\n for mime_type in mime_types:\n try:\n lexer = pygments.lexers.get_lexer_for_mimetype(mime_type)\n break\n except ClassNotFound:\n pass\n else:\n for name in lexer_names:\n try:\n lexer = pygments.lexers.get_lexer_by_name(name)\n except ClassNotFound:\n pass\n\n if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)):\n # JSON response with an incorrect Content-Type?\n try:\n json.loads(body) # FIXME: the body also gets parsed in json.py\n except ValueError:\n pass # Nope\n else:\n lexer = pygments.lexers.get_lexer_by_name('json')\n\n return lexer", "focal_method_lines": [108, 155], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\ndef get_lexer(\n mime: str,\n explicit_json=False,\n body=''\n) -> Optional[Type[Lexer]]:\n # Build candidate mime type and lexer names.\n mime_types, lexer_names = [mime], []\n type_, subtype = mime.split('/', 1)\n if '+' not in subtype:\n lexer_names.append(subtype)\n else:\n subtype_name, subtype_suffix = subtype.split('+', 1)\n lexer_names.extend([subtype_name, subtype_suffix])\n mime_types.extend([\n '%s/%s' % (type_, subtype_name),\n '%s/%s' % (type_, subtype_suffix)\n ])\n\n # As a last resort, if no lexer feels responsible, and\n # the subtype contains 'json', take the JSON lexer\n if 'json' in subtype:\n lexer_names.append('json')\n\n # Try to resolve the right lexer.\n lexer = None\n for mime_type in mime_types:\n try:\n lexer = pygments.lexers.get_lexer_for_mimetype(mime_type)\n break\n except ClassNotFound:\n pass\n else:\n for name in lexer_names:\n try:\n lexer = pygments.lexers.get_lexer_by_name(name)\n except ClassNotFound:\n pass\n\n if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)):\n # JSON response with an incorrect Content-Type?\n try:\n json.loads(body) # FIXME: the body also gets parsed in json.py\n except ValueError:\n pass # Nope\n else:\n lexer = pygments.lexers.get_lexer_by_name('json')\n\n return lexer", "has_branch": true, "total_branches": 2} {"prompt_id": 125, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "ColorFormatter", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer", "focal_method_lines": [45, 71], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\nclass ColorFormatter(FormatterPlugin):\n\n group_name = 'colors'\n\n def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer", "has_branch": true, "total_branches": 2} {"prompt_id": 126, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "ColorFormatter", "method": "format_headers", "focal_method_txt": " def format_headers(self, headers: str) -> str:\n return pygments.highlight(\n code=headers,\n lexer=self.http_lexer,\n formatter=self.formatter,\n ).strip()", "focal_method_lines": [73, 74], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\nclass ColorFormatter(FormatterPlugin):\n\n group_name = 'colors'\n\n def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer\n\n def format_headers(self, headers: str) -> str:\n return pygments.highlight(\n code=headers,\n lexer=self.http_lexer,\n formatter=self.formatter,\n ).strip()", "has_branch": false, "total_branches": 0} {"prompt_id": 127, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "ColorFormatter", "method": "format_body", "focal_method_txt": " def format_body(self, body: str, mime: str) -> str:\n lexer = self.get_lexer_for_body(mime, body)\n if lexer:\n body = pygments.highlight(\n code=body,\n lexer=lexer,\n formatter=self.formatter,\n )\n return body", "focal_method_lines": [80, 88], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\nclass ColorFormatter(FormatterPlugin):\n\n group_name = 'colors'\n\n def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer\n\n def format_body(self, body: str, mime: str) -> str:\n lexer = self.get_lexer_for_body(mime, body)\n if lexer:\n body = pygments.highlight(\n code=body,\n lexer=lexer,\n formatter=self.formatter,\n )\n return body", "has_branch": true, "total_branches": 2} {"prompt_id": 128, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "ColorFormatter", "method": "get_lexer_for_body", "focal_method_txt": " def get_lexer_for_body(\n self, mime: str,\n body: str\n ) -> Optional[Type[Lexer]]:\n return get_lexer(\n mime=mime,\n explicit_json=self.explicit_json,\n body=body,\n )", "focal_method_lines": [90, 94], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\nclass ColorFormatter(FormatterPlugin):\n\n group_name = 'colors'\n\n def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer\n\n def get_lexer_for_body(\n self, mime: str,\n body: str\n ) -> Optional[Type[Lexer]]:\n return get_lexer(\n mime=mime,\n explicit_json=self.explicit_json,\n body=body,\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 129, "project": "httpie", "module": "httpie.output.formatters.colors", "class": "ColorFormatter", "method": "get_style_class", "focal_method_txt": " @staticmethod\n def get_style_class(color_scheme: str) -> Type[pygments.style.Style]:\n try:\n return pygments.styles.get_style_by_name(color_scheme)\n except ClassNotFound:\n return Solarized256Style", "focal_method_lines": [101, 105], "in_stack": false, "globals": ["AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES"], "type_context": "import json\nfrom typing import Optional, Type\nimport pygments.lexer\nimport pygments.lexers\nimport pygments.style\nimport pygments.styles\nimport pygments.token\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.special import TextLexer\nfrom pygments.lexers.text import HttpLexer as PygmentsHttpLexer\nfrom pygments.util import ClassNotFound\nfrom httpie.compat import is_windows\nfrom httpie.context import Environment\nfrom httpie.plugins import FormatterPlugin\n\nAUTO_STYLE = 'auto'\nDEFAULT_STYLE = AUTO_STYLE\nSOLARIZED_STYLE = 'solarized'\nAVAILABLE_STYLES = set(pygments.styles.get_all_styles())\n\nclass ColorFormatter(FormatterPlugin):\n\n group_name = 'colors'\n\n def __init__(\n self,\n env: Environment,\n explicit_json=False,\n color_scheme=DEFAULT_STYLE,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n if not env.colors:\n self.enabled = False\n return\n\n use_auto_style = color_scheme == AUTO_STYLE\n has_256_colors = env.colors == 256\n if use_auto_style or not has_256_colors:\n http_lexer = PygmentsHttpLexer()\n formatter = TerminalFormatter()\n else:\n http_lexer = SimplifiedHTTPLexer()\n formatter = Terminal256Formatter(\n style=self.get_style_class(color_scheme)\n )\n\n self.explicit_json = explicit_json # --json\n self.formatter = formatter\n self.http_lexer = http_lexer\n\n @staticmethod\n def get_style_class(color_scheme: str) -> Type[pygments.style.Style]:\n try:\n return pygments.styles.get_style_by_name(color_scheme)\n except ClassNotFound:\n return Solarized256Style", "has_branch": false, "total_branches": 0} {"prompt_id": 130, "project": "httpie", "module": "httpie.output.formatters.headers", "class": "HeadersFormatter", "method": "__init__", "focal_method_txt": " def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['headers']['sort']", "focal_method_lines": [5, 7], "in_stack": false, "globals": [], "type_context": "from httpie.plugins import FormatterPlugin\n\n\n\nclass HeadersFormatter(FormatterPlugin):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['headers']['sort']", "has_branch": false, "total_branches": 0} {"prompt_id": 131, "project": "httpie", "module": "httpie.output.formatters.headers", "class": "HeadersFormatter", "method": "format_headers", "focal_method_txt": " def format_headers(self, headers: str) -> str:\n \"\"\"\n Sorts headers by name while retaining relative\n order of multiple headers with the same name.\n\n \"\"\"\n lines = headers.splitlines()\n headers = sorted(lines[1:], key=lambda h: h.split(':')[0])\n return '\\r\\n'.join(lines[:1] + headers)", "focal_method_lines": [9, 17], "in_stack": false, "globals": [], "type_context": "from httpie.plugins import FormatterPlugin\n\n\n\nclass HeadersFormatter(FormatterPlugin):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['headers']['sort']\n\n def format_headers(self, headers: str) -> str:\n \"\"\"\n Sorts headers by name while retaining relative\n order of multiple headers with the same name.\n\n \"\"\"\n lines = headers.splitlines()\n headers = sorted(lines[1:], key=lambda h: h.split(':')[0])\n return '\\r\\n'.join(lines[:1] + headers)", "has_branch": false, "total_branches": 0} {"prompt_id": 132, "project": "httpie", "module": "httpie.output.formatters.json", "class": "JSONFormatter", "method": "__init__", "focal_method_txt": " def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['json']['format']", "focal_method_lines": [8, 10], "in_stack": false, "globals": [], "type_context": "import json\nfrom httpie.plugins import FormatterPlugin\n\n\n\nclass JSONFormatter(FormatterPlugin):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['json']['format']", "has_branch": false, "total_branches": 0} {"prompt_id": 133, "project": "httpie", "module": "httpie.output.formatters.json", "class": "JSONFormatter", "method": "format_body", "focal_method_txt": " def format_body(self, body: str, mime: str) -> str:\n maybe_json = [\n 'json',\n 'javascript',\n 'text',\n ]\n if (self.kwargs['explicit_json']\n or any(token in mime for token in maybe_json)):\n try:\n obj = json.loads(body)\n except ValueError:\n pass # Invalid JSON, ignore.\n else:\n # Indent, sort keys by name, and avoid\n # unicode escapes to improve readability.\n body = json.dumps(\n obj=obj,\n sort_keys=self.format_options['json']['sort_keys'],\n ensure_ascii=False,\n indent=self.format_options['json']['indent']\n )\n return body", "focal_method_lines": [12, 33], "in_stack": false, "globals": [], "type_context": "import json\nfrom httpie.plugins import FormatterPlugin\n\n\n\nclass JSONFormatter(FormatterPlugin):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.enabled = self.format_options['json']['format']\n\n def format_body(self, body: str, mime: str) -> str:\n maybe_json = [\n 'json',\n 'javascript',\n 'text',\n ]\n if (self.kwargs['explicit_json']\n or any(token in mime for token in maybe_json)):\n try:\n obj = json.loads(body)\n except ValueError:\n pass # Invalid JSON, ignore.\n else:\n # Indent, sort keys by name, and avoid\n # unicode escapes to improve readability.\n body = json.dumps(\n obj=obj,\n sort_keys=self.format_options['json']['sort_keys'],\n ensure_ascii=False,\n indent=self.format_options['json']['indent']\n )\n return body", "has_branch": true, "total_branches": 2} {"prompt_id": 134, "project": "httpie", "module": "httpie.output.processing", "class": "Conversion", "method": "get_converter", "focal_method_txt": " @staticmethod\n def get_converter(mime: str) -> Optional[ConverterPlugin]:\n if is_valid_mime(mime):\n for converter_class in plugin_manager.get_converters():\n if converter_class.supports(mime):\n return converter_class(mime)", "focal_method_lines": [18, 22], "in_stack": false, "globals": ["MIME_RE"], "type_context": "import re\nfrom typing import Optional, List\nfrom httpie.plugins import ConverterPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.context import Environment\n\nMIME_RE = re.compile(r'^[^/]+/[^/]+$')\n\nclass Conversion:\n\n @staticmethod\n def get_converter(mime: str) -> Optional[ConverterPlugin]:\n if is_valid_mime(mime):\n for converter_class in plugin_manager.get_converters():\n if converter_class.supports(mime):\n return converter_class(mime)", "has_branch": true, "total_branches": 2} {"prompt_id": 135, "project": "httpie", "module": "httpie.output.processing", "class": "Formatting", "method": "__init__", "focal_method_txt": " def __init__(self, groups: List[str], env=Environment(), **kwargs):\n \"\"\"\n :param groups: names of processor groups to be applied\n :param env: Environment\n :param kwargs: additional keyword arguments for processors\n\n \"\"\"\n available_plugins = plugin_manager.get_formatters_grouped()\n self.enabled_plugins = []\n for group in groups:\n for cls in available_plugins[group]:\n p = cls(env=env, **kwargs)\n if p.enabled:\n self.enabled_plugins.append(p)", "focal_method_lines": [28, 41], "in_stack": false, "globals": ["MIME_RE"], "type_context": "import re\nfrom typing import Optional, List\nfrom httpie.plugins import ConverterPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.context import Environment\n\nMIME_RE = re.compile(r'^[^/]+/[^/]+$')\n\nclass Formatting:\n\n def __init__(self, groups: List[str], env=Environment(), **kwargs):\n \"\"\"\n :param groups: names of processor groups to be applied\n :param env: Environment\n :param kwargs: additional keyword arguments for processors\n\n \"\"\"\n available_plugins = plugin_manager.get_formatters_grouped()\n self.enabled_plugins = []\n for group in groups:\n for cls in available_plugins[group]:\n p = cls(env=env, **kwargs)\n if p.enabled:\n self.enabled_plugins.append(p)", "has_branch": true, "total_branches": 2} {"prompt_id": 136, "project": "httpie", "module": "httpie.output.processing", "class": "Formatting", "method": "format_headers", "focal_method_txt": " def format_headers(self, headers: str) -> str:\n for p in self.enabled_plugins:\n headers = p.format_headers(headers)\n return headers", "focal_method_lines": [43, 46], "in_stack": false, "globals": ["MIME_RE"], "type_context": "import re\nfrom typing import Optional, List\nfrom httpie.plugins import ConverterPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.context import Environment\n\nMIME_RE = re.compile(r'^[^/]+/[^/]+$')\n\nclass Formatting:\n\n def __init__(self, groups: List[str], env=Environment(), **kwargs):\n \"\"\"\n :param groups: names of processor groups to be applied\n :param env: Environment\n :param kwargs: additional keyword arguments for processors\n\n \"\"\"\n available_plugins = plugin_manager.get_formatters_grouped()\n self.enabled_plugins = []\n for group in groups:\n for cls in available_plugins[group]:\n p = cls(env=env, **kwargs)\n if p.enabled:\n self.enabled_plugins.append(p)\n\n def format_headers(self, headers: str) -> str:\n for p in self.enabled_plugins:\n headers = p.format_headers(headers)\n return headers", "has_branch": true, "total_branches": 2} {"prompt_id": 137, "project": "httpie", "module": "httpie.output.processing", "class": "Formatting", "method": "format_body", "focal_method_txt": " def format_body(self, content: str, mime: str) -> str:\n if is_valid_mime(mime):\n for p in self.enabled_plugins:\n content = p.format_body(content, mime)\n return content", "focal_method_lines": [48, 52], "in_stack": false, "globals": ["MIME_RE"], "type_context": "import re\nfrom typing import Optional, List\nfrom httpie.plugins import ConverterPlugin\nfrom httpie.plugins.registry import plugin_manager\nfrom httpie.context import Environment\n\nMIME_RE = re.compile(r'^[^/]+/[^/]+$')\n\nclass Formatting:\n\n def __init__(self, groups: List[str], env=Environment(), **kwargs):\n \"\"\"\n :param groups: names of processor groups to be applied\n :param env: Environment\n :param kwargs: additional keyword arguments for processors\n\n \"\"\"\n available_plugins = plugin_manager.get_formatters_grouped()\n self.enabled_plugins = []\n for group in groups:\n for cls in available_plugins[group]:\n p = cls(env=env, **kwargs)\n if p.enabled:\n self.enabled_plugins.append(p)\n\n def format_body(self, content: str, mime: str) -> str:\n if is_valid_mime(mime):\n for p in self.enabled_plugins:\n content = p.format_body(content, mime)\n return content", "has_branch": true, "total_branches": 2} {"prompt_id": 138, "project": "httpie", "module": "httpie.output.streams", "class": "BaseStream", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n msg: HTTPMessage,\n with_headers=True,\n with_body=True,\n on_body_chunk_downloaded: Callable[[bytes], None] = None\n ):\n \"\"\"\n :param msg: a :class:`models.HTTPMessage` subclass\n :param with_headers: if `True`, headers will be included\n :param with_body: if `True`, body will be included\n\n \"\"\"\n assert with_headers or with_body\n self.msg = msg\n self.with_headers = with_headers\n self.with_body = with_body\n self.on_body_chunk_downloaded = on_body_chunk_downloaded", "focal_method_lines": [29, 46], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass BaseStream:\n\n def __init__(\n self,\n msg: HTTPMessage,\n with_headers=True,\n with_body=True,\n on_body_chunk_downloaded: Callable[[bytes], None] = None\n ):\n \"\"\"\n :param msg: a :class:`models.HTTPMessage` subclass\n :param with_headers: if `True`, headers will be included\n :param with_body: if `True`, body will be included\n\n \"\"\"\n assert with_headers or with_body\n self.msg = msg\n self.with_headers = with_headers\n self.with_body = with_body\n self.on_body_chunk_downloaded = on_body_chunk_downloaded", "has_branch": false, "total_branches": 0} {"prompt_id": 139, "project": "httpie", "module": "httpie.output.streams", "class": "BaseStream", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> Iterable[bytes]:\n \"\"\"Return an iterator over `self.msg`.\"\"\"\n if self.with_headers:\n yield self.get_headers()\n yield b'\\r\\n\\r\\n'\n\n if self.with_body:\n try:\n for chunk in self.iter_body():\n yield chunk\n if self.on_body_chunk_downloaded:\n self.on_body_chunk_downloaded(chunk)\n except DataSuppressedError as e:\n if self.with_headers:\n yield b'\\n'\n yield e.message", "focal_method_lines": [56, 71], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass BaseStream:\n\n def __init__(\n self,\n msg: HTTPMessage,\n with_headers=True,\n with_body=True,\n on_body_chunk_downloaded: Callable[[bytes], None] = None\n ):\n \"\"\"\n :param msg: a :class:`models.HTTPMessage` subclass\n :param with_headers: if `True`, headers will be included\n :param with_body: if `True`, body will be included\n\n \"\"\"\n assert with_headers or with_body\n self.msg = msg\n self.with_headers = with_headers\n self.with_body = with_body\n self.on_body_chunk_downloaded = on_body_chunk_downloaded\n\n def __iter__(self) -> Iterable[bytes]:\n \"\"\"Return an iterator over `self.msg`.\"\"\"\n if self.with_headers:\n yield self.get_headers()\n yield b'\\r\\n\\r\\n'\n\n if self.with_body:\n try:\n for chunk in self.iter_body():\n yield chunk\n if self.on_body_chunk_downloaded:\n self.on_body_chunk_downloaded(chunk)\n except DataSuppressedError as e:\n if self.with_headers:\n yield b'\\n'\n yield e.message", "has_branch": true, "total_branches": 2} {"prompt_id": 140, "project": "httpie", "module": "httpie.output.streams", "class": "RawStream", "method": "__init__", "focal_method_txt": " def __init__(self, chunk_size=CHUNK_SIZE, **kwargs):\n super().__init__(**kwargs)\n self.chunk_size = chunk_size", "focal_method_lines": [80, 82], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass RawStream(BaseStream):\n\n CHUNK_SIZE = 1024 * 100\n\n CHUNK_SIZE_BY_LINE = 1\n\n def __init__(self, chunk_size=CHUNK_SIZE, **kwargs):\n super().__init__(**kwargs)\n self.chunk_size = chunk_size", "has_branch": false, "total_branches": 0} {"prompt_id": 141, "project": "httpie", "module": "httpie.output.streams", "class": "RawStream", "method": "iter_body", "focal_method_txt": " def iter_body(self) -> Iterable[bytes]:\n return self.msg.iter_body(self.chunk_size)", "focal_method_lines": [84, 85], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass RawStream(BaseStream):\n\n CHUNK_SIZE = 1024 * 100\n\n CHUNK_SIZE_BY_LINE = 1\n\n def __init__(self, chunk_size=CHUNK_SIZE, **kwargs):\n super().__init__(**kwargs)\n self.chunk_size = chunk_size\n\n def iter_body(self) -> Iterable[bytes]:\n return self.msg.iter_body(self.chunk_size)", "has_branch": false, "total_branches": 0} {"prompt_id": 142, "project": "httpie", "module": "httpie.output.streams", "class": "EncodedStream", "method": "__init__", "focal_method_txt": " def __init__(self, env=Environment(), **kwargs):\n super().__init__(**kwargs)\n if env.stdout_isatty:\n # Use the encoding supported by the terminal.\n output_encoding = env.stdout_encoding\n else:\n # Preserve the message encoding.\n output_encoding = self.msg.encoding\n # Default to utf8 when unsure.\n self.output_encoding = output_encoding or 'utf8'", "focal_method_lines": [98, 107], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass EncodedStream(BaseStream):\n\n CHUNK_SIZE = 1\n\n def __init__(self, env=Environment(), **kwargs):\n super().__init__(**kwargs)\n if env.stdout_isatty:\n # Use the encoding supported by the terminal.\n output_encoding = env.stdout_encoding\n else:\n # Preserve the message encoding.\n output_encoding = self.msg.encoding\n # Default to utf8 when unsure.\n self.output_encoding = output_encoding or 'utf8'", "has_branch": true, "total_branches": 2} {"prompt_id": 143, "project": "httpie", "module": "httpie.output.streams", "class": "EncodedStream", "method": "iter_body", "focal_method_txt": " def iter_body(self) -> Iterable[bytes]:\n for line, lf in self.msg.iter_lines(self.CHUNK_SIZE):\n if b'\\0' in line:\n raise BinarySuppressedError()\n yield line.decode(self.msg.encoding) \\\n .encode(self.output_encoding, 'replace') + lf", "focal_method_lines": [109, 113], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass EncodedStream(BaseStream):\n\n CHUNK_SIZE = 1\n\n def __init__(self, env=Environment(), **kwargs):\n super().__init__(**kwargs)\n if env.stdout_isatty:\n # Use the encoding supported by the terminal.\n output_encoding = env.stdout_encoding\n else:\n # Preserve the message encoding.\n output_encoding = self.msg.encoding\n # Default to utf8 when unsure.\n self.output_encoding = output_encoding or 'utf8'\n\n def iter_body(self) -> Iterable[bytes]:\n for line, lf in self.msg.iter_lines(self.CHUNK_SIZE):\n if b'\\0' in line:\n raise BinarySuppressedError()\n yield line.decode(self.msg.encoding) \\\n .encode(self.output_encoding, 'replace') + lf", "has_branch": true, "total_branches": 2} {"prompt_id": 144, "project": "httpie", "module": "httpie.output.streams", "class": "PrettyStream", "method": "__init__", "focal_method_txt": " def __init__(\n self, conversion: Conversion,\n formatting: Formatting,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.formatting = formatting\n self.conversion = conversion\n self.mime = self.msg.content_type.split(';')[0]", "focal_method_lines": [128, 136], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass PrettyStream(EncodedStream):\n\n CHUNK_SIZE = 1\n\n def __init__(\n self, conversion: Conversion,\n formatting: Formatting,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.formatting = formatting\n self.conversion = conversion\n self.mime = self.msg.content_type.split(';')[0]", "has_branch": false, "total_branches": 0} {"prompt_id": 145, "project": "httpie", "module": "httpie.output.streams", "class": "PrettyStream", "method": "get_headers", "focal_method_txt": " def get_headers(self) -> bytes:\n return self.formatting.format_headers(\n self.msg.headers).encode(self.output_encoding)", "focal_method_lines": [138, 139], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass PrettyStream(EncodedStream):\n\n CHUNK_SIZE = 1\n\n def __init__(\n self, conversion: Conversion,\n formatting: Formatting,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.formatting = formatting\n self.conversion = conversion\n self.mime = self.msg.content_type.split(';')[0]\n\n def get_headers(self) -> bytes:\n return self.formatting.format_headers(\n self.msg.headers).encode(self.output_encoding)", "has_branch": false, "total_branches": 0} {"prompt_id": 146, "project": "httpie", "module": "httpie.output.streams", "class": "PrettyStream", "method": "iter_body", "focal_method_txt": " def iter_body(self) -> Iterable[bytes]:\n first_chunk = True\n iter_lines = self.msg.iter_lines(self.CHUNK_SIZE)\n for line, lf in iter_lines:\n if b'\\0' in line:\n if first_chunk:\n converter = self.conversion.get_converter(self.mime)\n if converter:\n body = bytearray()\n # noinspection PyAssignmentToLoopOrWithParameter\n for line, lf in chain([(line, lf)], iter_lines):\n body.extend(line)\n body.extend(lf)\n self.mime, body = converter.convert(body)\n assert isinstance(body, str)\n yield self.process_body(body)\n return\n raise BinarySuppressedError()\n yield self.process_body(line) + lf\n first_chunk = False", "focal_method_lines": [142, 161], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass PrettyStream(EncodedStream):\n\n CHUNK_SIZE = 1\n\n def __init__(\n self, conversion: Conversion,\n formatting: Formatting,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.formatting = formatting\n self.conversion = conversion\n self.mime = self.msg.content_type.split(';')[0]\n\n def iter_body(self) -> Iterable[bytes]:\n first_chunk = True\n iter_lines = self.msg.iter_lines(self.CHUNK_SIZE)\n for line, lf in iter_lines:\n if b'\\0' in line:\n if first_chunk:\n converter = self.conversion.get_converter(self.mime)\n if converter:\n body = bytearray()\n # noinspection PyAssignmentToLoopOrWithParameter\n for line, lf in chain([(line, lf)], iter_lines):\n body.extend(line)\n body.extend(lf)\n self.mime, body = converter.convert(body)\n assert isinstance(body, str)\n yield self.process_body(body)\n return\n raise BinarySuppressedError()\n yield self.process_body(line) + lf\n first_chunk = False", "has_branch": true, "total_branches": 2} {"prompt_id": 147, "project": "httpie", "module": "httpie.output.streams", "class": "PrettyStream", "method": "process_body", "focal_method_txt": " def process_body(self, chunk: Union[str, bytes]) -> bytes:\n if not isinstance(chunk, str):\n # Text when a converter has been used,\n # otherwise it will always be bytes.\n chunk = chunk.decode(self.msg.encoding, 'replace')\n chunk = self.formatting.format_body(content=chunk, mime=self.mime)\n return chunk.encode(self.output_encoding, 'replace')", "focal_method_lines": [163, 169], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass PrettyStream(EncodedStream):\n\n CHUNK_SIZE = 1\n\n def __init__(\n self, conversion: Conversion,\n formatting: Formatting,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.formatting = formatting\n self.conversion = conversion\n self.mime = self.msg.content_type.split(';')[0]\n\n def process_body(self, chunk: Union[str, bytes]) -> bytes:\n if not isinstance(chunk, str):\n # Text when a converter has been used,\n # otherwise it will always be bytes.\n chunk = chunk.decode(self.msg.encoding, 'replace')\n chunk = self.formatting.format_body(content=chunk, mime=self.mime)\n return chunk.encode(self.output_encoding, 'replace')", "has_branch": true, "total_branches": 2} {"prompt_id": 148, "project": "httpie", "module": "httpie.output.streams", "class": "BufferedPrettyStream", "method": "iter_body", "focal_method_txt": " def iter_body(self) -> Iterable[bytes]:\n # Read the whole body before prettifying it,\n # but bail out immediately if the body is binary.\n converter = None\n body = bytearray()\n\n for chunk in self.msg.iter_body(self.CHUNK_SIZE):\n if not converter and b'\\0' in chunk:\n converter = self.conversion.get_converter(self.mime)\n if not converter:\n raise BinarySuppressedError()\n body.extend(chunk)\n\n if converter:\n self.mime, body = converter.convert(body)\n\n yield self.process_body(body)", "focal_method_lines": [182, 198], "in_stack": false, "globals": ["BINARY_SUPPRESSED_NOTICE"], "type_context": "from itertools import chain\nfrom typing import Callable, Iterable, Union\nfrom httpie.context import Environment\nfrom httpie.models import HTTPMessage\nfrom httpie.output.processing import Conversion, Formatting\n\nBINARY_SUPPRESSED_NOTICE = (\n b'\\n'\n b'+-----------------------------------------+\\n'\n b'| NOTE: binary data not shown in terminal |\\n'\n b'+-----------------------------------------+'\n)\n\nclass BufferedPrettyStream(PrettyStream):\n\n CHUNK_SIZE = 1024 * 10\n\n def iter_body(self) -> Iterable[bytes]:\n # Read the whole body before prettifying it,\n # but bail out immediately if the body is binary.\n converter = None\n body = bytearray()\n\n for chunk in self.msg.iter_body(self.CHUNK_SIZE):\n if not converter and b'\\0' in chunk:\n converter = self.conversion.get_converter(self.mime)\n if not converter:\n raise BinarySuppressedError()\n body.extend(chunk)\n\n if converter:\n self.mime, body = converter.convert(body)\n\n yield self.process_body(body)", "has_branch": true, "total_branches": 2} {"prompt_id": 149, "project": "httpie", "module": "httpie.output.writer", "class": "", "method": "write_message", "focal_method_txt": "def write_message(\n requests_message: Union[requests.PreparedRequest, requests.Response],\n env: Environment,\n args: argparse.Namespace,\n with_headers=False,\n with_body=False,\n):\n if not (with_body or with_headers):\n return\n write_stream_kwargs = {\n 'stream': build_output_stream_for_message(\n args=args,\n env=env,\n requests_message=requests_message,\n with_body=with_body,\n with_headers=with_headers,\n ),\n # NOTE: `env.stdout` will in fact be `stderr` with `--download`\n 'outfile': env.stdout,\n 'flush': env.stdout_isatty or args.stream\n }\n try:\n if env.is_windows and 'colors' in args.prettify:\n write_stream_with_colors_win_py3(**write_stream_kwargs)\n else:\n write_stream(**write_stream_kwargs)\n except IOError as e:\n show_traceback = args.debug or args.traceback\n if not show_traceback and e.errno == errno.EPIPE:\n # Ignore broken pipes unless --traceback.\n env.stderr.write('\\n')\n else:\n raise", "focal_method_lines": [18, 50], "in_stack": false, "globals": ["MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES"], "type_context": "import argparse\nimport errno\nfrom typing import IO, TextIO, Tuple, Type, Union\nimport requests\nfrom httpie.context import Environment\nfrom httpie.models import HTTPRequest, HTTPResponse\nfrom httpie.output.processing import Conversion, Formatting\nfrom httpie.output.streams import (\n BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream,\n)\n\nMESSAGE_SEPARATOR = '\\n\\n'\nMESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode()\n\ndef write_message(\n requests_message: Union[requests.PreparedRequest, requests.Response],\n env: Environment,\n args: argparse.Namespace,\n with_headers=False,\n with_body=False,\n):\n if not (with_body or with_headers):\n return\n write_stream_kwargs = {\n 'stream': build_output_stream_for_message(\n args=args,\n env=env,\n requests_message=requests_message,\n with_body=with_body,\n with_headers=with_headers,\n ),\n # NOTE: `env.stdout` will in fact be `stderr` with `--download`\n 'outfile': env.stdout,\n 'flush': env.stdout_isatty or args.stream\n }\n try:\n if env.is_windows and 'colors' in args.prettify:\n write_stream_with_colors_win_py3(**write_stream_kwargs)\n else:\n write_stream(**write_stream_kwargs)\n except IOError as e:\n show_traceback = args.debug or args.traceback\n if not show_traceback and e.errno == errno.EPIPE:\n # Ignore broken pipes unless --traceback.\n env.stderr.write('\\n')\n else:\n raise", "has_branch": true, "total_branches": 2} {"prompt_id": 150, "project": "httpie", "module": "httpie.output.writer", "class": "", "method": "write_stream", "focal_method_txt": "def write_stream(\n stream: BaseStream,\n outfile: Union[IO, TextIO],\n flush: bool\n):\n \"\"\"Write the output stream.\"\"\"\n try:\n # Writing bytes so we use the buffer interface (Python 3).\n buf = outfile.buffer\n except AttributeError:\n buf = outfile\n\n for chunk in stream:\n buf.write(chunk)\n if flush:\n outfile.flush()", "focal_method_lines": [53, 68], "in_stack": false, "globals": ["MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES"], "type_context": "import argparse\nimport errno\nfrom typing import IO, TextIO, Tuple, Type, Union\nimport requests\nfrom httpie.context import Environment\nfrom httpie.models import HTTPRequest, HTTPResponse\nfrom httpie.output.processing import Conversion, Formatting\nfrom httpie.output.streams import (\n BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream,\n)\n\nMESSAGE_SEPARATOR = '\\n\\n'\nMESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode()\n\ndef write_stream(\n stream: BaseStream,\n outfile: Union[IO, TextIO],\n flush: bool\n):\n \"\"\"Write the output stream.\"\"\"\n try:\n # Writing bytes so we use the buffer interface (Python 3).\n buf = outfile.buffer\n except AttributeError:\n buf = outfile\n\n for chunk in stream:\n buf.write(chunk)\n if flush:\n outfile.flush()", "has_branch": true, "total_branches": 2} {"prompt_id": 151, "project": "httpie", "module": "httpie.output.writer", "class": "", "method": "write_stream_with_colors_win_py3", "focal_method_txt": "def write_stream_with_colors_win_py3(\n stream: 'BaseStream',\n outfile: TextIO,\n flush: bool\n):\n \"\"\"Like `write`, but colorized chunks are written as text\n directly to `outfile` to ensure it gets processed by colorama.\n Applies only to Windows with Python 3 and colorized terminal output.\n\n \"\"\"\n color = b'\\x1b['\n encoding = outfile.encoding\n for chunk in stream:\n if color in chunk:\n outfile.write(chunk.decode(encoding))\n else:\n outfile.buffer.write(chunk)\n if flush:\n outfile.flush()", "focal_method_lines": [71, 89], "in_stack": false, "globals": ["MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES"], "type_context": "import argparse\nimport errno\nfrom typing import IO, TextIO, Tuple, Type, Union\nimport requests\nfrom httpie.context import Environment\nfrom httpie.models import HTTPRequest, HTTPResponse\nfrom httpie.output.processing import Conversion, Formatting\nfrom httpie.output.streams import (\n BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream,\n)\n\nMESSAGE_SEPARATOR = '\\n\\n'\nMESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode()\n\ndef write_stream_with_colors_win_py3(\n stream: 'BaseStream',\n outfile: TextIO,\n flush: bool\n):\n \"\"\"Like `write`, but colorized chunks are written as text\n directly to `outfile` to ensure it gets processed by colorama.\n Applies only to Windows with Python 3 and colorized terminal output.\n\n \"\"\"\n color = b'\\x1b['\n encoding = outfile.encoding\n for chunk in stream:\n if color in chunk:\n outfile.write(chunk.decode(encoding))\n else:\n outfile.buffer.write(chunk)\n if flush:\n outfile.flush()", "has_branch": true, "total_branches": 2} {"prompt_id": 152, "project": "httpie", "module": "httpie.output.writer", "class": "", "method": "build_output_stream_for_message", "focal_method_txt": "def build_output_stream_for_message(\n args: argparse.Namespace,\n env: Environment,\n requests_message: Union[requests.PreparedRequest, requests.Response],\n with_headers: bool,\n with_body: bool,\n):\n stream_class, stream_kwargs = get_stream_type_and_kwargs(\n env=env,\n args=args,\n )\n message_class = {\n requests.PreparedRequest: HTTPRequest,\n requests.Response: HTTPResponse,\n }[type(requests_message)]\n yield from stream_class(\n msg=message_class(requests_message),\n with_headers=with_headers,\n with_body=with_body,\n **stream_kwargs,\n )\n if (env.stdout_isatty and with_body\n and not getattr(requests_message, 'is_body_upload_chunk', False)):\n # Ensure a blank line after the response body.\n # For terminal output only.\n yield MESSAGE_SEPARATOR_BYTES", "focal_method_lines": [92, 117], "in_stack": false, "globals": ["MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES"], "type_context": "import argparse\nimport errno\nfrom typing import IO, TextIO, Tuple, Type, Union\nimport requests\nfrom httpie.context import Environment\nfrom httpie.models import HTTPRequest, HTTPResponse\nfrom httpie.output.processing import Conversion, Formatting\nfrom httpie.output.streams import (\n BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream,\n)\n\nMESSAGE_SEPARATOR = '\\n\\n'\nMESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode()\n\ndef build_output_stream_for_message(\n args: argparse.Namespace,\n env: Environment,\n requests_message: Union[requests.PreparedRequest, requests.Response],\n with_headers: bool,\n with_body: bool,\n):\n stream_class, stream_kwargs = get_stream_type_and_kwargs(\n env=env,\n args=args,\n )\n message_class = {\n requests.PreparedRequest: HTTPRequest,\n requests.Response: HTTPResponse,\n }[type(requests_message)]\n yield from stream_class(\n msg=message_class(requests_message),\n with_headers=with_headers,\n with_body=with_body,\n **stream_kwargs,\n )\n if (env.stdout_isatty and with_body\n and not getattr(requests_message, 'is_body_upload_chunk', False)):\n # Ensure a blank line after the response body.\n # For terminal output only.\n yield MESSAGE_SEPARATOR_BYTES", "has_branch": true, "total_branches": 2} {"prompt_id": 153, "project": "httpie", "module": "httpie.output.writer", "class": "", "method": "get_stream_type_and_kwargs", "focal_method_txt": "def get_stream_type_and_kwargs(\n env: Environment,\n args: argparse.Namespace\n) -> Tuple[Type['BaseStream'], dict]:\n \"\"\"Pick the right stream type and kwargs for it based on `env` and `args`.\n\n \"\"\"\n if not env.stdout_isatty and not args.prettify:\n stream_class = RawStream\n stream_kwargs = {\n 'chunk_size': (\n RawStream.CHUNK_SIZE_BY_LINE\n if args.stream\n else RawStream.CHUNK_SIZE\n )\n }\n elif args.prettify:\n stream_class = PrettyStream if args.stream else BufferedPrettyStream\n stream_kwargs = {\n 'env': env,\n 'conversion': Conversion(),\n 'formatting': Formatting(\n env=env,\n groups=args.prettify,\n color_scheme=args.style,\n explicit_json=args.json,\n format_options=args.format_options,\n )\n }\n else:\n stream_class = EncodedStream\n stream_kwargs = {\n 'env': env\n }\n\n return stream_class, stream_kwargs", "focal_method_lines": [120, 155], "in_stack": false, "globals": ["MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES"], "type_context": "import argparse\nimport errno\nfrom typing import IO, TextIO, Tuple, Type, Union\nimport requests\nfrom httpie.context import Environment\nfrom httpie.models import HTTPRequest, HTTPResponse\nfrom httpie.output.processing import Conversion, Formatting\nfrom httpie.output.streams import (\n BaseStream, BufferedPrettyStream, EncodedStream, PrettyStream, RawStream,\n)\n\nMESSAGE_SEPARATOR = '\\n\\n'\nMESSAGE_SEPARATOR_BYTES = MESSAGE_SEPARATOR.encode()\n\ndef get_stream_type_and_kwargs(\n env: Environment,\n args: argparse.Namespace\n) -> Tuple[Type['BaseStream'], dict]:\n \"\"\"Pick the right stream type and kwargs for it based on `env` and `args`.\n\n \"\"\"\n if not env.stdout_isatty and not args.prettify:\n stream_class = RawStream\n stream_kwargs = {\n 'chunk_size': (\n RawStream.CHUNK_SIZE_BY_LINE\n if args.stream\n else RawStream.CHUNK_SIZE\n )\n }\n elif args.prettify:\n stream_class = PrettyStream if args.stream else BufferedPrettyStream\n stream_kwargs = {\n 'env': env,\n 'conversion': Conversion(),\n 'formatting': Formatting(\n env=env,\n groups=args.prettify,\n color_scheme=args.style,\n explicit_json=args.json,\n format_options=args.format_options,\n )\n }\n else:\n stream_class = EncodedStream\n stream_kwargs = {\n 'env': env\n }\n\n return stream_class, stream_kwargs", "has_branch": true, "total_branches": 2} {"prompt_id": 154, "project": "httpie", "module": "httpie.plugins.base", "class": "AuthPlugin", "method": "get_auth", "focal_method_txt": " def get_auth(self, username=None, password=None):\n \"\"\"\n If `auth_parse` is set to `True`, then `username`\n and `password` contain the parsed credentials.\n\n Use `self.raw_auth` to access the raw value passed through\n `--auth, -a`.\n\n Return a ``requests.auth.AuthBase`` subclass instance.\n\n \"\"\"\n raise NotImplementedError()", "focal_method_lines": [55, 66], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass AuthPlugin(BasePlugin):\n\n auth_type = None\n\n auth_require = True\n\n auth_parse = True\n\n netrc_parse = False\n\n prompt_password = True\n\n raw_auth = None\n\n def get_auth(self, username=None, password=None):\n \"\"\"\n If `auth_parse` is set to `True`, then `username`\n and `password` contain the parsed credentials.\n\n Use `self.raw_auth` to access the raw value passed through\n `--auth, -a`.\n\n Return a ``requests.auth.AuthBase`` subclass instance.\n\n \"\"\"\n raise NotImplementedError()", "has_branch": false, "total_branches": 0} {"prompt_id": 155, "project": "httpie", "module": "httpie.plugins.base", "class": "TransportPlugin", "method": "get_adapter", "focal_method_txt": " def get_adapter(self):\n \"\"\"\n Return a ``requests.adapters.BaseAdapter`` subclass instance to be\n mounted to ``self.prefix``.\n\n \"\"\"\n raise NotImplementedError()", "focal_method_lines": [84, 90], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass TransportPlugin(BasePlugin):\n\n prefix = None\n\n def get_adapter(self):\n \"\"\"\n Return a ``requests.adapters.BaseAdapter`` subclass instance to be\n mounted to ``self.prefix``.\n\n \"\"\"\n raise NotImplementedError()", "has_branch": false, "total_branches": 0} {"prompt_id": 156, "project": "httpie", "module": "httpie.plugins.base", "class": "ConverterPlugin", "method": "__init__", "focal_method_txt": " def __init__(self, mime):\n self.mime = mime", "focal_method_lines": [103, 104], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass ConverterPlugin(BasePlugin):\n\n def __init__(self, mime):\n self.mime = mime", "has_branch": false, "total_branches": 0} {"prompt_id": 157, "project": "httpie", "module": "httpie.plugins.base", "class": "ConverterPlugin", "method": "convert", "focal_method_txt": " def convert(self, content_bytes):\n raise NotImplementedError", "focal_method_lines": [106, 107], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass ConverterPlugin(BasePlugin):\n\n def __init__(self, mime):\n self.mime = mime\n\n def convert(self, content_bytes):\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 158, "project": "httpie", "module": "httpie.plugins.base", "class": "FormatterPlugin", "method": "__init__", "focal_method_txt": " def __init__(self, **kwargs):\n \"\"\"\n :param env: an class:`Environment` instance\n :param kwargs: additional keyword argument that some\n formatters might require.\n\n \"\"\"\n self.enabled = True\n self.kwargs = kwargs\n self.format_options = kwargs['format_options']", "focal_method_lines": [121, 130], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass FormatterPlugin(BasePlugin):\n\n group_name = 'format'\n\n def __init__(self, **kwargs):\n \"\"\"\n :param env: an class:`Environment` instance\n :param kwargs: additional keyword argument that some\n formatters might require.\n\n \"\"\"\n self.enabled = True\n self.kwargs = kwargs\n self.format_options = kwargs['format_options']", "has_branch": false, "total_branches": 0} {"prompt_id": 159, "project": "httpie", "module": "httpie.plugins.base", "class": "FormatterPlugin", "method": "format_headers", "focal_method_txt": " def format_headers(self, headers: str) -> str:\n \"\"\"Return processed `headers`\n\n :param headers: The headers as text.\n\n \"\"\"\n return headers", "focal_method_lines": [132, 138], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass FormatterPlugin(BasePlugin):\n\n group_name = 'format'\n\n def __init__(self, **kwargs):\n \"\"\"\n :param env: an class:`Environment` instance\n :param kwargs: additional keyword argument that some\n formatters might require.\n\n \"\"\"\n self.enabled = True\n self.kwargs = kwargs\n self.format_options = kwargs['format_options']\n\n def format_headers(self, headers: str) -> str:\n \"\"\"Return processed `headers`\n\n :param headers: The headers as text.\n\n \"\"\"\n return headers", "has_branch": false, "total_branches": 0} {"prompt_id": 160, "project": "httpie", "module": "httpie.plugins.base", "class": "FormatterPlugin", "method": "format_body", "focal_method_txt": " def format_body(self, content: str, mime: str) -> str:\n \"\"\"Return processed `content`.\n\n :param mime: E.g., 'application/atom+xml'.\n :param content: The body content as text\n\n \"\"\"\n return content", "focal_method_lines": [140, 147], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass FormatterPlugin(BasePlugin):\n\n group_name = 'format'\n\n def __init__(self, **kwargs):\n \"\"\"\n :param env: an class:`Environment` instance\n :param kwargs: additional keyword argument that some\n formatters might require.\n\n \"\"\"\n self.enabled = True\n self.kwargs = kwargs\n self.format_options = kwargs['format_options']\n\n def format_body(self, content: str, mime: str) -> str:\n \"\"\"Return processed `content`.\n\n :param mime: E.g., 'application/atom+xml'.\n :param content: The body content as text\n\n \"\"\"\n return content", "has_branch": false, "total_branches": 0} {"prompt_id": 161, "project": "httpie", "module": "httpie.plugins.manager", "class": "PluginManager", "method": "filter", "focal_method_txt": " def filter(self, by_type=Type[BasePlugin]):\n return [plugin for plugin in self if issubclass(plugin, by_type)]", "focal_method_lines": [27, 28], "in_stack": false, "globals": ["ENTRY_POINT_NAMES"], "type_context": "from itertools import groupby\nfrom operator import attrgetter\nfrom typing import Dict, List, Type\nfrom pkg_resources import iter_entry_points\nfrom httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin\nfrom httpie.plugins.base import BasePlugin, TransportPlugin\n\nENTRY_POINT_NAMES = [\n 'httpie.plugins.auth.v1',\n 'httpie.plugins.formatter.v1',\n 'httpie.plugins.converter.v1',\n 'httpie.plugins.transport.v1',\n]\n\nclass PluginManager(list):\n\n def filter(self, by_type=Type[BasePlugin]):\n return [plugin for plugin in self if issubclass(plugin, by_type)]", "has_branch": false, "total_branches": 0} {"prompt_id": 162, "project": "httpie", "module": "httpie.plugins.manager", "class": "PluginManager", "method": "load_installed_plugins", "focal_method_txt": " def load_installed_plugins(self):\n for entry_point_name in ENTRY_POINT_NAMES:\n for entry_point in iter_entry_points(entry_point_name):\n plugin = entry_point.load()\n plugin.package_name = entry_point.dist.key\n self.register(entry_point.load())", "focal_method_lines": [30, 35], "in_stack": false, "globals": ["ENTRY_POINT_NAMES"], "type_context": "from itertools import groupby\nfrom operator import attrgetter\nfrom typing import Dict, List, Type\nfrom pkg_resources import iter_entry_points\nfrom httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin\nfrom httpie.plugins.base import BasePlugin, TransportPlugin\n\nENTRY_POINT_NAMES = [\n 'httpie.plugins.auth.v1',\n 'httpie.plugins.formatter.v1',\n 'httpie.plugins.converter.v1',\n 'httpie.plugins.transport.v1',\n]\n\nclass PluginManager(list):\n\n def load_installed_plugins(self):\n for entry_point_name in ENTRY_POINT_NAMES:\n for entry_point in iter_entry_points(entry_point_name):\n plugin = entry_point.load()\n plugin.package_name = entry_point.dist.key\n self.register(entry_point.load())", "has_branch": true, "total_branches": 2} {"prompt_id": 163, "project": "httpie", "module": "httpie.plugins.manager", "class": "PluginManager", "method": "get_auth_plugin_mapping", "focal_method_txt": " def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]:\n return {\n plugin.auth_type: plugin for plugin in self.get_auth_plugins()\n }", "focal_method_lines": [41, 42], "in_stack": false, "globals": ["ENTRY_POINT_NAMES"], "type_context": "from itertools import groupby\nfrom operator import attrgetter\nfrom typing import Dict, List, Type\nfrom pkg_resources import iter_entry_points\nfrom httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin\nfrom httpie.plugins.base import BasePlugin, TransportPlugin\n\nENTRY_POINT_NAMES = [\n 'httpie.plugins.auth.v1',\n 'httpie.plugins.formatter.v1',\n 'httpie.plugins.converter.v1',\n 'httpie.plugins.transport.v1',\n]\n\nclass PluginManager(list):\n\n def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]:\n return {\n plugin.auth_type: plugin for plugin in self.get_auth_plugins()\n }", "has_branch": false, "total_branches": 0} {"prompt_id": 164, "project": "httpie", "module": "httpie.plugins.manager", "class": "PluginManager", "method": "get_formatters_grouped", "focal_method_txt": " def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]:\n return {\n group_name: list(group)\n for group_name, group\n in groupby(self.get_formatters(), key=attrgetter('group_name'))\n }", "focal_method_lines": [53, 54], "in_stack": false, "globals": ["ENTRY_POINT_NAMES"], "type_context": "from itertools import groupby\nfrom operator import attrgetter\nfrom typing import Dict, List, Type\nfrom pkg_resources import iter_entry_points\nfrom httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin\nfrom httpie.plugins.base import BasePlugin, TransportPlugin\n\nENTRY_POINT_NAMES = [\n 'httpie.plugins.auth.v1',\n 'httpie.plugins.formatter.v1',\n 'httpie.plugins.converter.v1',\n 'httpie.plugins.transport.v1',\n]\n\nclass PluginManager(list):\n\n def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]:\n return {\n group_name: list(group)\n for group_name, group\n in groupby(self.get_formatters(), key=attrgetter('group_name'))\n }", "has_branch": false, "total_branches": 0} {"prompt_id": 165, "project": "httpie", "module": "httpie.sessions", "class": "", "method": "get_httpie_session", "focal_method_txt": "def get_httpie_session(\n config_dir: Path,\n session_name: str,\n host: Optional[str],\n url: str,\n) -> 'Session':\n if os.path.sep in session_name:\n path = os.path.expanduser(session_name)\n else:\n hostname = host or urlsplit(url).netloc.split('@')[-1]\n if not hostname:\n # HACK/FIXME: httpie-unixsocket's URLs have no hostname.\n hostname = 'localhost'\n\n # host:port => host_port\n hostname = hostname.replace(':', '_')\n path = (\n config_dir / SESSIONS_DIR_NAME / hostname / f'{session_name}.json'\n )\n session = Session(path)\n session.load()\n return session", "focal_method_lines": [29, 50], "in_stack": false, "globals": ["SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES"], "type_context": "import os\nimport re\nfrom http.cookies import SimpleCookie\nfrom pathlib import Path\nfrom typing import Iterable, Optional, Union\nfrom urllib.parse import urlsplit\nfrom requests.auth import AuthBase\nfrom requests.cookies import RequestsCookieJar, create_cookie\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR\nfrom httpie.plugins.registry import plugin_manager\n\nSESSIONS_DIR_NAME = 'sessions'\nDEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME\nVALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')\nSESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']\n\nclass Session(BaseConfigDict):\n\n helpurl = 'https://httpie.org/doc#sessions'\n\n about = 'HTTPie session file'\n\n def __init__(self, path: Union[str, Path]):\n super().__init__(path=Path(path))\n self['headers'] = {}\n self['cookies'] = {}\n self['auth'] = {\n 'type': None,\n 'username': None,\n 'password': None\n }\n\ndef get_httpie_session(\n config_dir: Path,\n session_name: str,\n host: Optional[str],\n url: str,\n) -> 'Session':\n if os.path.sep in session_name:\n path = os.path.expanduser(session_name)\n else:\n hostname = host or urlsplit(url).netloc.split('@')[-1]\n if not hostname:\n # HACK/FIXME: httpie-unixsocket's URLs have no hostname.\n hostname = 'localhost'\n\n # host:port => host_port\n hostname = hostname.replace(':', '_')\n path = (\n config_dir / SESSIONS_DIR_NAME / hostname / f'{session_name}.json'\n )\n session = Session(path)\n session.load()\n return session", "has_branch": true, "total_branches": 2} {"prompt_id": 166, "project": "httpie", "module": "httpie.sessions", "class": "Session", "method": "__init__", "focal_method_txt": " def __init__(self, path: Union[str, Path]):\n super().__init__(path=Path(path))\n self['headers'] = {}\n self['cookies'] = {}\n self['auth'] = {\n 'type': None,\n 'username': None,\n 'password': None\n }", "focal_method_lines": [57, 61], "in_stack": false, "globals": ["SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES"], "type_context": "import os\nimport re\nfrom http.cookies import SimpleCookie\nfrom pathlib import Path\nfrom typing import Iterable, Optional, Union\nfrom urllib.parse import urlsplit\nfrom requests.auth import AuthBase\nfrom requests.cookies import RequestsCookieJar, create_cookie\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR\nfrom httpie.plugins.registry import plugin_manager\n\nSESSIONS_DIR_NAME = 'sessions'\nDEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME\nVALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')\nSESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']\n\nclass Session(BaseConfigDict):\n\n helpurl = 'https://httpie.org/doc#sessions'\n\n about = 'HTTPie session file'\n\n def __init__(self, path: Union[str, Path]):\n super().__init__(path=Path(path))\n self['headers'] = {}\n self['cookies'] = {}\n self['auth'] = {\n 'type': None,\n 'username': None,\n 'password': None\n }", "has_branch": false, "total_branches": 0} {"prompt_id": 167, "project": "httpie", "module": "httpie.sessions", "class": "Session", "method": "update_headers", "focal_method_txt": " def update_headers(self, request_headers: RequestHeadersDict):\n \"\"\"\n Update the session headers with the request ones while ignoring\n certain name prefixes.\n\n \"\"\"\n headers = self.headers\n for name, value in request_headers.items():\n\n if value is None:\n continue # Ignore explicitly unset headers\n\n if type(value) is not str:\n value = value.decode('utf8')\n\n if name.lower() == 'user-agent' and value.startswith('HTTPie/'):\n continue\n\n if name.lower() == 'cookie':\n for cookie_name, morsel in SimpleCookie(value).items():\n self['cookies'][cookie_name] = {'value': morsel.value}\n del request_headers[name]\n continue\n\n for prefix in SESSION_IGNORED_HEADER_PREFIXES:\n if name.lower().startswith(prefix.lower()):\n break\n else:\n headers[name] = value\n\n self['headers'] = dict(headers)", "focal_method_lines": [67, 97], "in_stack": false, "globals": ["SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES"], "type_context": "import os\nimport re\nfrom http.cookies import SimpleCookie\nfrom pathlib import Path\nfrom typing import Iterable, Optional, Union\nfrom urllib.parse import urlsplit\nfrom requests.auth import AuthBase\nfrom requests.cookies import RequestsCookieJar, create_cookie\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR\nfrom httpie.plugins.registry import plugin_manager\n\nSESSIONS_DIR_NAME = 'sessions'\nDEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME\nVALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')\nSESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']\n\nclass Session(BaseConfigDict):\n\n helpurl = 'https://httpie.org/doc#sessions'\n\n about = 'HTTPie session file'\n\n def __init__(self, path: Union[str, Path]):\n super().__init__(path=Path(path))\n self['headers'] = {}\n self['cookies'] = {}\n self['auth'] = {\n 'type': None,\n 'username': None,\n 'password': None\n }\n\n def update_headers(self, request_headers: RequestHeadersDict):\n \"\"\"\n Update the session headers with the request ones while ignoring\n certain name prefixes.\n\n \"\"\"\n headers = self.headers\n for name, value in request_headers.items():\n\n if value is None:\n continue # Ignore explicitly unset headers\n\n if type(value) is not str:\n value = value.decode('utf8')\n\n if name.lower() == 'user-agent' and value.startswith('HTTPie/'):\n continue\n\n if name.lower() == 'cookie':\n for cookie_name, morsel in SimpleCookie(value).items():\n self['cookies'][cookie_name] = {'value': morsel.value}\n del request_headers[name]\n continue\n\n for prefix in SESSION_IGNORED_HEADER_PREFIXES:\n if name.lower().startswith(prefix.lower()):\n break\n else:\n headers[name] = value\n\n self['headers'] = dict(headers)", "has_branch": true, "total_branches": 2} {"prompt_id": 168, "project": "httpie", "module": "httpie.sessions", "class": "Session", "method": "remove_cookies", "focal_method_txt": " def remove_cookies(self, names: Iterable[str]):\n for name in names:\n if name in self['cookies']:\n del self['cookies'][name]", "focal_method_lines": [157, 160], "in_stack": false, "globals": ["SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES"], "type_context": "import os\nimport re\nfrom http.cookies import SimpleCookie\nfrom pathlib import Path\nfrom typing import Iterable, Optional, Union\nfrom urllib.parse import urlsplit\nfrom requests.auth import AuthBase\nfrom requests.cookies import RequestsCookieJar, create_cookie\nfrom httpie.cli.dicts import RequestHeadersDict\nfrom httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR\nfrom httpie.plugins.registry import plugin_manager\n\nSESSIONS_DIR_NAME = 'sessions'\nDEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME\nVALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')\nSESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']\n\nclass Session(BaseConfigDict):\n\n helpurl = 'https://httpie.org/doc#sessions'\n\n about = 'HTTPie session file'\n\n def __init__(self, path: Union[str, Path]):\n super().__init__(path=Path(path))\n self['headers'] = {}\n self['cookies'] = {}\n self['auth'] = {\n 'type': None,\n 'username': None,\n 'password': None\n }\n\n def remove_cookies(self, names: Iterable[str]):\n for name in names:\n if name in self['cookies']:\n del self['cookies'][name]", "has_branch": true, "total_branches": 2} {"prompt_id": 169, "project": "httpie", "module": "httpie.uploads", "class": "", "method": "prepare_request_body", "focal_method_txt": "def prepare_request_body(\n body: Union[str, bytes, IO, MultipartEncoder, RequestDataDict],\n body_read_callback: Callable[[bytes], bytes],\n content_length_header_value: int = None,\n chunked=False,\n offline=False,\n) -> Union[str, bytes, IO, MultipartEncoder, ChunkedUploadStream]:\n\n is_file_like = hasattr(body, 'read')\n\n if isinstance(body, RequestDataDict):\n body = urlencode(body, doseq=True)\n\n if offline:\n if is_file_like:\n return body.read()\n return body\n\n if not is_file_like:\n if chunked:\n body = ChunkedUploadStream(\n # Pass the entire body as one chunk.\n stream=(chunk.encode() for chunk in [body]),\n callback=body_read_callback,\n )\n else:\n # File-like object.\n\n if not super_len(body):\n # Zero-length -> assume stdin.\n if content_length_header_value is None and not chunked:\n #\n # Read the whole stdin to determine `Content-Length`.\n #\n # TODO: Instead of opt-in --chunked, consider making\n # `Transfer-Encoding: chunked` for STDIN opt-out via\n # something like --no-chunked.\n # This would be backwards-incompatible so wait until v3.0.0.\n #\n body = body.read()\n else:\n orig_read = body.read\n\n def new_read(*args):\n chunk = orig_read(*args)\n body_read_callback(chunk)\n return chunk\n\n body.read = new_read\n\n if chunked:\n if isinstance(body, MultipartEncoder):\n body = ChunkedMultipartUploadStream(\n encoder=body,\n )\n else:\n body = ChunkedUploadStream(\n stream=body,\n callback=body_read_callback,\n )\n\n return body", "focal_method_lines": [36, 97], "in_stack": false, "globals": [], "type_context": "import zlib\nfrom typing import Callable, IO, Iterable, Tuple, Union\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.utils import super_len\nfrom requests_toolbelt import MultipartEncoder\nfrom httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict\n\n\n\nclass ChunkedUploadStream:\n\n def __init__(self, stream: Iterable, callback: Callable):\n self.callback = callback\n self.stream = stream\n\nclass ChunkedMultipartUploadStream:\n\n chunk_size = 100 * 1024\n\n def __init__(self, encoder: MultipartEncoder):\n self.encoder = encoder\n\ndef prepare_request_body(\n body: Union[str, bytes, IO, MultipartEncoder, RequestDataDict],\n body_read_callback: Callable[[bytes], bytes],\n content_length_header_value: int = None,\n chunked=False,\n offline=False,\n) -> Union[str, bytes, IO, MultipartEncoder, ChunkedUploadStream]:\n\n is_file_like = hasattr(body, 'read')\n\n if isinstance(body, RequestDataDict):\n body = urlencode(body, doseq=True)\n\n if offline:\n if is_file_like:\n return body.read()\n return body\n\n if not is_file_like:\n if chunked:\n body = ChunkedUploadStream(\n # Pass the entire body as one chunk.\n stream=(chunk.encode() for chunk in [body]),\n callback=body_read_callback,\n )\n else:\n # File-like object.\n\n if not super_len(body):\n # Zero-length -> assume stdin.\n if content_length_header_value is None and not chunked:\n #\n # Read the whole stdin to determine `Content-Length`.\n #\n # TODO: Instead of opt-in --chunked, consider making\n # `Transfer-Encoding: chunked` for STDIN opt-out via\n # something like --no-chunked.\n # This would be backwards-incompatible so wait until v3.0.0.\n #\n body = body.read()\n else:\n orig_read = body.read\n\n def new_read(*args):\n chunk = orig_read(*args)\n body_read_callback(chunk)\n return chunk\n\n body.read = new_read\n\n if chunked:\n if isinstance(body, MultipartEncoder):\n body = ChunkedMultipartUploadStream(\n encoder=body,\n )\n else:\n body = ChunkedUploadStream(\n stream=body,\n callback=body_read_callback,\n )\n\n return body", "has_branch": true, "total_branches": 2} {"prompt_id": 170, "project": "httpie", "module": "httpie.uploads", "class": "", "method": "get_multipart_data_and_content_type", "focal_method_txt": "def get_multipart_data_and_content_type(\n data: MultipartRequestDataDict,\n boundary: str = None,\n content_type: str = None,\n) -> Tuple[MultipartEncoder, str]:\n encoder = MultipartEncoder(\n fields=data.items(),\n boundary=boundary,\n )\n if content_type:\n content_type = content_type.strip()\n if 'boundary=' not in content_type:\n content_type = f'{content_type}; boundary={encoder.boundary_value}'\n else:\n content_type = encoder.content_type\n\n data = encoder\n return data, content_type", "focal_method_lines": [100, 117], "in_stack": false, "globals": [], "type_context": "import zlib\nfrom typing import Callable, IO, Iterable, Tuple, Union\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.utils import super_len\nfrom requests_toolbelt import MultipartEncoder\nfrom httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict\n\n\n\ndef get_multipart_data_and_content_type(\n data: MultipartRequestDataDict,\n boundary: str = None,\n content_type: str = None,\n) -> Tuple[MultipartEncoder, str]:\n encoder = MultipartEncoder(\n fields=data.items(),\n boundary=boundary,\n )\n if content_type:\n content_type = content_type.strip()\n if 'boundary=' not in content_type:\n content_type = f'{content_type}; boundary={encoder.boundary_value}'\n else:\n content_type = encoder.content_type\n\n data = encoder\n return data, content_type", "has_branch": true, "total_branches": 2} {"prompt_id": 171, "project": "httpie", "module": "httpie.uploads", "class": "", "method": "compress_request", "focal_method_txt": "def compress_request(\n request: requests.PreparedRequest,\n always: bool,\n):\n deflater = zlib.compressobj()\n if isinstance(request.body, str):\n body_bytes = request.body.encode()\n elif hasattr(request.body, 'read'):\n body_bytes = request.body.read()\n else:\n body_bytes = request.body\n deflated_data = deflater.compress(body_bytes)\n deflated_data += deflater.flush()\n is_economical = len(deflated_data) < len(body_bytes)\n if is_economical or always:\n request.body = deflated_data\n request.headers['Content-Encoding'] = 'deflate'\n request.headers['Content-Length'] = str(len(deflated_data))", "focal_method_lines": [120, 137], "in_stack": false, "globals": [], "type_context": "import zlib\nfrom typing import Callable, IO, Iterable, Tuple, Union\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.utils import super_len\nfrom requests_toolbelt import MultipartEncoder\nfrom httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict\n\n\n\ndef compress_request(\n request: requests.PreparedRequest,\n always: bool,\n):\n deflater = zlib.compressobj()\n if isinstance(request.body, str):\n body_bytes = request.body.encode()\n elif hasattr(request.body, 'read'):\n body_bytes = request.body.read()\n else:\n body_bytes = request.body\n deflated_data = deflater.compress(body_bytes)\n deflated_data += deflater.flush()\n is_economical = len(deflated_data) < len(body_bytes)\n if is_economical or always:\n request.body = deflated_data\n request.headers['Content-Encoding'] = 'deflate'\n request.headers['Content-Length'] = str(len(deflated_data))", "has_branch": true, "total_branches": 2} {"prompt_id": 172, "project": "httpie", "module": "httpie.uploads", "class": "ChunkedUploadStream", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> Iterable[Union[str, bytes]]:\n for chunk in self.stream:\n self.callback(chunk)\n yield chunk", "focal_method_lines": [16, 19], "in_stack": false, "globals": [], "type_context": "import zlib\nfrom typing import Callable, IO, Iterable, Tuple, Union\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.utils import super_len\nfrom requests_toolbelt import MultipartEncoder\nfrom httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict\n\n\n\nclass ChunkedUploadStream:\n\n def __init__(self, stream: Iterable, callback: Callable):\n self.callback = callback\n self.stream = stream\n\n def __iter__(self) -> Iterable[Union[str, bytes]]:\n for chunk in self.stream:\n self.callback(chunk)\n yield chunk", "has_branch": true, "total_branches": 2} {"prompt_id": 173, "project": "httpie", "module": "httpie.uploads", "class": "ChunkedMultipartUploadStream", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> Iterable[Union[str, bytes]]:\n while True:\n chunk = self.encoder.read(self.chunk_size)\n if not chunk:\n break\n yield chunk", "focal_method_lines": [28, 33], "in_stack": false, "globals": [], "type_context": "import zlib\nfrom typing import Callable, IO, Iterable, Tuple, Union\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.utils import super_len\nfrom requests_toolbelt import MultipartEncoder\nfrom httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict\n\n\n\nclass ChunkedMultipartUploadStream:\n\n chunk_size = 100 * 1024\n\n def __init__(self, encoder: MultipartEncoder):\n self.encoder = encoder\n\n def __iter__(self) -> Iterable[Union[str, bytes]]:\n while True:\n chunk = self.encoder.read(self.chunk_size)\n if not chunk:\n break\n yield chunk", "has_branch": true, "total_branches": 2} {"prompt_id": 174, "project": "httpie", "module": "httpie.utils", "class": "", "method": "load_json_preserve_order", "focal_method_txt": "def load_json_preserve_order(s):\n return json.loads(s, object_pairs_hook=OrderedDict)", "focal_method_lines": [13, 14], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\ndef load_json_preserve_order(s):\n return json.loads(s, object_pairs_hook=OrderedDict)", "has_branch": false, "total_branches": 0} {"prompt_id": 175, "project": "httpie", "module": "httpie.utils", "class": "", "method": "repr_dict", "focal_method_txt": "def repr_dict(d: dict) -> str:\n return pformat(d)", "focal_method_lines": [17, 18], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\ndef repr_dict(d: dict) -> str:\n return pformat(d)", "has_branch": false, "total_branches": 0} {"prompt_id": 176, "project": "httpie", "module": "httpie.utils", "class": "", "method": "humanize_bytes", "focal_method_txt": "def humanize_bytes(n, precision=2):\n # Author: Doug Latornell\n # Licence: MIT\n # URL: https://code.activestate.com/recipes/577081/\n \"\"\"Return a humanized string representation of a number of bytes.\n\n Assumes `from __future__ import division`.\n\n >>> humanize_bytes(1)\n '1 B'\n >>> humanize_bytes(1024, precision=1)\n '1.0 kB'\n >>> humanize_bytes(1024 * 123, precision=1)\n '123.0 kB'\n >>> humanize_bytes(1024 * 12342, precision=1)\n '12.1 MB'\n >>> humanize_bytes(1024 * 12342, precision=2)\n '12.05 MB'\n >>> humanize_bytes(1024 * 1234, precision=2)\n '1.21 MB'\n >>> humanize_bytes(1024 * 1234 * 1111, precision=2)\n '1.31 GB'\n >>> humanize_bytes(1024 * 1234 * 1111, precision=1)\n '1.3 GB'\n\n \"\"\"\n abbrevs = [\n (1 << 50, 'PB'),\n (1 << 40, 'TB'),\n (1 << 30, 'GB'),\n (1 << 20, 'MB'),\n (1 << 10, 'kB'),\n (1, 'B')\n ]\n\n if n == 1:\n return '1 B'\n\n for factor, suffix in abbrevs:\n if n >= factor:\n break\n\n # noinspection PyUnboundLocalVariable\n return '%.*f %s' % (precision, n / factor, suffix)", "focal_method_lines": [21, 64], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\ndef humanize_bytes(n, precision=2):\n # Author: Doug Latornell\n # Licence: MIT\n # URL: https://code.activestate.com/recipes/577081/\n \"\"\"Return a humanized string representation of a number of bytes.\n\n Assumes `from __future__ import division`.\n\n >>> humanize_bytes(1)\n '1 B'\n >>> humanize_bytes(1024, precision=1)\n '1.0 kB'\n >>> humanize_bytes(1024 * 123, precision=1)\n '123.0 kB'\n >>> humanize_bytes(1024 * 12342, precision=1)\n '12.1 MB'\n >>> humanize_bytes(1024 * 12342, precision=2)\n '12.05 MB'\n >>> humanize_bytes(1024 * 1234, precision=2)\n '1.21 MB'\n >>> humanize_bytes(1024 * 1234 * 1111, precision=2)\n '1.31 GB'\n >>> humanize_bytes(1024 * 1234 * 1111, precision=1)\n '1.3 GB'\n\n \"\"\"\n abbrevs = [\n (1 << 50, 'PB'),\n (1 << 40, 'TB'),\n (1 << 30, 'GB'),\n (1 << 20, 'MB'),\n (1 << 10, 'kB'),\n (1, 'B')\n ]\n\n if n == 1:\n return '1 B'\n\n for factor, suffix in abbrevs:\n if n >= factor:\n break\n\n # noinspection PyUnboundLocalVariable\n return '%.*f %s' % (precision, n / factor, suffix)", "has_branch": true, "total_branches": 2} {"prompt_id": 177, "project": "httpie", "module": "httpie.utils", "class": "", "method": "get_content_type", "focal_method_txt": "def get_content_type(filename):\n \"\"\"\n Return the content type for ``filename`` in format appropriate\n for Content-Type headers, or ``None`` if the file type is unknown\n to ``mimetypes``.\n\n \"\"\"\n mime, encoding = mimetypes.guess_type(filename, strict=False)\n if mime:\n content_type = mime\n if encoding:\n content_type = '%s; charset=%s' % (mime, encoding)\n return content_type", "focal_method_lines": [76, 88], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\ndef get_content_type(filename):\n \"\"\"\n Return the content type for ``filename`` in format appropriate\n for Content-Type headers, or ``None`` if the file type is unknown\n to ``mimetypes``.\n\n \"\"\"\n mime, encoding = mimetypes.guess_type(filename, strict=False)\n if mime:\n content_type = mime\n if encoding:\n content_type = '%s; charset=%s' % (mime, encoding)\n return content_type", "has_branch": true, "total_branches": 2} {"prompt_id": 178, "project": "httpie", "module": "httpie.utils", "class": "", "method": "get_expired_cookies", "focal_method_txt": "def get_expired_cookies(\n headers: List[Tuple[str, str]],\n now: float = None\n) -> List[dict]:\n\n now = now or time.time()\n\n def is_expired(expires: Optional[float]) -> bool:\n return expires is not None and expires <= now\n\n attr_sets: List[Tuple[str, str]] = parse_ns_headers(\n value for name, value in headers\n if name.lower() == 'set-cookie'\n )\n cookies = [\n # The first attr name is the cookie name.\n dict(attrs[1:], name=attrs[0][0])\n for attrs in attr_sets\n ]\n\n _max_age_to_expires(cookies=cookies, now=now)\n\n return [\n {\n 'name': cookie['name'],\n 'path': cookie.get('path', '/')\n }\n for cookie in cookies\n if is_expired(expires=cookie.get('expires'))\n ]", "focal_method_lines": [91, 113], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\ndef get_expired_cookies(\n headers: List[Tuple[str, str]],\n now: float = None\n) -> List[dict]:\n\n now = now or time.time()\n\n def is_expired(expires: Optional[float]) -> bool:\n return expires is not None and expires <= now\n\n attr_sets: List[Tuple[str, str]] = parse_ns_headers(\n value for name, value in headers\n if name.lower() == 'set-cookie'\n )\n cookies = [\n # The first attr name is the cookie name.\n dict(attrs[1:], name=attrs[0][0])\n for attrs in attr_sets\n ]\n\n _max_age_to_expires(cookies=cookies, now=now)\n\n return [\n {\n 'name': cookie['name'],\n 'path': cookie.get('path', '/')\n }\n for cookie in cookies\n if is_expired(expires=cookie.get('expires'))\n ]", "has_branch": false, "total_branches": 0} {"prompt_id": 179, "project": "httpie", "module": "httpie.utils", "class": "ExplicitNullAuth", "method": "__call__", "focal_method_txt": " def __call__(self, r):\n return r", "focal_method_lines": [72, 73], "in_stack": false, "globals": [], "type_context": "import json\nimport mimetypes\nimport time\nfrom collections import OrderedDict\nfrom http.cookiejar import parse_ns_headers\nfrom pprint import pformat\nfrom typing import List, Optional, Tuple\nimport requests.auth\n\n\n\nclass ExplicitNullAuth(requests.auth.AuthBase):\n\n def __call__(self, r):\n return r", "has_branch": false, "total_branches": 0} {"prompt_id": 180, "project": "isort", "module": "isort.exceptions", "class": "InvalidSettingsPath", "method": "__init__", "focal_method_txt": " def __init__(self, settings_path: str):\n super().__init__(\n f\"isort was told to use the settings_path: {settings_path} as the base directory or \"\n \"file that represents the starting point of config file discovery, but it does not \"\n \"exist.\"\n )\n self.settings_path = settings_path", "focal_method_lines": [14, 20], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass InvalidSettingsPath(ISortError):\n\n def __init__(self, settings_path: str):\n super().__init__(\n f\"isort was told to use the settings_path: {settings_path} as the base directory or \"\n \"file that represents the starting point of config file discovery, but it does not \"\n \"exist.\"\n )\n self.settings_path = settings_path", "has_branch": false, "total_branches": 0} {"prompt_id": 181, "project": "isort", "module": "isort.exceptions", "class": "ExistingSyntaxErrors", "method": "__init__", "focal_method_txt": " def __init__(self, file_path: str):\n super().__init__(\n f\"isort was told to sort imports within code that contains syntax errors: \"\n f\"{file_path}.\"\n )\n self.file_path = file_path", "focal_method_lines": [26, 31], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass ExistingSyntaxErrors(ISortError):\n\n def __init__(self, file_path: str):\n super().__init__(\n f\"isort was told to sort imports within code that contains syntax errors: \"\n f\"{file_path}.\"\n )\n self.file_path = file_path", "has_branch": false, "total_branches": 0} {"prompt_id": 182, "project": "isort", "module": "isort.exceptions", "class": "IntroducedSyntaxErrors", "method": "__init__", "focal_method_txt": " def __init__(self, file_path: str):\n super().__init__(\n f\"isort introduced syntax errors when attempting to sort the imports contained within \"\n f\"{file_path}.\"\n )\n self.file_path = file_path", "focal_method_lines": [37, 42], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass IntroducedSyntaxErrors(ISortError):\n\n def __init__(self, file_path: str):\n super().__init__(\n f\"isort introduced syntax errors when attempting to sort the imports contained within \"\n f\"{file_path}.\"\n )\n self.file_path = file_path", "has_branch": false, "total_branches": 0} {"prompt_id": 183, "project": "isort", "module": "isort.exceptions", "class": "FileSkipped", "method": "__init__", "focal_method_txt": " def __init__(self, message: str, file_path: str):\n super().__init__(message)\n self.file_path = file_path", "focal_method_lines": [48, 50], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass FileSkipped(ISortError):\n\n def __init__(self, message: str, file_path: str):\n super().__init__(message)\n self.file_path = file_path", "has_branch": false, "total_branches": 0} {"prompt_id": 184, "project": "isort", "module": "isort.exceptions", "class": "FileSkipComment", "method": "__init__", "focal_method_txt": " def __init__(self, file_path: str):\n super().__init__(\n f\"{file_path} contains an file skip comment and was skipped.\", file_path=file_path\n )", "focal_method_lines": [56, 57], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass FileSkipComment(FileSkipped):\n\n def __init__(self, file_path: str):\n super().__init__(\n f\"{file_path} contains an file skip comment and was skipped.\", file_path=file_path\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 185, "project": "isort", "module": "isort.exceptions", "class": "FileSkipSetting", "method": "__init__", "focal_method_txt": " def __init__(self, file_path: str):\n super().__init__(\n f\"{file_path} was skipped as it's listed in 'skip' setting\"\n \" or matches a glob in 'skip_glob' setting\",\n file_path=file_path,\n )", "focal_method_lines": [65, 66], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass FileSkipSetting(FileSkipped):\n\n def __init__(self, file_path: str):\n super().__init__(\n f\"{file_path} was skipped as it's listed in 'skip' setting\"\n \" or matches a glob in 'skip_glob' setting\",\n file_path=file_path,\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 186, "project": "isort", "module": "isort.exceptions", "class": "ProfileDoesNotExist", "method": "__init__", "focal_method_txt": " def __init__(self, profile: str):\n super().__init__(\n f\"Specified profile of {profile} does not exist. \"\n f\"Available profiles: {','.join(profiles)}.\"\n )\n self.profile = profile", "focal_method_lines": [76, 81], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass ProfileDoesNotExist(ISortError):\n\n def __init__(self, profile: str):\n super().__init__(\n f\"Specified profile of {profile} does not exist. \"\n f\"Available profiles: {','.join(profiles)}.\"\n )\n self.profile = profile", "has_branch": false, "total_branches": 0} {"prompt_id": 187, "project": "isort", "module": "isort.exceptions", "class": "FormattingPluginDoesNotExist", "method": "__init__", "focal_method_txt": " def __init__(self, formatter: str):\n super().__init__(f\"Specified formatting plugin of {formatter} does not exist. \")\n self.formatter = formatter", "focal_method_lines": [87, 89], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass FormattingPluginDoesNotExist(ISortError):\n\n def __init__(self, formatter: str):\n super().__init__(f\"Specified formatting plugin of {formatter} does not exist. \")\n self.formatter = formatter", "has_branch": false, "total_branches": 0} {"prompt_id": 188, "project": "isort", "module": "isort.exceptions", "class": "LiteralParsingFailure", "method": "__init__", "focal_method_txt": " def __init__(self, code: str, original_error: Exception):\n super().__init__(\n f\"isort failed to parse the given literal {code}. It's important to note \"\n \"that isort literal sorting only supports simple literals parsable by \"\n f\"ast.literal_eval which gave the exception of {original_error}.\"\n )\n self.code = code\n self.original_error = original_error", "focal_method_lines": [97, 104], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass LiteralParsingFailure(ISortError):\n\n def __init__(self, code: str, original_error: Exception):\n super().__init__(\n f\"isort failed to parse the given literal {code}. It's important to note \"\n \"that isort literal sorting only supports simple literals parsable by \"\n f\"ast.literal_eval which gave the exception of {original_error}.\"\n )\n self.code = code\n self.original_error = original_error", "has_branch": false, "total_branches": 0} {"prompt_id": 189, "project": "isort", "module": "isort.exceptions", "class": "LiteralSortTypeMismatch", "method": "__init__", "focal_method_txt": " def __init__(self, kind: type, expected_kind: type):\n super().__init__(\n f\"isort was told to sort a literal of type {expected_kind} but was given \"\n f\"a literal of type {kind}.\"\n )\n self.kind = kind\n self.expected_kind = expected_kind", "focal_method_lines": [112, 118], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass LiteralSortTypeMismatch(ISortError):\n\n def __init__(self, kind: type, expected_kind: type):\n super().__init__(\n f\"isort was told to sort a literal of type {expected_kind} but was given \"\n f\"a literal of type {kind}.\"\n )\n self.kind = kind\n self.expected_kind = expected_kind", "has_branch": false, "total_branches": 0} {"prompt_id": 190, "project": "isort", "module": "isort.exceptions", "class": "AssignmentsFormatMismatch", "method": "__init__", "focal_method_txt": " def __init__(self, code: str):\n super().__init__(\n \"isort was told to sort a section of assignments, however the given code:\\n\\n\"\n f\"{code}\\n\\n\"\n \"Does not match isort's strict single line formatting requirement for assignment \"\n \"sorting:\\n\\n\"\n \"{variable_name} = {value}\\n\"\n \"{variable_name2} = {value2}\\n\"\n \"...\\n\\n\"\n )\n self.code = code", "focal_method_lines": [126, 136], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass AssignmentsFormatMismatch(ISortError):\n\n def __init__(self, code: str):\n super().__init__(\n \"isort was told to sort a section of assignments, however the given code:\\n\\n\"\n f\"{code}\\n\\n\"\n \"Does not match isort's strict single line formatting requirement for assignment \"\n \"sorting:\\n\\n\"\n \"{variable_name} = {value}\\n\"\n \"{variable_name2} = {value2}\\n\"\n \"...\\n\\n\"\n )\n self.code = code", "has_branch": false, "total_branches": 0} {"prompt_id": 191, "project": "isort", "module": "isort.exceptions", "class": "UnsupportedSettings", "method": "__init__", "focal_method_txt": " def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]):\n errors = \"\\n\".join(\n self._format_option(name, **option) for name, option in unsupported_settings.items()\n )\n\n super().__init__(\n \"isort was provided settings that it doesn't support:\\n\\n\"\n f\"{errors}\\n\\n\"\n \"For a complete and up-to-date listing of supported settings see: \"\n \"https://pycqa.github.io/isort/docs/configuration/options/.\\n\"\n )\n self.unsupported_settings = unsupported_settings", "focal_method_lines": [148, 159], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass UnsupportedSettings(ISortError):\n\n def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]):\n errors = \"\\n\".join(\n self._format_option(name, **option) for name, option in unsupported_settings.items()\n )\n\n super().__init__(\n \"isort was provided settings that it doesn't support:\\n\\n\"\n f\"{errors}\\n\\n\"\n \"For a complete and up-to-date listing of supported settings see: \"\n \"https://pycqa.github.io/isort/docs/configuration/options/.\\n\"\n )\n self.unsupported_settings = unsupported_settings", "has_branch": false, "total_branches": 0} {"prompt_id": 192, "project": "isort", "module": "isort.exceptions", "class": "UnsupportedEncoding", "method": "__init__", "focal_method_txt": " def __init__(self, filename: Union[str, Path]):\n super().__init__(f\"Unknown or unsupported encoding in {filename}\")\n self.filename = filename", "focal_method_lines": [165, 167], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass UnsupportedEncoding(ISortError):\n\n def __init__(self, filename: Union[str, Path]):\n super().__init__(f\"Unknown or unsupported encoding in {filename}\")\n self.filename = filename", "has_branch": false, "total_branches": 0} {"prompt_id": 193, "project": "isort", "module": "isort.exceptions", "class": "MissingSection", "method": "__init__", "focal_method_txt": " def __init__(self, import_module: str, section: str):\n super().__init__(\n f\"Found {import_module} import while parsing, but {section} was not included \"\n \"in the `sections` setting of your config. Please add it before continuing\\n\"\n \"See https://pycqa.github.io/isort/#custom-sections-and-ordering \"\n \"for more info.\"\n )", "focal_method_lines": [173, 174], "in_stack": false, "globals": [], "type_context": "from pathlib import Path\nfrom typing import Any, Dict, Union\nfrom .profiles import profiles\n\n\n\nclass MissingSection(ISortError):\n\n def __init__(self, import_module: str, section: str):\n super().__init__(\n f\"Found {import_module} import while parsing, but {section} was not included \"\n \"in the `sections` setting of your config. Please add it before continuing\\n\"\n \"See https://pycqa.github.io/isort/#custom-sections-and-ordering \"\n \"for more info.\"\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 194, "project": "isort", "module": "isort.format", "class": "", "method": "format_simplified", "focal_method_txt": "def format_simplified(import_line: str) -> str:\n import_line = import_line.strip()\n if import_line.startswith(\"from \"):\n import_line = import_line.replace(\"from \", \"\")\n import_line = import_line.replace(\" import \", \".\")\n elif import_line.startswith(\"import \"):\n import_line = import_line.replace(\"import \", \"\")\n\n return import_line", "focal_method_lines": [20, 28], "in_stack": false, "globals": ["ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN"], "type_context": "import re\nimport sys\nfrom datetime import datetime\nfrom difflib import unified_diff\nfrom pathlib import Path\nfrom typing import Optional, TextIO\n\nADDED_LINE_PATTERN = re.compile(r\"\\+[^+]\")\nREMOVED_LINE_PATTERN = re.compile(r\"-[^-]\")\n\ndef format_simplified(import_line: str) -> str:\n import_line = import_line.strip()\n if import_line.startswith(\"from \"):\n import_line = import_line.replace(\"from \", \"\")\n import_line = import_line.replace(\" import \", \".\")\n elif import_line.startswith(\"import \"):\n import_line = import_line.replace(\"import \", \"\")\n\n return import_line", "has_branch": true, "total_branches": 2} {"prompt_id": 195, "project": "isort", "module": "isort.format", "class": "", "method": "format_natural", "focal_method_txt": "def format_natural(import_line: str) -> str:\n import_line = import_line.strip()\n if not import_line.startswith(\"from \") and not import_line.startswith(\"import \"):\n if \".\" not in import_line:\n return f\"import {import_line}\"\n parts = import_line.split(\".\")\n end = parts.pop(-1)\n return f\"from {'.'.join(parts)} import {end}\"\n\n return import_line", "focal_method_lines": [31, 40], "in_stack": false, "globals": ["ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN"], "type_context": "import re\nimport sys\nfrom datetime import datetime\nfrom difflib import unified_diff\nfrom pathlib import Path\nfrom typing import Optional, TextIO\n\nADDED_LINE_PATTERN = re.compile(r\"\\+[^+]\")\nREMOVED_LINE_PATTERN = re.compile(r\"-[^-]\")\n\ndef format_natural(import_line: str) -> str:\n import_line = import_line.strip()\n if not import_line.startswith(\"from \") and not import_line.startswith(\"import \"):\n if \".\" not in import_line:\n return f\"import {import_line}\"\n parts = import_line.split(\".\")\n end = parts.pop(-1)\n return f\"from {'.'.join(parts)} import {end}\"\n\n return import_line", "has_branch": true, "total_branches": 2} {"prompt_id": 196, "project": "isort", "module": "isort.format", "class": "", "method": "ask_whether_to_apply_changes_to_file", "focal_method_txt": "def ask_whether_to_apply_changes_to_file(file_path: str) -> bool:\n answer = None\n while answer not in (\"yes\", \"y\", \"no\", \"n\", \"quit\", \"q\"):\n answer = input(f\"Apply suggested changes to '{file_path}' [y/n/q]? \") # nosec\n answer = answer.lower()\n if answer in (\"no\", \"n\"):\n return False\n if answer in (\"quit\", \"q\"):\n sys.exit(1)\n return True", "focal_method_lines": [76, 85], "in_stack": false, "globals": ["ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN"], "type_context": "import re\nimport sys\nfrom datetime import datetime\nfrom difflib import unified_diff\nfrom pathlib import Path\nfrom typing import Optional, TextIO\n\nADDED_LINE_PATTERN = re.compile(r\"\\+[^+]\")\nREMOVED_LINE_PATTERN = re.compile(r\"-[^-]\")\n\ndef ask_whether_to_apply_changes_to_file(file_path: str) -> bool:\n answer = None\n while answer not in (\"yes\", \"y\", \"no\", \"n\", \"quit\", \"q\"):\n answer = input(f\"Apply suggested changes to '{file_path}' [y/n/q]? \") # nosec\n answer = answer.lower()\n if answer in (\"no\", \"n\"):\n return False\n if answer in (\"quit\", \"q\"):\n sys.exit(1)\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 197, "project": "isort", "module": "isort.format", "class": "", "method": "create_terminal_printer", "focal_method_txt": "def create_terminal_printer(color: bool, output: Optional[TextIO] = None):\n if color and colorama_unavailable:\n no_colorama_message = (\n \"\\n\"\n \"Sorry, but to use --color (color_output) the colorama python package is required.\\n\\n\"\n \"Reference: https://pypi.org/project/colorama/\\n\\n\"\n \"You can either install it separately on your system or as the colors extra \"\n \"for isort. Ex: \\n\\n\"\n \"$ pip install isort[colors]\\n\"\n )\n print(no_colorama_message, file=sys.stderr)\n sys.exit(1)\n\n return ColoramaPrinter(output) if color else BasicPrinter(output)", "focal_method_lines": [136, 149], "in_stack": false, "globals": ["ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN"], "type_context": "import re\nimport sys\nfrom datetime import datetime\nfrom difflib import unified_diff\nfrom pathlib import Path\nfrom typing import Optional, TextIO\n\nADDED_LINE_PATTERN = re.compile(r\"\\+[^+]\")\nREMOVED_LINE_PATTERN = re.compile(r\"-[^-]\")\n\nclass BasicPrinter:\n\n ERROR = \"ERROR\"\n\n SUCCESS = \"SUCCESS\"\n\n def __init__(self, output: Optional[TextIO] = None):\n self.output = output or sys.stdout\n\nclass ColoramaPrinter(BasicPrinter):\n\n def __init__(self, output: Optional[TextIO] = None):\n super().__init__(output=output)\n\n # Note: this constants are instance variables instead ofs class variables\n # because they refer to colorama which might not be installed.\n self.ERROR = self.style_text(\"ERROR\", colorama.Fore.RED)\n self.SUCCESS = self.style_text(\"SUCCESS\", colorama.Fore.GREEN)\n self.ADDED_LINE = colorama.Fore.GREEN\n self.REMOVED_LINE = colorama.Fore.RED\n\ndef create_terminal_printer(color: bool, output: Optional[TextIO] = None):\n if color and colorama_unavailable:\n no_colorama_message = (\n \"\\n\"\n \"Sorry, but to use --color (color_output) the colorama python package is required.\\n\\n\"\n \"Reference: https://pypi.org/project/colorama/\\n\\n\"\n \"You can either install it separately on your system or as the colors extra \"\n \"for isort. Ex: \\n\\n\"\n \"$ pip install isort[colors]\\n\"\n )\n print(no_colorama_message, file=sys.stderr)\n sys.exit(1)\n\n return ColoramaPrinter(output) if color else BasicPrinter(output)", "has_branch": true, "total_branches": 2} {"prompt_id": 243, "project": "py_backwards", "module": "py_backwards.compiler", "class": "", "method": "compile_files", "focal_method_txt": "def compile_files(input_: str, output: str, target: CompilationTarget,\n root: Optional[str] = None) -> CompilationResult:\n \"\"\"Compiles all files from input_ to output.\"\"\"\n dependencies = set()\n start = time()\n count = 0\n for paths in get_input_output_paths(input_, output, root):\n count += 1\n dependencies.update(_compile_file(paths, target))\n return CompilationResult(count, time() - start, target,\n sorted(dependencies))", "focal_method_lines": [76, 85], "in_stack": false, "globals": [], "type_context": "from copy import deepcopy\nfrom time import time\nfrom traceback import format_exc\nfrom typing import List, Tuple, Optional\nfrom typed_ast import ast3 as ast\nfrom astunparse import unparse, dump\nfrom autopep8 import fix_code\nfrom .files import get_input_output_paths, InputOutput\nfrom .transformers import transformers\nfrom .types import CompilationTarget, CompilationResult\nfrom .exceptions import CompilationError, TransformationError\nfrom .utils.helpers import debug\n\n\n\ndef compile_files(input_: str, output: str, target: CompilationTarget,\n root: Optional[str] = None) -> CompilationResult:\n \"\"\"Compiles all files from input_ to output.\"\"\"\n dependencies = set()\n start = time()\n count = 0\n for paths in get_input_output_paths(input_, output, root):\n count += 1\n dependencies.update(_compile_file(paths, target))\n return CompilationResult(count, time() - start, target,\n sorted(dependencies))", "has_branch": true, "total_branches": 2} {"prompt_id": 244, "project": "py_backwards", "module": "py_backwards.conf", "class": "", "method": "init_settings", "focal_method_txt": "def init_settings(args: Namespace) -> None:\n if args.debug:\n settings.debug = True", "focal_method_lines": [11, 13], "in_stack": false, "globals": ["settings"], "type_context": "from argparse import Namespace\n\nsettings = Settings()\n\ndef init_settings(args: Namespace) -> None:\n if args.debug:\n settings.debug = True", "has_branch": true, "total_branches": 2} {"prompt_id": 245, "project": "py_backwards", "module": "py_backwards.files", "class": "", "method": "get_input_output_paths", "focal_method_txt": "def get_input_output_paths(input_: str, output: str,\n root: Optional[str]) -> Iterable[InputOutput]:\n \"\"\"Get input/output paths pairs.\"\"\"\n if output.endswith('.py') and not input_.endswith('.py'):\n raise InvalidInputOutput\n\n if not Path(input_).exists():\n raise InputDoesntExists\n\n if input_.endswith('.py'):\n if output.endswith('.py'):\n yield InputOutput(Path(input_), Path(output))\n else:\n input_path = Path(input_)\n if root is None:\n output_path = Path(output).joinpath(input_path.name)\n else:\n output_path = Path(output).joinpath(input_path.relative_to(root))\n yield InputOutput(input_path, output_path)\n else:\n output_path = Path(output)\n input_path = Path(input_)\n root_path = input_path if root is None else Path(root)\n for child_input in input_path.glob('**/*.py'):\n child_output = output_path.joinpath(\n child_input.relative_to(root_path))\n yield InputOutput(child_input, child_output)", "focal_method_lines": [11, 37], "in_stack": false, "globals": [], "type_context": "from typing import Iterable, Optional\nfrom .types import InputOutput\nfrom .exceptions import InvalidInputOutput, InputDoesntExists\n\n\n\ndef get_input_output_paths(input_: str, output: str,\n root: Optional[str]) -> Iterable[InputOutput]:\n \"\"\"Get input/output paths pairs.\"\"\"\n if output.endswith('.py') and not input_.endswith('.py'):\n raise InvalidInputOutput\n\n if not Path(input_).exists():\n raise InputDoesntExists\n\n if input_.endswith('.py'):\n if output.endswith('.py'):\n yield InputOutput(Path(input_), Path(output))\n else:\n input_path = Path(input_)\n if root is None:\n output_path = Path(output).joinpath(input_path.name)\n else:\n output_path = Path(output).joinpath(input_path.relative_to(root))\n yield InputOutput(input_path, output_path)\n else:\n output_path = Path(output)\n input_path = Path(input_)\n root_path = input_path if root is None else Path(root)\n for child_input in input_path.glob('**/*.py'):\n child_output = output_path.joinpath(\n child_input.relative_to(root_path))\n yield InputOutput(child_input, child_output)", "has_branch": true, "total_branches": 2} {"prompt_id": 246, "project": "py_backwards", "module": "py_backwards.main", "class": "", "method": "main", "focal_method_txt": "def main() -> int:\n parser = ArgumentParser(\n 'py-backwards',\n description='Python to python compiler that allows you to use some '\n 'Python 3.6 features in older versions.')\n parser.add_argument('-i', '--input', type=str, nargs='+', required=True,\n help='input file or folder')\n parser.add_argument('-o', '--output', type=str, required=True,\n help='output file or folder')\n parser.add_argument('-t', '--target', type=str,\n required=True, choices=const.TARGETS.keys(),\n help='target python version')\n parser.add_argument('-r', '--root', type=str, required=False,\n help='sources root')\n parser.add_argument('-d', '--debug', action='store_true', required=False,\n help='enable debug output')\n args = parser.parse_args()\n init_settings(args)\n\n try:\n for input_ in args.input:\n result = compile_files(input_, args.output,\n const.TARGETS[args.target],\n args.root)\n except exceptions.CompilationError as e:\n print(messages.syntax_error(e), file=sys.stderr)\n return 1\n except exceptions.TransformationError as e:\n print(messages.transformation_error(e), file=sys.stderr)\n return 1\n except exceptions.InputDoesntExists:\n print(messages.input_doesnt_exists(args.input), file=sys.stderr)\n return 1\n except exceptions.InvalidInputOutput:\n print(messages.invalid_output(args.input, args.output),\n file=sys.stderr)\n return 1\n except PermissionError:\n print(messages.permission_error(args.output), file=sys.stderr)\n return 1\n\n print(messages.compilation_result(result))\n return 0", "focal_method_lines": [11, 53], "in_stack": false, "globals": [], "type_context": "from colorama import init\nfrom argparse import ArgumentParser\nimport sys\nfrom .compiler import compile_files\nfrom .conf import init_settings\nfrom . import const, messages, exceptions\n\n\n\ndef main() -> int:\n parser = ArgumentParser(\n 'py-backwards',\n description='Python to python compiler that allows you to use some '\n 'Python 3.6 features in older versions.')\n parser.add_argument('-i', '--input', type=str, nargs='+', required=True,\n help='input file or folder')\n parser.add_argument('-o', '--output', type=str, required=True,\n help='output file or folder')\n parser.add_argument('-t', '--target', type=str,\n required=True, choices=const.TARGETS.keys(),\n help='target python version')\n parser.add_argument('-r', '--root', type=str, required=False,\n help='sources root')\n parser.add_argument('-d', '--debug', action='store_true', required=False,\n help='enable debug output')\n args = parser.parse_args()\n init_settings(args)\n\n try:\n for input_ in args.input:\n result = compile_files(input_, args.output,\n const.TARGETS[args.target],\n args.root)\n except exceptions.CompilationError as e:\n print(messages.syntax_error(e), file=sys.stderr)\n return 1\n except exceptions.TransformationError as e:\n print(messages.transformation_error(e), file=sys.stderr)\n return 1\n except exceptions.InputDoesntExists:\n print(messages.input_doesnt_exists(args.input), file=sys.stderr)\n return 1\n except exceptions.InvalidInputOutput:\n print(messages.invalid_output(args.input, args.output),\n file=sys.stderr)\n return 1\n except PermissionError:\n print(messages.permission_error(args.output), file=sys.stderr)\n return 1\n\n print(messages.compilation_result(result))\n return 0", "has_branch": true, "total_branches": 2} {"prompt_id": 247, "project": "py_backwards", "module": "py_backwards.transformers.base", "class": "BaseImportRewrite", "method": "visit_Import", "focal_method_txt": " def visit_Import(self, node: ast.Import) -> Union[ast.Import, ast.Try]:\n rewrite = self._get_matched_rewrite(node.names[0].name)\n if rewrite:\n return self._replace_import(node, *rewrite)\n\n return self.generic_visit(node)", "focal_method_lines": [67, 72], "in_stack": false, "globals": [], "type_context": "from abc import ABCMeta, abstractmethod\nfrom typing import List, Tuple, Union, Optional, Iterable, Dict\nfrom typed_ast import ast3 as ast\nfrom ..types import CompilationTarget, TransformationResult\nfrom ..utils.snippet import snippet, extend\n\n\n\nclass BaseImportRewrite(BaseNodeTransformer):\n\n rewrites = []\n\n def visit_Import(self, node: ast.Import) -> Union[ast.Import, ast.Try]:\n rewrite = self._get_matched_rewrite(node.names[0].name)\n if rewrite:\n return self._replace_import(node, *rewrite)\n\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 248, "project": "py_backwards", "module": "py_backwards.transformers.base", "class": "BaseImportRewrite", "method": "visit_ImportFrom", "focal_method_txt": " def visit_ImportFrom(self, node: ast.ImportFrom) -> Union[ast.ImportFrom, ast.Try]:\n rewrite = self._get_matched_rewrite(node.module)\n if rewrite:\n return self._replace_import_from_module(node, *rewrite)\n\n names_to_replace = dict(self._get_names_to_replace(node))\n if names_to_replace:\n return self._replace_import_from_names(node, names_to_replace)\n\n return self.generic_visit(node)", "focal_method_lines": [126, 135], "in_stack": false, "globals": [], "type_context": "from abc import ABCMeta, abstractmethod\nfrom typing import List, Tuple, Union, Optional, Iterable, Dict\nfrom typed_ast import ast3 as ast\nfrom ..types import CompilationTarget, TransformationResult\nfrom ..utils.snippet import snippet, extend\n\n\n\nclass BaseImportRewrite(BaseNodeTransformer):\n\n rewrites = []\n\n def visit_ImportFrom(self, node: ast.ImportFrom) -> Union[ast.ImportFrom, ast.Try]:\n rewrite = self._get_matched_rewrite(node.module)\n if rewrite:\n return self._replace_import_from_module(node, *rewrite)\n\n names_to_replace = dict(self._get_names_to_replace(node))\n if names_to_replace:\n return self._replace_import_from_names(node, names_to_replace)\n\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 249, "project": "py_backwards", "module": "py_backwards.transformers.dict_unpacking", "class": "DictUnpackingTransformer", "method": "visit_Module", "focal_method_txt": " def visit_Module(self, node: ast.Module) -> ast.Module:\n insert_at(0, node, merge_dicts.get_body()) # type: ignore\n return self.generic_visit(node)", "focal_method_lines": [66, 68], "in_stack": false, "globals": ["Splitted", "Pair"], "type_context": "from typing import Union, Iterable, Optional, List, Tuple\nfrom typed_ast import ast3 as ast\nfrom ..utils.tree import insert_at\nfrom ..utils.snippet import snippet\nfrom .base import BaseNodeTransformer\n\nSplitted = List[Union[List[Tuple[ast.expr, ast.expr]], ast.expr]]\nPair = Tuple[Optional[ast.expr], ast.expr]\n\nclass DictUnpackingTransformer(BaseNodeTransformer):\n\n target = (3, 4)\n\n def visit_Module(self, node: ast.Module) -> ast.Module:\n insert_at(0, node, merge_dicts.get_body()) # type: ignore\n return self.generic_visit(node)", "has_branch": false, "total_branches": 0} {"prompt_id": 250, "project": "py_backwards", "module": "py_backwards.transformers.dict_unpacking", "class": "DictUnpackingTransformer", "method": "visit_Dict", "focal_method_txt": " def visit_Dict(self, node: ast.Dict) -> Union[ast.Dict, ast.Call]:\n if None not in node.keys:\n return self.generic_visit(node) # type: ignore\n\n self._tree_changed = True\n pairs = zip(node.keys, node.values)\n splitted = self._split_by_None(pairs)\n prepared = self._prepare_splitted(splitted)\n return self._merge_dicts(prepared)", "focal_method_lines": [70, 78], "in_stack": false, "globals": ["Splitted", "Pair"], "type_context": "from typing import Union, Iterable, Optional, List, Tuple\nfrom typed_ast import ast3 as ast\nfrom ..utils.tree import insert_at\nfrom ..utils.snippet import snippet\nfrom .base import BaseNodeTransformer\n\nSplitted = List[Union[List[Tuple[ast.expr, ast.expr]], ast.expr]]\nPair = Tuple[Optional[ast.expr], ast.expr]\n\nclass DictUnpackingTransformer(BaseNodeTransformer):\n\n target = (3, 4)\n\n def visit_Dict(self, node: ast.Dict) -> Union[ast.Dict, ast.Call]:\n if None not in node.keys:\n return self.generic_visit(node) # type: ignore\n\n self._tree_changed = True\n pairs = zip(node.keys, node.values)\n splitted = self._split_by_None(pairs)\n prepared = self._prepare_splitted(splitted)\n return self._merge_dicts(prepared)", "has_branch": true, "total_branches": 2} {"prompt_id": 251, "project": "py_backwards", "module": "py_backwards.transformers.metaclass", "class": "MetaclassTransformer", "method": "visit_Module", "focal_method_txt": " def visit_Module(self, node: ast.Module) -> ast.Module:\n insert_at(0, node, six_import.get_body())\n return self.generic_visit(node)", "focal_method_lines": [27, 29], "in_stack": false, "globals": [], "type_context": "from typed_ast import ast3 as ast\nfrom ..utils.snippet import snippet\nfrom ..utils.tree import insert_at\nfrom .base import BaseNodeTransformer\n\n\n\nclass MetaclassTransformer(BaseNodeTransformer):\n\n target = (2, 7)\n\n dependencies = ['six']\n\n def visit_Module(self, node: ast.Module) -> ast.Module:\n insert_at(0, node, six_import.get_body())\n return self.generic_visit(node)", "has_branch": false, "total_branches": 0} {"prompt_id": 252, "project": "py_backwards", "module": "py_backwards.transformers.metaclass", "class": "MetaclassTransformer", "method": "visit_ClassDef", "focal_method_txt": " def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:\n if node.keywords:\n metaclass = node.keywords[0].value\n node.bases = class_bases.get_body(metaclass=metaclass, # type: ignore\n bases=ast.List(elts=node.bases))\n node.keywords = []\n self._tree_changed = True\n\n return self.generic_visit(node)", "focal_method_lines": [31, 39], "in_stack": false, "globals": [], "type_context": "from typed_ast import ast3 as ast\nfrom ..utils.snippet import snippet\nfrom ..utils.tree import insert_at\nfrom .base import BaseNodeTransformer\n\n\n\nclass MetaclassTransformer(BaseNodeTransformer):\n\n target = (2, 7)\n\n dependencies = ['six']\n\n def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:\n if node.keywords:\n metaclass = node.keywords[0].value\n node.bases = class_bases.get_body(metaclass=metaclass, # type: ignore\n bases=ast.List(elts=node.bases))\n node.keywords = []\n self._tree_changed = True\n\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 253, "project": "py_backwards", "module": "py_backwards.transformers.python2_future", "class": "Python2FutureTransformer", "method": "visit_Module", "focal_method_txt": " def visit_Module(self, node: ast.Module) -> ast.Module:\n self._tree_changed = True\n node.body = imports.get_body(future='__future__') + node.body # type: ignore\n return self.generic_visit(node)", "focal_method_lines": [23, 26], "in_stack": false, "globals": [], "type_context": "from typed_ast import ast3 as ast\nfrom ..utils.snippet import snippet\nfrom .base import BaseNodeTransformer\n\n\n\nclass Python2FutureTransformer(BaseNodeTransformer):\n\n target = (2, 7)\n\n def visit_Module(self, node: ast.Module) -> ast.Module:\n self._tree_changed = True\n node.body = imports.get_body(future='__future__') + node.body # type: ignore\n return self.generic_visit(node)", "has_branch": false, "total_branches": 0} {"prompt_id": 254, "project": "py_backwards", "module": "py_backwards.transformers.return_from_generator", "class": "ReturnFromGeneratorTransformer", "method": "visit_FunctionDef", "focal_method_txt": " def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:\n generator_returns = self._find_generator_returns(node)\n\n if generator_returns:\n self._tree_changed = True\n\n for parent, return_ in generator_returns:\n self._replace_return(parent, return_)\n\n return self.generic_visit(node)", "focal_method_lines": [63, 72], "in_stack": false, "globals": [], "type_context": "from typing import List, Tuple, Any\nfrom typed_ast import ast3 as ast\nfrom ..utils.snippet import snippet, let\nfrom .base import BaseNodeTransformer\n\n\n\nclass ReturnFromGeneratorTransformer(BaseNodeTransformer):\n\n target = (3, 2)\n\n def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:\n generator_returns = self._find_generator_returns(node)\n\n if generator_returns:\n self._tree_changed = True\n\n for parent, return_ in generator_returns:\n self._replace_return(parent, return_)\n\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 255, "project": "py_backwards", "module": "py_backwards.transformers.six_moves", "class": "MovedAttribute", "method": "__init__", "focal_method_txt": " def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n self.name = name\n if new_mod is None:\n new_mod = name\n self.new_mod = new_mod\n if new_attr is None:\n if old_attr is None:\n new_attr = name\n else:\n new_attr = old_attr\n self.new_attr = new_attr", "focal_method_lines": [7, 17], "in_stack": false, "globals": ["_moved_attributes", "_urllib_parse_moved_attributes", "_urllib_error_moved_attributes", "_urllib_request_moved_attributes", "_urllib_response_moved_attributes", "_urllib_robotparser_moved_attributes", "prefixed_moves"], "type_context": "from ..utils.helpers import eager\nfrom .base import BaseImportRewrite\n\n_moved_attributes = [\n MovedAttribute(\"cStringIO\", \"cStringIO\", \"io\", \"StringIO\"),\n MovedAttribute(\"filter\", \"itertools\", \"builtins\", \"ifilter\", \"filter\"),\n MovedAttribute(\"filterfalse\", \"itertools\", \"itertools\", \"ifilterfalse\", \"filterfalse\"),\n MovedAttribute(\"input\", \"__builtin__\", \"builtins\", \"raw_input\", \"input\"),\n MovedAttribute(\"intern\", \"__builtin__\", \"sys\"),\n MovedAttribute(\"map\", \"itertools\", \"builtins\", \"imap\", \"map\"),\n MovedAttribute(\"getcwd\", \"os\", \"os\", \"getcwdu\", \"getcwd\"),\n MovedAttribute(\"getcwdb\", \"os\", \"os\", \"getcwd\", \"getcwdb\"),\n MovedAttribute(\"getstatusoutput\", \"commands\", \"subprocess\"),\n MovedAttribute(\"getoutput\", \"commands\", \"subprocess\"),\n MovedAttribute(\"range\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n MovedAttribute(\"reload_module\", \"__builtin__\", \"imp\", \"reload\"),\n MovedAttribute(\"reload_module\", \"__builtin__\", \"importlib\", \"reload\"),\n MovedAttribute(\"reduce\", \"__builtin__\", \"functools\"),\n MovedAttribute(\"shlex_quote\", \"pipes\", \"shlex\", \"quote\"),\n MovedAttribute(\"StringIO\", \"StringIO\", \"io\"),\n MovedAttribute(\"UserDict\", \"UserDict\", \"collections\"),\n MovedAttribute(\"UserList\", \"UserList\", \"collections\"),\n MovedAttribute(\"UserString\", \"UserString\", \"collections\"),\n MovedAttribute(\"xrange\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n MovedAttribute(\"zip\", \"itertools\", \"builtins\", \"izip\", \"zip\"),\n MovedAttribute(\"zip_longest\", \"itertools\", \"itertools\", \"izip_longest\", \"zip_longest\"),\n MovedModule(\"builtins\", \"__builtin__\"),\n MovedModule(\"configparser\", \"ConfigParser\"),\n MovedModule(\"copyreg\", \"copy_reg\"),\n MovedModule(\"dbm_gnu\", \"gdbm\", \"dbm.gnu\"),\n MovedModule(\"_dummy_thread\", \"dummy_thread\", \"_dummy_thread\"),\n MovedModule(\"http_cookiejar\", \"cookielib\", \"http.cookiejar\"),\n MovedModule(\"http_cookies\", \"Cookie\", \"http.cookies\"),\n MovedModule(\"html_entities\", \"htmlentitydefs\", \"html.entities\"),\n MovedModule(\"html_parser\", \"HTMLParser\", \"html.parser\"),\n MovedModule(\"http_client\", \"httplib\", \"http.client\"),\n MovedModule(\"email_mime_base\", \"email.MIMEBase\", \"email.mime.base\"),\n MovedModule(\"email_mime_image\", \"email.MIMEImage\", \"email.mime.image\"),\n MovedModule(\"email_mime_multipart\", \"email.MIMEMultipart\", \"email.mime.multipart\"),\n MovedModule(\"email_mime_nonmultipart\", \"email.MIMENonMultipart\", \"email.mime.nonmultipart\"),\n MovedModule(\"email_mime_text\", \"email.MIMEText\", \"email.mime.text\"),\n MovedModule(\"BaseHTTPServer\", \"BaseHTTPServer\", \"http.server\"),\n MovedModule(\"CGIHTTPServer\", \"CGIHTTPServer\", \"http.server\"),\n MovedModule(\"SimpleHTTPServer\", \"SimpleHTTPServer\", \"http.server\"),\n MovedModule(\"cPickle\", \"cPickle\", \"pickle\"),\n MovedModule(\"queue\", \"Queue\"),\n MovedModule(\"reprlib\", \"repr\"),\n MovedModule(\"socketserver\", \"SocketServer\"),\n MovedModule(\"_thread\", \"thread\", \"_thread\"),\n MovedModule(\"tkinter\", \"Tkinter\"),\n MovedModule(\"tkinter_dialog\", \"Dialog\", \"tkinter.dialog\"),\n MovedModule(\"tkinter_filedialog\", \"FileDialog\", \"tkinter.filedialog\"),\n MovedModule(\"tkinter_scrolledtext\", \"ScrolledText\", \"tkinter.scrolledtext\"),\n MovedModule(\"tkinter_simpledialog\", \"SimpleDialog\", \"tkinter.simpledialog\"),\n MovedModule(\"tkinter_tix\", \"Tix\", \"tkinter.tix\"),\n MovedModule(\"tkinter_ttk\", \"ttk\", \"tkinter.ttk\"),\n MovedModule(\"tkinter_constants\", \"Tkconstants\", \"tkinter.constants\"),\n MovedModule(\"tkinter_dnd\", \"Tkdnd\", \"tkinter.dnd\"),\n MovedModule(\"tkinter_colorchooser\", \"tkColorChooser\",\n \"tkinter.colorchooser\"),\n MovedModule(\"tkinter_commondialog\", \"tkCommonDialog\",\n \"tkinter.commondialog\"),\n MovedModule(\"tkinter_tkfiledialog\", \"tkFileDialog\", \"tkinter.filedialog\"),\n MovedModule(\"tkinter_font\", \"tkFont\", \"tkinter.font\"),\n MovedModule(\"tkinter_messagebox\", \"tkMessageBox\", \"tkinter.messagebox\"),\n MovedModule(\"tkinter_tksimpledialog\", \"tkSimpleDialog\",\n \"tkinter.simpledialog\"),\n MovedModule(\"urllib_parse\", __name__ + \".moves.urllib_parse\", \"urllib.parse\"),\n MovedModule(\"urllib_error\", __name__ + \".moves.urllib_error\", \"urllib.error\"),\n MovedModule(\"urllib\", __name__ + \".moves.urllib\", __name__ + \".moves.urllib\"),\n MovedModule(\"urllib_robotparser\", \"robotparser\", \"urllib.robotparser\"),\n MovedModule(\"xmlrpc_client\", \"xmlrpclib\", \"xmlrpc.client\"),\n MovedModule(\"xmlrpc_server\", \"SimpleXMLRPCServer\", \"xmlrpc.server\"),\n]\n_urllib_parse_moved_attributes = [\n MovedAttribute(\"ParseResult\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"SplitResult\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"parse_qs\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"parse_qsl\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urldefrag\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urljoin\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlparse\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlsplit\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlunparse\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlunsplit\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"quote\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"quote_plus\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote_plus\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote_to_bytes\", \"urllib\", \"urllib.parse\", \"unquote\", \"unquote_to_bytes\"),\n MovedAttribute(\"urlencode\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splitquery\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splittag\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splituser\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splitvalue\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"uses_fragment\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_netloc\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_params\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_query\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_relative\", \"urlparse\", \"urllib.parse\"),\n]\n_urllib_error_moved_attributes = [\n MovedAttribute(\"URLError\", \"urllib2\", \"urllib.error\"),\n MovedAttribute(\"HTTPError\", \"urllib2\", \"urllib.error\"),\n MovedAttribute(\"ContentTooShortError\", \"urllib\", \"urllib.error\"),\n]\n_urllib_request_moved_attributes = [\n MovedAttribute(\"urlopen\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"install_opener\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"build_opener\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"pathname2url\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"url2pathname\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"getproxies\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"Request\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"OpenerDirector\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPDefaultErrorHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPRedirectHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPCookieProcessor\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"BaseHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPPasswordMgr\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPPasswordMgrWithDefaultRealm\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"AbstractBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"AbstractDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPSHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"FileHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"FTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"CacheFTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"UnknownHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPErrorProcessor\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"urlretrieve\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"urlcleanup\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"URLopener\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"FancyURLopener\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"proxy_bypass\", \"urllib\", \"urllib.request\"),\n]\n_urllib_response_moved_attributes = [\n MovedAttribute(\"addbase\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addclosehook\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addinfo\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addinfourl\", \"urllib\", \"urllib.response\"),\n]\n_urllib_robotparser_moved_attributes = [\n MovedAttribute(\"RobotFileParser\", \"robotparser\", \"urllib.robotparser\"),\n]\nprefixed_moves = [('', _moved_attributes),\n ('.urllib.parse', _urllib_parse_moved_attributes),\n ('.urllib.error', _urllib_error_moved_attributes),\n ('.urllib.request', _urllib_request_moved_attributes),\n ('.urllib.response', _urllib_response_moved_attributes),\n ('.urllib.robotparser', _urllib_robotparser_moved_attributes)]\n\nclass MovedAttribute:\n\n def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n self.name = name\n if new_mod is None:\n new_mod = name\n self.new_mod = new_mod\n if new_attr is None:\n if old_attr is None:\n new_attr = name\n else:\n new_attr = old_attr\n self.new_attr = new_attr", "has_branch": true, "total_branches": 2} {"prompt_id": 256, "project": "py_backwards", "module": "py_backwards.transformers.six_moves", "class": "MovedModule", "method": "__init__", "focal_method_txt": " def __init__(self, name, old, new=None):\n self.name = name\n if new is None:\n new = name\n self.new = new", "focal_method_lines": [21, 25], "in_stack": false, "globals": ["_moved_attributes", "_urllib_parse_moved_attributes", "_urllib_error_moved_attributes", "_urllib_request_moved_attributes", "_urllib_response_moved_attributes", "_urllib_robotparser_moved_attributes", "prefixed_moves"], "type_context": "from ..utils.helpers import eager\nfrom .base import BaseImportRewrite\n\n_moved_attributes = [\n MovedAttribute(\"cStringIO\", \"cStringIO\", \"io\", \"StringIO\"),\n MovedAttribute(\"filter\", \"itertools\", \"builtins\", \"ifilter\", \"filter\"),\n MovedAttribute(\"filterfalse\", \"itertools\", \"itertools\", \"ifilterfalse\", \"filterfalse\"),\n MovedAttribute(\"input\", \"__builtin__\", \"builtins\", \"raw_input\", \"input\"),\n MovedAttribute(\"intern\", \"__builtin__\", \"sys\"),\n MovedAttribute(\"map\", \"itertools\", \"builtins\", \"imap\", \"map\"),\n MovedAttribute(\"getcwd\", \"os\", \"os\", \"getcwdu\", \"getcwd\"),\n MovedAttribute(\"getcwdb\", \"os\", \"os\", \"getcwd\", \"getcwdb\"),\n MovedAttribute(\"getstatusoutput\", \"commands\", \"subprocess\"),\n MovedAttribute(\"getoutput\", \"commands\", \"subprocess\"),\n MovedAttribute(\"range\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n MovedAttribute(\"reload_module\", \"__builtin__\", \"imp\", \"reload\"),\n MovedAttribute(\"reload_module\", \"__builtin__\", \"importlib\", \"reload\"),\n MovedAttribute(\"reduce\", \"__builtin__\", \"functools\"),\n MovedAttribute(\"shlex_quote\", \"pipes\", \"shlex\", \"quote\"),\n MovedAttribute(\"StringIO\", \"StringIO\", \"io\"),\n MovedAttribute(\"UserDict\", \"UserDict\", \"collections\"),\n MovedAttribute(\"UserList\", \"UserList\", \"collections\"),\n MovedAttribute(\"UserString\", \"UserString\", \"collections\"),\n MovedAttribute(\"xrange\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n MovedAttribute(\"zip\", \"itertools\", \"builtins\", \"izip\", \"zip\"),\n MovedAttribute(\"zip_longest\", \"itertools\", \"itertools\", \"izip_longest\", \"zip_longest\"),\n MovedModule(\"builtins\", \"__builtin__\"),\n MovedModule(\"configparser\", \"ConfigParser\"),\n MovedModule(\"copyreg\", \"copy_reg\"),\n MovedModule(\"dbm_gnu\", \"gdbm\", \"dbm.gnu\"),\n MovedModule(\"_dummy_thread\", \"dummy_thread\", \"_dummy_thread\"),\n MovedModule(\"http_cookiejar\", \"cookielib\", \"http.cookiejar\"),\n MovedModule(\"http_cookies\", \"Cookie\", \"http.cookies\"),\n MovedModule(\"html_entities\", \"htmlentitydefs\", \"html.entities\"),\n MovedModule(\"html_parser\", \"HTMLParser\", \"html.parser\"),\n MovedModule(\"http_client\", \"httplib\", \"http.client\"),\n MovedModule(\"email_mime_base\", \"email.MIMEBase\", \"email.mime.base\"),\n MovedModule(\"email_mime_image\", \"email.MIMEImage\", \"email.mime.image\"),\n MovedModule(\"email_mime_multipart\", \"email.MIMEMultipart\", \"email.mime.multipart\"),\n MovedModule(\"email_mime_nonmultipart\", \"email.MIMENonMultipart\", \"email.mime.nonmultipart\"),\n MovedModule(\"email_mime_text\", \"email.MIMEText\", \"email.mime.text\"),\n MovedModule(\"BaseHTTPServer\", \"BaseHTTPServer\", \"http.server\"),\n MovedModule(\"CGIHTTPServer\", \"CGIHTTPServer\", \"http.server\"),\n MovedModule(\"SimpleHTTPServer\", \"SimpleHTTPServer\", \"http.server\"),\n MovedModule(\"cPickle\", \"cPickle\", \"pickle\"),\n MovedModule(\"queue\", \"Queue\"),\n MovedModule(\"reprlib\", \"repr\"),\n MovedModule(\"socketserver\", \"SocketServer\"),\n MovedModule(\"_thread\", \"thread\", \"_thread\"),\n MovedModule(\"tkinter\", \"Tkinter\"),\n MovedModule(\"tkinter_dialog\", \"Dialog\", \"tkinter.dialog\"),\n MovedModule(\"tkinter_filedialog\", \"FileDialog\", \"tkinter.filedialog\"),\n MovedModule(\"tkinter_scrolledtext\", \"ScrolledText\", \"tkinter.scrolledtext\"),\n MovedModule(\"tkinter_simpledialog\", \"SimpleDialog\", \"tkinter.simpledialog\"),\n MovedModule(\"tkinter_tix\", \"Tix\", \"tkinter.tix\"),\n MovedModule(\"tkinter_ttk\", \"ttk\", \"tkinter.ttk\"),\n MovedModule(\"tkinter_constants\", \"Tkconstants\", \"tkinter.constants\"),\n MovedModule(\"tkinter_dnd\", \"Tkdnd\", \"tkinter.dnd\"),\n MovedModule(\"tkinter_colorchooser\", \"tkColorChooser\",\n \"tkinter.colorchooser\"),\n MovedModule(\"tkinter_commondialog\", \"tkCommonDialog\",\n \"tkinter.commondialog\"),\n MovedModule(\"tkinter_tkfiledialog\", \"tkFileDialog\", \"tkinter.filedialog\"),\n MovedModule(\"tkinter_font\", \"tkFont\", \"tkinter.font\"),\n MovedModule(\"tkinter_messagebox\", \"tkMessageBox\", \"tkinter.messagebox\"),\n MovedModule(\"tkinter_tksimpledialog\", \"tkSimpleDialog\",\n \"tkinter.simpledialog\"),\n MovedModule(\"urllib_parse\", __name__ + \".moves.urllib_parse\", \"urllib.parse\"),\n MovedModule(\"urllib_error\", __name__ + \".moves.urllib_error\", \"urllib.error\"),\n MovedModule(\"urllib\", __name__ + \".moves.urllib\", __name__ + \".moves.urllib\"),\n MovedModule(\"urllib_robotparser\", \"robotparser\", \"urllib.robotparser\"),\n MovedModule(\"xmlrpc_client\", \"xmlrpclib\", \"xmlrpc.client\"),\n MovedModule(\"xmlrpc_server\", \"SimpleXMLRPCServer\", \"xmlrpc.server\"),\n]\n_urllib_parse_moved_attributes = [\n MovedAttribute(\"ParseResult\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"SplitResult\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"parse_qs\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"parse_qsl\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urldefrag\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urljoin\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlparse\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlsplit\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlunparse\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"urlunsplit\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"quote\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"quote_plus\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote_plus\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"unquote_to_bytes\", \"urllib\", \"urllib.parse\", \"unquote\", \"unquote_to_bytes\"),\n MovedAttribute(\"urlencode\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splitquery\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splittag\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splituser\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"splitvalue\", \"urllib\", \"urllib.parse\"),\n MovedAttribute(\"uses_fragment\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_netloc\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_params\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_query\", \"urlparse\", \"urllib.parse\"),\n MovedAttribute(\"uses_relative\", \"urlparse\", \"urllib.parse\"),\n]\n_urllib_error_moved_attributes = [\n MovedAttribute(\"URLError\", \"urllib2\", \"urllib.error\"),\n MovedAttribute(\"HTTPError\", \"urllib2\", \"urllib.error\"),\n MovedAttribute(\"ContentTooShortError\", \"urllib\", \"urllib.error\"),\n]\n_urllib_request_moved_attributes = [\n MovedAttribute(\"urlopen\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"install_opener\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"build_opener\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"pathname2url\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"url2pathname\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"getproxies\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"Request\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"OpenerDirector\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPDefaultErrorHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPRedirectHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPCookieProcessor\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"BaseHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPPasswordMgr\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPPasswordMgrWithDefaultRealm\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"AbstractBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"AbstractDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"ProxyDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPSHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"FileHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"FTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"CacheFTPHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"UnknownHandler\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"HTTPErrorProcessor\", \"urllib2\", \"urllib.request\"),\n MovedAttribute(\"urlretrieve\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"urlcleanup\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"URLopener\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"FancyURLopener\", \"urllib\", \"urllib.request\"),\n MovedAttribute(\"proxy_bypass\", \"urllib\", \"urllib.request\"),\n]\n_urllib_response_moved_attributes = [\n MovedAttribute(\"addbase\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addclosehook\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addinfo\", \"urllib\", \"urllib.response\"),\n MovedAttribute(\"addinfourl\", \"urllib\", \"urllib.response\"),\n]\n_urllib_robotparser_moved_attributes = [\n MovedAttribute(\"RobotFileParser\", \"robotparser\", \"urllib.robotparser\"),\n]\nprefixed_moves = [('', _moved_attributes),\n ('.urllib.parse', _urllib_parse_moved_attributes),\n ('.urllib.error', _urllib_error_moved_attributes),\n ('.urllib.request', _urllib_request_moved_attributes),\n ('.urllib.response', _urllib_response_moved_attributes),\n ('.urllib.robotparser', _urllib_robotparser_moved_attributes)]\n\nclass MovedModule:\n\n def __init__(self, name, old, new=None):\n self.name = name\n if new is None:\n new = name\n self.new = new", "has_branch": true, "total_branches": 2} {"prompt_id": 257, "project": "py_backwards", "module": "py_backwards.transformers.starred_unpacking", "class": "StarredUnpackingTransformer", "method": "visit_List", "focal_method_txt": " def visit_List(self, node: ast.List) -> ast.List:\n if not self._has_starred(node.elts):\n return self.generic_visit(node) # type: ignore\n\n self._tree_changed = True\n\n return self.generic_visit(self._to_sum_of_lists(node.elts))", "focal_method_lines": [65, 71], "in_stack": false, "globals": ["Splitted", "ListEntry"], "type_context": "from typing import Union, Iterable, List\nfrom typed_ast import ast3 as ast\nfrom .base import BaseNodeTransformer\n\nSplitted = Union[List[ast.expr], ast.Starred]\nListEntry = Union[ast.Call, ast.List]\n\nclass StarredUnpackingTransformer(BaseNodeTransformer):\n\n target = (3, 4)\n\n def visit_List(self, node: ast.List) -> ast.List:\n if not self._has_starred(node.elts):\n return self.generic_visit(node) # type: ignore\n\n self._tree_changed = True\n\n return self.generic_visit(self._to_sum_of_lists(node.elts))", "has_branch": true, "total_branches": 2} {"prompt_id": 258, "project": "py_backwards", "module": "py_backwards.transformers.starred_unpacking", "class": "StarredUnpackingTransformer", "method": "visit_Call", "focal_method_txt": " def visit_Call(self, node: ast.Call) -> ast.Call:\n if not self._has_starred(node.args):\n return self.generic_visit(self.generic_visit(node)) # type: ignore\n\n self._tree_changed = True\n\n args = self._to_sum_of_lists(node.args)\n node.args = [ast.Starred(value=args)]\n return self.generic_visit(node)", "focal_method_lines": [73, 81], "in_stack": false, "globals": ["Splitted", "ListEntry"], "type_context": "from typing import Union, Iterable, List\nfrom typed_ast import ast3 as ast\nfrom .base import BaseNodeTransformer\n\nSplitted = Union[List[ast.expr], ast.Starred]\nListEntry = Union[ast.Call, ast.List]\n\nclass StarredUnpackingTransformer(BaseNodeTransformer):\n\n target = (3, 4)\n\n def visit_Call(self, node: ast.Call) -> ast.Call:\n if not self._has_starred(node.args):\n return self.generic_visit(self.generic_visit(node)) # type: ignore\n\n self._tree_changed = True\n\n args = self._to_sum_of_lists(node.args)\n node.args = [ast.Starred(value=args)]\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 259, "project": "py_backwards", "module": "py_backwards.transformers.super_without_arguments", "class": "SuperWithoutArgumentsTransformer", "method": "visit_Call", "focal_method_txt": " def visit_Call(self, node: ast.Call) -> ast.Call:\n if isinstance(node.func, ast.Name) and node.func.id == 'super' and not len(node.args):\n self._replace_super_args(node)\n self._tree_changed = True\n\n return self.generic_visit(node)", "focal_method_lines": [32, 37], "in_stack": false, "globals": [], "type_context": "from typed_ast import ast3 as ast\nfrom ..utils.tree import get_closest_parent_of\nfrom ..utils.helpers import warn\nfrom ..exceptions import NodeNotFound\nfrom .base import BaseNodeTransformer\n\n\n\nclass SuperWithoutArgumentsTransformer(BaseNodeTransformer):\n\n target = (2, 7)\n\n def visit_Call(self, node: ast.Call) -> ast.Call:\n if isinstance(node.func, ast.Name) and node.func.id == 'super' and not len(node.args):\n self._replace_super_args(node)\n self._tree_changed = True\n\n return self.generic_visit(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 260, "project": "py_backwards", "module": "py_backwards.utils.helpers", "class": "", "method": "eager", "focal_method_txt": "def eager(fn: Callable[..., Iterable[T]]) -> Callable[..., List[T]]:\n @wraps(fn)\n def wrapped(*args: Any, **kwargs: Any) -> List[T]:\n return list(fn(*args, **kwargs))\n\n return wrapped", "focal_method_lines": [11, 16], "in_stack": false, "globals": ["T"], "type_context": "from inspect import getsource\nimport re\nimport sys\nfrom typing import Any, Callable, Iterable, List, TypeVar\nfrom functools import wraps\nfrom ..conf import settings\nfrom .. import messages\n\nT = TypeVar('T')\n\ndef eager(fn: Callable[..., Iterable[T]]) -> Callable[..., List[T]]:\n @wraps(fn)\n def wrapped(*args: Any, **kwargs: Any) -> List[T]:\n return list(fn(*args, **kwargs))\n\n return wrapped", "has_branch": false, "total_branches": 0} {"prompt_id": 261, "project": "py_backwards", "module": "py_backwards.utils.helpers", "class": "", "method": "get_source", "focal_method_txt": "def get_source(fn: Callable[..., Any]) -> str:\n \"\"\"Returns source code of the function.\"\"\"\n source_lines = getsource(fn).split('\\n')\n padding = len(re.findall(r'^(\\s*)', source_lines[0])[0])\n return '\\n'.join(line[padding:] for line in source_lines)", "focal_method_lines": [31, 35], "in_stack": false, "globals": ["T"], "type_context": "from inspect import getsource\nimport re\nimport sys\nfrom typing import Any, Callable, Iterable, List, TypeVar\nfrom functools import wraps\nfrom ..conf import settings\nfrom .. import messages\n\nT = TypeVar('T')\n\ndef get_source(fn: Callable[..., Any]) -> str:\n \"\"\"Returns source code of the function.\"\"\"\n source_lines = getsource(fn).split('\\n')\n padding = len(re.findall(r'^(\\s*)', source_lines[0])[0])\n return '\\n'.join(line[padding:] for line in source_lines)", "has_branch": false, "total_branches": 0} {"prompt_id": 262, "project": "py_backwards", "module": "py_backwards.utils.helpers", "class": "", "method": "debug", "focal_method_txt": "def debug(get_message: Callable[[], str]) -> None:\n if settings.debug:\n print(messages.debug(get_message()), file=sys.stderr)", "focal_method_lines": [42, 44], "in_stack": false, "globals": ["T"], "type_context": "from inspect import getsource\nimport re\nimport sys\nfrom typing import Any, Callable, Iterable, List, TypeVar\nfrom functools import wraps\nfrom ..conf import settings\nfrom .. import messages\n\nT = TypeVar('T')\n\ndef debug(get_message: Callable[[], str]) -> None:\n if settings.debug:\n print(messages.debug(get_message()), file=sys.stderr)", "has_branch": true, "total_branches": 2} {"prompt_id": 263, "project": "py_backwards", "module": "py_backwards.utils.snippet", "class": "", "method": "extend_tree", "focal_method_txt": "def extend_tree(tree: ast.AST, variables: Dict[str, Variable]) -> None:\n for node in find(tree, ast.Call):\n if isinstance(node.func, ast.Name) and node.func.id == 'extend':\n parent, index = get_non_exp_parent_and_index(tree, node)\n replace_at(index, parent, variables[node.args[0].id])", "focal_method_lines": [92, 96], "in_stack": false, "globals": ["Variable", "T"], "type_context": "from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar\nfrom typed_ast import ast3 as ast\nfrom .tree import find, get_non_exp_parent_and_index, replace_at\nfrom .helpers import eager, VariablesGenerator, get_source\n\nVariable = Union[ast.AST, List[ast.AST], str]\nT = TypeVar('T', bound=ast.AST)\n\ndef extend_tree(tree: ast.AST, variables: Dict[str, Variable]) -> None:\n for node in find(tree, ast.Call):\n if isinstance(node.func, ast.Name) and node.func.id == 'extend':\n parent, index = get_non_exp_parent_and_index(tree, node)\n replace_at(index, parent, variables[node.args[0].id])", "has_branch": true, "total_branches": 2} {"prompt_id": 264, "project": "py_backwards", "module": "py_backwards.utils.snippet", "class": "VariablesReplacer", "method": "visit_ImportFrom", "focal_method_txt": " def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom:\n node.module = self._replace_module(node.module)\n return self.generic_visit(node)", "focal_method_lines": [71, 73], "in_stack": false, "globals": ["Variable", "T"], "type_context": "from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar\nfrom typed_ast import ast3 as ast\nfrom .tree import find, get_non_exp_parent_and_index, replace_at\nfrom .helpers import eager, VariablesGenerator, get_source\n\nVariable = Union[ast.AST, List[ast.AST], str]\nT = TypeVar('T', bound=ast.AST)\n\nclass VariablesReplacer(ast.NodeTransformer):\n\n def __init__(self, variables: Dict[str, Variable]) -> None:\n self._variables = variables\n\n def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom:\n node.module = self._replace_module(node.module)\n return self.generic_visit(node)", "has_branch": false, "total_branches": 0} {"prompt_id": 265, "project": "py_backwards", "module": "py_backwards.utils.snippet", "class": "VariablesReplacer", "method": "visit_alias", "focal_method_txt": " def visit_alias(self, node: ast.alias) -> ast.alias:\n node.name = self._replace_module(node.name)\n node = self._replace_field_or_node(node, 'asname')\n return self.generic_visit(node)", "focal_method_lines": [75, 78], "in_stack": false, "globals": ["Variable", "T"], "type_context": "from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar\nfrom typed_ast import ast3 as ast\nfrom .tree import find, get_non_exp_parent_and_index, replace_at\nfrom .helpers import eager, VariablesGenerator, get_source\n\nVariable = Union[ast.AST, List[ast.AST], str]\nT = TypeVar('T', bound=ast.AST)\n\nclass VariablesReplacer(ast.NodeTransformer):\n\n def __init__(self, variables: Dict[str, Variable]) -> None:\n self._variables = variables\n\n def visit_alias(self, node: ast.alias) -> ast.alias:\n node.name = self._replace_module(node.name)\n node = self._replace_field_or_node(node, 'asname')\n return self.generic_visit(node)", "has_branch": false, "total_branches": 0} {"prompt_id": 266, "project": "py_backwards", "module": "py_backwards.utils.snippet", "class": "snippet", "method": "get_body", "focal_method_txt": " def get_body(self, **snippet_kwargs: Variable) -> List[ast.AST]:\n \"\"\"Get AST of snippet body with replaced variables.\"\"\"\n source = get_source(self._fn)\n tree = ast.parse(source)\n variables = self._get_variables(tree, snippet_kwargs)\n extend_tree(tree, variables)\n VariablesReplacer.replace(tree, variables)\n return tree.body[0].body", "focal_method_lines": [121, 128], "in_stack": false, "globals": ["Variable", "T"], "type_context": "from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar\nfrom typed_ast import ast3 as ast\nfrom .tree import find, get_non_exp_parent_and_index, replace_at\nfrom .helpers import eager, VariablesGenerator, get_source\n\nVariable = Union[ast.AST, List[ast.AST], str]\nT = TypeVar('T', bound=ast.AST)\n\nclass VariablesReplacer(ast.NodeTransformer):\n\n def __init__(self, variables: Dict[str, Variable]) -> None:\n self._variables = variables\n\nclass snippet:\n\n def __init__(self, fn: Callable[..., None]) -> None:\n self._fn = fn\n\n def get_body(self, **snippet_kwargs: Variable) -> List[ast.AST]:\n \"\"\"Get AST of snippet body with replaced variables.\"\"\"\n source = get_source(self._fn)\n tree = ast.parse(source)\n variables = self._get_variables(tree, snippet_kwargs)\n extend_tree(tree, variables)\n VariablesReplacer.replace(tree, variables)\n return tree.body[0].body", "has_branch": false, "total_branches": 0} {"prompt_id": 267, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "get_parent", "focal_method_txt": "def get_parent(tree: ast.AST, node: ast.AST, rebuild: bool = False) -> ast.AST:\n \"\"\"Get parrent of node in tree.\"\"\"\n if node not in _parents or rebuild:\n _build_parents(tree)\n\n try:\n return _parents[node]\n except IndexError:\n raise NodeNotFound('Parent for {} not found'.format(node))", "focal_method_lines": [14, 22], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef get_parent(tree: ast.AST, node: ast.AST, rebuild: bool = False) -> ast.AST:\n \"\"\"Get parrent of node in tree.\"\"\"\n if node not in _parents or rebuild:\n _build_parents(tree)\n\n try:\n return _parents[node]\n except IndexError:\n raise NodeNotFound('Parent for {} not found'.format(node))", "has_branch": true, "total_branches": 2} {"prompt_id": 268, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "get_non_exp_parent_and_index", "focal_method_txt": "def get_non_exp_parent_and_index(tree: ast.AST, node: ast.AST) \\\n -> Tuple[ast.AST, int]:\n \"\"\"Get non-Exp parent and index of child.\"\"\"\n parent = get_parent(tree, node)\n\n while not hasattr(parent, 'body'):\n node = parent\n parent = get_parent(tree, parent)\n\n return parent, parent.body.index(node)", "focal_method_lines": [25, 34], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef get_non_exp_parent_and_index(tree: ast.AST, node: ast.AST) \\\n -> Tuple[ast.AST, int]:\n \"\"\"Get non-Exp parent and index of child.\"\"\"\n parent = get_parent(tree, node)\n\n while not hasattr(parent, 'body'):\n node = parent\n parent = get_parent(tree, parent)\n\n return parent, parent.body.index(node)", "has_branch": true, "total_branches": 2} {"prompt_id": 269, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "find", "focal_method_txt": "def find(tree: ast.AST, type_: Type[T]) -> Iterable[T]:\n \"\"\"Finds all nodes with type T.\"\"\"\n for node in ast.walk(tree):\n if isinstance(node, type_):\n yield node", "focal_method_lines": [40, 44], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef find(tree: ast.AST, type_: Type[T]) -> Iterable[T]:\n \"\"\"Finds all nodes with type T.\"\"\"\n for node in ast.walk(tree):\n if isinstance(node, type_):\n yield node", "has_branch": true, "total_branches": 2} {"prompt_id": 270, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "insert_at", "focal_method_txt": "def insert_at(index: int, parent: ast.AST,\n nodes: Union[ast.AST, List[ast.AST]]) -> None:\n \"\"\"Inserts nodes to parents body at index.\"\"\"\n if not isinstance(nodes, list):\n nodes = [nodes]\n\n for child in nodes[::-1]:\n parent.body.insert(index, child)", "focal_method_lines": [47, 54], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef insert_at(index: int, parent: ast.AST,\n nodes: Union[ast.AST, List[ast.AST]]) -> None:\n \"\"\"Inserts nodes to parents body at index.\"\"\"\n if not isinstance(nodes, list):\n nodes = [nodes]\n\n for child in nodes[::-1]:\n parent.body.insert(index, child)", "has_branch": true, "total_branches": 2} {"prompt_id": 271, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "replace_at", "focal_method_txt": "def replace_at(index: int, parent: ast.AST,\n nodes: Union[ast.AST, List[ast.AST]]) -> None:\n \"\"\"Replaces node in parents body at index with nodes.\"\"\"\n parent.body.pop(index) # type: ignore\n insert_at(index, parent, nodes)", "focal_method_lines": [57, 61], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef replace_at(index: int, parent: ast.AST,\n nodes: Union[ast.AST, List[ast.AST]]) -> None:\n \"\"\"Replaces node in parents body at index with nodes.\"\"\"\n parent.body.pop(index) # type: ignore\n insert_at(index, parent, nodes)", "has_branch": false, "total_branches": 0} {"prompt_id": 272, "project": "py_backwards", "module": "py_backwards.utils.tree", "class": "", "method": "get_closest_parent_of", "focal_method_txt": "def get_closest_parent_of(tree: ast.AST, node: ast.AST,\n type_: Type[T]) -> T:\n \"\"\"Get a closest parent of passed type.\"\"\"\n parent = node\n\n while True:\n parent = get_parent(tree, parent)\n\n if isinstance(parent, type_):\n return parent", "focal_method_lines": [64, 73], "in_stack": false, "globals": ["_parents", "T"], "type_context": "from weakref import WeakKeyDictionary\nfrom typing import Tuple, Iterable, Type, TypeVar, Union, List\nfrom typed_ast import ast3 as ast\nfrom ..exceptions import NodeNotFound\n\n_parents = WeakKeyDictionary()\nT = TypeVar('T', bound=ast.AST)\n\ndef get_closest_parent_of(tree: ast.AST, node: ast.AST,\n type_: Type[T]) -> T:\n \"\"\"Get a closest parent of passed type.\"\"\"\n parent = node\n\n while True:\n parent = get_parent(tree, parent)\n\n if isinstance(parent, type_):\n return parent", "has_branch": true, "total_branches": 2} {"prompt_id": 273, "project": "pymonet", "module": "pymonet.box", "class": "Box", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: object) -> bool:\n return isinstance(other, Box) and self.value == other.value", "focal_method_lines": [19, 20], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Box(Generic[T]):\n\n def __init__(self, value: T) -> None:\n \"\"\"\n :param value: value to store in Box\n :type value: Any\n \"\"\"\n self.value = value\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, Box) and self.value == other.value", "has_branch": false, "total_branches": 0} {"prompt_id": 274, "project": "pymonet", "module": "pymonet.box", "class": "Box", "method": "to_lazy", "focal_method_txt": " def to_lazy(self):\n \"\"\"\n Transform Box into Lazy with returning value function.\n\n :returns: not folded Lazy monad with function returning previous value\n :rtype: Lazy[Function(() -> A)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "focal_method_lines": [80, 89], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Box(Generic[T]):\n\n def __init__(self, value: T) -> None:\n \"\"\"\n :param value: value to store in Box\n :type value: Any\n \"\"\"\n self.value = value\n\n def to_lazy(self):\n \"\"\"\n Transform Box into Lazy with returning value function.\n\n :returns: not folded Lazy monad with function returning previous value\n :rtype: Lazy[Function(() -> A)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 275, "project": "pymonet", "module": "pymonet.either", "class": "Either", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: object) -> bool:\n return isinstance(other, Either) and\\\n self.value == other.value and\\\n self.is_right() == other.is_right()", "focal_method_lines": [16, 17], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Any\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Either(Generic[T]):\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, Either) and\\\n self.value == other.value and\\\n self.is_right() == other.is_right()", "has_branch": false, "total_branches": 0} {"prompt_id": 276, "project": "pymonet", "module": "pymonet.either", "class": "Either", "method": "case", "focal_method_txt": " def case(self, error: Callable[[T], U], success: Callable[[T], U]) -> U:\n \"\"\"\n Take 2 functions call only one of then with either value and return her result.\n\n :params error: function to call when Either is Left\n :type error: Function(A) -> B\n :params success: function to call when Either is Right\n :type success: Function(A) -> B\n :returns: result of success handler when Eihter is Right, result of error handler when Eihter is Left\n :rtpye: B\n \"\"\"\n if self.is_right():\n return success(self.value)\n return error(self.value)", "focal_method_lines": [21, 34], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Any\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Either(Generic[T]):\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def case(self, error: Callable[[T], U], success: Callable[[T], U]) -> U:\n \"\"\"\n Take 2 functions call only one of then with either value and return her result.\n\n :params error: function to call when Either is Left\n :type error: Function(A) -> B\n :params success: function to call when Either is Right\n :type success: Function(A) -> B\n :returns: result of success handler when Eihter is Right, result of error handler when Eihter is Left\n :rtpye: B\n \"\"\"\n if self.is_right():\n return success(self.value)\n return error(self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 277, "project": "pymonet", "module": "pymonet.either", "class": "Either", "method": "to_lazy", "focal_method_txt": " def to_lazy(self):\n \"\"\"\n Transform Either to Try.\n\n :returns: Lazy monad with function returning previous value\n :rtype: Lazy[Function() -> A]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "focal_method_lines": [69, 78], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Any\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Either(Generic[T]):\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def to_lazy(self):\n \"\"\"\n Transform Either to Try.\n\n :returns: Lazy monad with function returning previous value\n :rtype: Lazy[Function() -> A]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 278, "project": "pymonet", "module": "pymonet.immutable_list", "class": "ImmutableList", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: object) -> bool:\n return isinstance(other, ImmutableList) \\\n and self.head == other.head\\\n and self.tail == other.tail\\\n and self.is_empty == other.is_empty", "focal_method_lines": [17, 18], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Optional\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass ImmutableList(Generic[T]):\n\n def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:\n self.head = head\n self.tail = tail\n self.is_empty = is_empty\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, ImmutableList) \\\n and self.head == other.head\\\n and self.tail == other.tail\\\n and self.is_empty == other.is_empty", "has_branch": false, "total_branches": 0} {"prompt_id": 279, "project": "pymonet", "module": "pymonet.immutable_list", "class": "ImmutableList", "method": "__len__", "focal_method_txt": " def __len__(self):\n if self.head is None:\n return 0\n\n if self.tail is None:\n return 1\n\n return len(self.tail) + 1", "focal_method_lines": [46, 53], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Optional\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass ImmutableList(Generic[T]):\n\n def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:\n self.head = head\n self.tail = tail\n self.is_empty = is_empty\n\n def __len__(self):\n if self.head is None:\n return 0\n\n if self.tail is None:\n return 1\n\n return len(self.tail) + 1", "has_branch": true, "total_branches": 2} {"prompt_id": 280, "project": "pymonet", "module": "pymonet.immutable_list", "class": "ImmutableList", "method": "filter", "focal_method_txt": " def filter(self, fn: Callable[[Optional[T]], bool]) -> 'ImmutableList[T]':\n \"\"\"\n Returns new ImmutableList with only this elements that passed\n info argument returns True\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A) -> bool\n :returns: ImmutableList[A]\n \"\"\"\n if self.tail is None:\n if fn(self.head):\n return ImmutableList(self.head)\n return ImmutableList(is_empty=True)\n\n if fn(self.head):\n return ImmutableList(self.head, self.tail.filter(fn))\n\n return self.tail.filter(fn)", "focal_method_lines": [112, 129], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Optional\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass ImmutableList(Generic[T]):\n\n def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:\n self.head = head\n self.tail = tail\n self.is_empty = is_empty\n\n def filter(self, fn: Callable[[Optional[T]], bool]) -> 'ImmutableList[T]':\n \"\"\"\n Returns new ImmutableList with only this elements that passed\n info argument returns True\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A) -> bool\n :returns: ImmutableList[A]\n \"\"\"\n if self.tail is None:\n if fn(self.head):\n return ImmutableList(self.head)\n return ImmutableList(is_empty=True)\n\n if fn(self.head):\n return ImmutableList(self.head, self.tail.filter(fn))\n\n return self.tail.filter(fn)", "has_branch": true, "total_branches": 2} {"prompt_id": 281, "project": "pymonet", "module": "pymonet.immutable_list", "class": "ImmutableList", "method": "find", "focal_method_txt": " def find(self, fn: Callable[[Optional[T]], bool]) -> Optional[T]:\n \"\"\"\n Returns first element of ImmutableList that passed\n info argument returns True\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A) -> bool\n :returns: A\n \"\"\"\n if self.head is None:\n return None\n\n if self.tail is None:\n return self.head if fn(self.head) else None\n\n if fn(self.head):\n return self.head\n\n return self.tail.find(fn)", "focal_method_lines": [131, 149], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Optional\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass ImmutableList(Generic[T]):\n\n def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:\n self.head = head\n self.tail = tail\n self.is_empty = is_empty\n\n def find(self, fn: Callable[[Optional[T]], bool]) -> Optional[T]:\n \"\"\"\n Returns first element of ImmutableList that passed\n info argument returns True\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A) -> bool\n :returns: A\n \"\"\"\n if self.head is None:\n return None\n\n if self.tail is None:\n return self.head if fn(self.head) else None\n\n if fn(self.head):\n return self.head\n\n return self.tail.find(fn)", "has_branch": true, "total_branches": 2} {"prompt_id": 282, "project": "pymonet", "module": "pymonet.immutable_list", "class": "ImmutableList", "method": "reduce", "focal_method_txt": " def reduce(self, fn: Callable[[U, T], U], acc: U) -> U:\n \"\"\"\n Method executes a reducer function\n on each element of the array, resulting in a single output value.\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A, B) -> A\n :returns: A\n \"\"\"\n if self.head is None:\n return acc\n\n if self.tail is None:\n return fn(self.head, acc)\n\n \n return self.tail.reduce(fn, fn(acc, self.head))", "focal_method_lines": [151, 167], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Optional\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass ImmutableList(Generic[T]):\n\n def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:\n self.head = head\n self.tail = tail\n self.is_empty = is_empty\n\n def reduce(self, fn: Callable[[U, T], U], acc: U) -> U:\n \"\"\"\n Method executes a reducer function\n on each element of the array, resulting in a single output value.\n\n :param fn: function to call with ImmutableList value\n :type fn: Function(A, B) -> A\n :returns: A\n \"\"\"\n if self.head is None:\n return acc\n\n if self.tail is None:\n return fn(self.head, acc)\n\n \n return self.tail.reduce(fn, fn(acc, self.head))", "has_branch": true, "total_branches": 2} {"prompt_id": 283, "project": "pymonet", "module": "pymonet.lazy", "class": "Lazy", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: object) -> bool:\n \"\"\"\n Two Lazy are equals where both are evaluated both have the same value and constructor functions.\n \"\"\"\n return (\n isinstance(other, Lazy)\n and self.is_evaluated == other.is_evaluated\n and self.value == other.value\n and self.constructor_fn == other.constructor_fn\n )", "focal_method_lines": [26, 30], "in_stack": false, "globals": ["T", "U", "W"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\nW = TypeVar('W')\n\nclass Lazy(Generic[T, U]):\n\n def __init__(self, constructor_fn: Callable[[T], U]) -> None:\n \"\"\"\n :param constructor_fn: function to call during fold method call\n :type constructor_fn: Function() -> A\n \"\"\"\n self.constructor_fn = constructor_fn\n self.is_evaluated = False\n self.value = None\n\n def __eq__(self, other: object) -> bool:\n \"\"\"\n Two Lazy are equals where both are evaluated both have the same value and constructor functions.\n \"\"\"\n return (\n isinstance(other, Lazy)\n and self.is_evaluated == other.is_evaluated\n and self.value == other.value\n and self.constructor_fn == other.constructor_fn\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 284, "project": "pymonet", "module": "pymonet.lazy", "class": "Lazy", "method": "map", "focal_method_txt": " def map(self, mapper: Callable[[U], W]) -> 'Lazy[T, W]':\n \"\"\"\n Take function Function(A) -> B and returns new Lazy with mapped result of Lazy constructor function.\n Both mapper end constructor will be called only during calling fold method.\n\n :param mapper: mapper function\n :type mapper: Function(A) -> B\n :returns: Lazy with mapped value\n :rtype: Lazy[Function() -> B)]\n \"\"\"\n return Lazy(lambda *args: mapper(self.constructor_fn(*args)))", "focal_method_lines": [55, 65], "in_stack": false, "globals": ["T", "U", "W"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\nW = TypeVar('W')\n\nclass Lazy(Generic[T, U]):\n\n def __init__(self, constructor_fn: Callable[[T], U]) -> None:\n \"\"\"\n :param constructor_fn: function to call during fold method call\n :type constructor_fn: Function() -> A\n \"\"\"\n self.constructor_fn = constructor_fn\n self.is_evaluated = False\n self.value = None\n\n def map(self, mapper: Callable[[U], W]) -> 'Lazy[T, W]':\n \"\"\"\n Take function Function(A) -> B and returns new Lazy with mapped result of Lazy constructor function.\n Both mapper end constructor will be called only during calling fold method.\n\n :param mapper: mapper function\n :type mapper: Function(A) -> B\n :returns: Lazy with mapped value\n :rtype: Lazy[Function() -> B)]\n \"\"\"\n return Lazy(lambda *args: mapper(self.constructor_fn(*args)))", "has_branch": true, "total_branches": 2} {"prompt_id": 285, "project": "pymonet", "module": "pymonet.lazy", "class": "Lazy", "method": "ap", "focal_method_txt": " def ap(self, applicative):\n \"\"\"\n Applies the function inside the Lazy[A] structure to another applicative type for notempty Lazy.\n For empty returns copy of itself\n\n :param applicative: applicative contains function\n :type applicative: Lazy[Function(A) -> B]\n :returns: new Lazy with result of contains function\n :rtype: Lazy[B]\n \"\"\"\n return Lazy(lambda *args: self.constructor_fn(applicative.get(*args)))", "focal_method_lines": [67, 77], "in_stack": false, "globals": ["T", "U", "W"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\nW = TypeVar('W')\n\nclass Lazy(Generic[T, U]):\n\n def __init__(self, constructor_fn: Callable[[T], U]) -> None:\n \"\"\"\n :param constructor_fn: function to call during fold method call\n :type constructor_fn: Function() -> A\n \"\"\"\n self.constructor_fn = constructor_fn\n self.is_evaluated = False\n self.value = None\n\n def ap(self, applicative):\n \"\"\"\n Applies the function inside the Lazy[A] structure to another applicative type for notempty Lazy.\n For empty returns copy of itself\n\n :param applicative: applicative contains function\n :type applicative: Lazy[Function(A) -> B]\n :returns: new Lazy with result of contains function\n :rtype: Lazy[B]\n \"\"\"\n return Lazy(lambda *args: self.constructor_fn(applicative.get(*args)))", "has_branch": true, "total_branches": 2} {"prompt_id": 286, "project": "pymonet", "module": "pymonet.lazy", "class": "Lazy", "method": "bind", "focal_method_txt": " def bind(self, fn: 'Callable[[U], Lazy[U, W]]') -> 'Lazy[T, W]':\n \"\"\"\n Take function and call constructor function passing returned value to fn function.\n\n It's only way to call function store in Lazy\n :param fn: Function(constructor_fn) -> B\n :returns: result od folder function\n :rtype: B\n \"\"\"\n def lambda_fn(*args):\n computed_value = self._compute_value(*args)\n return fn(computed_value).constructor_fn\n\n return Lazy(lambda_fn)", "focal_method_lines": [79, 92], "in_stack": false, "globals": ["T", "U", "W"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\nW = TypeVar('W')\n\nclass Lazy(Generic[T, U]):\n\n def __init__(self, constructor_fn: Callable[[T], U]) -> None:\n \"\"\"\n :param constructor_fn: function to call during fold method call\n :type constructor_fn: Function() -> A\n \"\"\"\n self.constructor_fn = constructor_fn\n self.is_evaluated = False\n self.value = None\n\n def bind(self, fn: 'Callable[[U], Lazy[U, W]]') -> 'Lazy[T, W]':\n \"\"\"\n Take function and call constructor function passing returned value to fn function.\n\n It's only way to call function store in Lazy\n :param fn: Function(constructor_fn) -> B\n :returns: result od folder function\n :rtype: B\n \"\"\"\n def lambda_fn(*args):\n computed_value = self._compute_value(*args)\n return fn(computed_value).constructor_fn\n\n return Lazy(lambda_fn)", "has_branch": false, "total_branches": 0} {"prompt_id": 287, "project": "pymonet", "module": "pymonet.lazy", "class": "Lazy", "method": "get", "focal_method_txt": " def get(self, *args):\n \"\"\"\n Evaluate function and memoize her output or return memoized value when function was evaluated.\n\n :returns: result of function in Lazy\n :rtype: A\n \"\"\"\n if self.is_evaluated:\n return self.value\n return self._compute_value(*args)", "focal_method_lines": [94, 103], "in_stack": false, "globals": ["T", "U", "W"], "type_context": "from typing import TypeVar, Generic, Callable\n\nT = TypeVar('T')\nU = TypeVar('U')\nW = TypeVar('W')\n\nclass Lazy(Generic[T, U]):\n\n def __init__(self, constructor_fn: Callable[[T], U]) -> None:\n \"\"\"\n :param constructor_fn: function to call during fold method call\n :type constructor_fn: Function() -> A\n \"\"\"\n self.constructor_fn = constructor_fn\n self.is_evaluated = False\n self.value = None\n\n def get(self, *args):\n \"\"\"\n Evaluate function and memoize her output or return memoized value when function was evaluated.\n\n :returns: result of function in Lazy\n :rtype: A\n \"\"\"\n if self.is_evaluated:\n return self.value\n return self._compute_value(*args)", "has_branch": true, "total_branches": 2} {"prompt_id": 288, "project": "pymonet", "module": "pymonet.maybe", "class": "Maybe", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: object) -> bool:\n return isinstance(other, Maybe) and \\\n self.is_nothing == other.is_nothing and \\\n (self.is_nothing or self.value == other.value)", "focal_method_lines": [18, 19], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Union\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Maybe(Generic[T]):\n\n def __init__(self, value: T, is_nothing: bool) -> None:\n self.is_nothing = is_nothing\n if not is_nothing:\n self.value = value\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, Maybe) and \\\n self.is_nothing == other.is_nothing and \\\n (self.is_nothing or self.value == other.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 289, "project": "pymonet", "module": "pymonet.maybe", "class": "Maybe", "method": "filter", "focal_method_txt": " def filter(self, filterer: Callable[[T], bool]) -> Union['Maybe[T]', 'Maybe[None]']:\n \"\"\"\n If Maybe is empty or filterer returns False return default_value, in other case\n return new instance of Maybe with the same value.\n\n :param filterer:\n :type filterer: Function(A) -> Boolean\n :returns: copy of self when filterer returns True, in other case empty Maybe\n :rtype: Maybe[A] | Maybe[None]\n \"\"\"\n if self.is_nothing or not filterer(self.value):\n return Maybe.nothing()\n return Maybe.just(self.value)", "focal_method_lines": [86, 98], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Union\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Maybe(Generic[T]):\n\n def __init__(self, value: T, is_nothing: bool) -> None:\n self.is_nothing = is_nothing\n if not is_nothing:\n self.value = value\n\n def filter(self, filterer: Callable[[T], bool]) -> Union['Maybe[T]', 'Maybe[None]']:\n \"\"\"\n If Maybe is empty or filterer returns False return default_value, in other case\n return new instance of Maybe with the same value.\n\n :param filterer:\n :type filterer: Function(A) -> Boolean\n :returns: copy of self when filterer returns True, in other case empty Maybe\n :rtype: Maybe[A] | Maybe[None]\n \"\"\"\n if self.is_nothing or not filterer(self.value):\n return Maybe.nothing()\n return Maybe.just(self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 290, "project": "pymonet", "module": "pymonet.maybe", "class": "Maybe", "method": "to_lazy", "focal_method_txt": " def to_lazy(self):\n \"\"\"\n Transform Maybe to Try.\n\n :returns: Lazy monad with function returning previous value in other case Left with None\n :rtype: Lazy[Function() -> (A | None)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n if self.is_nothing:\n return Lazy(lambda: None)\n return Lazy(lambda: self.value)", "focal_method_lines": [139, 150], "in_stack": false, "globals": ["T", "U"], "type_context": "from typing import TypeVar, Generic, Callable, Union\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Maybe(Generic[T]):\n\n def __init__(self, value: T, is_nothing: bool) -> None:\n self.is_nothing = is_nothing\n if not is_nothing:\n self.value = value\n\n def to_lazy(self):\n \"\"\"\n Transform Maybe to Try.\n\n :returns: Lazy monad with function returning previous value in other case Left with None\n :rtype: Lazy[Function() -> (A | None)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n if self.is_nothing:\n return Lazy(lambda: None)\n return Lazy(lambda: self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 291, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "__init__", "focal_method_txt": " def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success", "focal_method_lines": [9, 11], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success", "has_branch": false, "total_branches": 0} {"prompt_id": 292, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "__eq__", "focal_method_txt": " def __eq__(self, other) -> bool:\n return isinstance(other, type(self))\\\n and self.value == other.value\\\n and self.is_success == other.is_success", "focal_method_lines": [13, 14], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def __eq__(self, other) -> bool:\n return isinstance(other, type(self))\\\n and self.value == other.value\\\n and self.is_success == other.is_success", "has_branch": false, "total_branches": 0} {"prompt_id": 293, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Try[value={}, is_success={}]'.format(self.value, self.is_success)", "focal_method_lines": [18, 19], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def __str__(self) -> str: # pragma: no cover\n return 'Try[value={}, is_success={}]'.format(self.value, self.is_success)", "has_branch": false, "total_branches": 0} {"prompt_id": 294, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "map", "focal_method_txt": " def map(self, mapper):\n \"\"\"\n Take function and applied this function with monad value and returns new monad with mapped value.\n\n :params mapper: function to apply on monad value\n :type mapper: Function(A) -> B\n :returns: for successfully new Try with mapped value, othercase copy of self\n :rtype: Try[B]\n \"\"\"\n if self.is_success:\n return Try(mapper(self.value), True)\n return Try(self.value, False)", "focal_method_lines": [39, 50], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def map(self, mapper):\n \"\"\"\n Take function and applied this function with monad value and returns new monad with mapped value.\n\n :params mapper: function to apply on monad value\n :type mapper: Function(A) -> B\n :returns: for successfully new Try with mapped value, othercase copy of self\n :rtype: Try[B]\n \"\"\"\n if self.is_success:\n return Try(mapper(self.value), True)\n return Try(self.value, False)", "has_branch": true, "total_branches": 2} {"prompt_id": 295, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "bind", "focal_method_txt": " def bind(self, binder):\n \"\"\"\n Take function and applied this function with monad value and returns function result.\n\n :params binder: function to apply on monad value\n :type binder: Function(A) -> Try[B]\n :returns: for successfully result of binder, othercase copy of self\n :rtype: Try[B]\n \"\"\"\n if self.is_success:\n return binder(self.value)\n return self", "focal_method_lines": [52, 63], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def bind(self, binder):\n \"\"\"\n Take function and applied this function with monad value and returns function result.\n\n :params binder: function to apply on monad value\n :type binder: Function(A) -> Try[B]\n :returns: for successfully result of binder, othercase copy of self\n :rtype: Try[B]\n \"\"\"\n if self.is_success:\n return binder(self.value)\n return self", "has_branch": true, "total_branches": 2} {"prompt_id": 296, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "on_success", "focal_method_txt": " def on_success(self, success_callback):\n \"\"\"\n Call success_callback function with monad value when monad is successfully.\n\n :params success_callback: function to apply with monad value.\n :type success_callback: Function(A)\n :returns: self\n :rtype: Try[A]\n \"\"\"\n if self.is_success:\n success_callback(self.value)\n return self", "focal_method_lines": [65, 76], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def on_success(self, success_callback):\n \"\"\"\n Call success_callback function with monad value when monad is successfully.\n\n :params success_callback: function to apply with monad value.\n :type success_callback: Function(A)\n :returns: self\n :rtype: Try[A]\n \"\"\"\n if self.is_success:\n success_callback(self.value)\n return self", "has_branch": true, "total_branches": 2} {"prompt_id": 297, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "on_fail", "focal_method_txt": " def on_fail(self, fail_callback):\n \"\"\"\n Call success_callback function with monad value when monad is not successfully.\n\n :params fail_callback: function to apply with monad value.\n :type fail_callback: Function(A)\n :returns: self\n :rtype: Try[A]\n \"\"\"\n if not self.is_success:\n fail_callback(self.value)\n return self", "focal_method_lines": [78, 89], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def on_fail(self, fail_callback):\n \"\"\"\n Call success_callback function with monad value when monad is not successfully.\n\n :params fail_callback: function to apply with monad value.\n :type fail_callback: Function(A)\n :returns: self\n :rtype: Try[A]\n \"\"\"\n if not self.is_success:\n fail_callback(self.value)\n return self", "has_branch": true, "total_branches": 2} {"prompt_id": 298, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "filter", "focal_method_txt": " def filter(self, filterer):\n \"\"\"\n Take filterer function, when monad is successfully call filterer with monad value.\n When filterer returns True method returns copy of monad, othercase\n not successfully Try with previous value.\n\n :params filterer: function to apply on monad value\n :type filterer: Function(A) -> Boolean\n :returns: Try with previous value\n :rtype: Try[A]\n \"\"\"\n if self.is_success and filterer(self.value):\n return Try(self.value, True)\n return Try(self.value, False)", "focal_method_lines": [91, 104], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def filter(self, filterer):\n \"\"\"\n Take filterer function, when monad is successfully call filterer with monad value.\n When filterer returns True method returns copy of monad, othercase\n not successfully Try with previous value.\n\n :params filterer: function to apply on monad value\n :type filterer: Function(A) -> Boolean\n :returns: Try with previous value\n :rtype: Try[A]\n \"\"\"\n if self.is_success and filterer(self.value):\n return Try(self.value, True)\n return Try(self.value, False)", "has_branch": true, "total_branches": 2} {"prompt_id": 299, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "get", "focal_method_txt": " def get(self):\n \"\"\"\n Return monad value.\n\n :returns: monad value\n :rtype: A\n \"\"\"\n return self.value", "focal_method_lines": [106, 113], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def get(self):\n \"\"\"\n Return monad value.\n\n :returns: monad value\n :rtype: A\n \"\"\"\n return self.value", "has_branch": false, "total_branches": 0} {"prompt_id": 300, "project": "pymonet", "module": "pymonet.monad_try", "class": "Try", "method": "get_or_else", "focal_method_txt": " def get_or_else(self, default_value):\n \"\"\"\n Return monad value when is successfully.\n Othercase return default_value argument.\n\n :params default_value: value to return when monad is not successfully.\n :type default_value: B\n :returns: monad value\n :rtype: A | B\n \"\"\"\n if self.is_success:\n return self.value\n return default_value", "focal_method_lines": [115, 127], "in_stack": false, "globals": [], "type_context": "from typing import Callable\n\n\n\nclass Try:\n\n def __init__(self, value, is_success: bool) -> None:\n self.value = value\n self.is_success = is_success\n\n def get_or_else(self, default_value):\n \"\"\"\n Return monad value when is successfully.\n Othercase return default_value argument.\n\n :params default_value: value to return when monad is not successfully.\n :type default_value: B\n :returns: monad value\n :rtype: A | B\n \"\"\"\n if self.is_success:\n return self.value\n return default_value", "has_branch": true, "total_branches": 2} {"prompt_id": 301, "project": "pymonet", "module": "pymonet.semigroups", "class": "Semigroup", "method": "__init__", "focal_method_txt": " def __init__(self, value):\n self.value = value", "focal_method_lines": [9, 10], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Semigroup:\n\n def __init__(self, value):\n self.value = value", "has_branch": false, "total_branches": 0} {"prompt_id": 302, "project": "pymonet", "module": "pymonet.semigroups", "class": "Semigroup", "method": "__eq__", "focal_method_txt": " def __eq__(self, other) -> bool:\n return self.value == other.value", "focal_method_lines": [12, 13], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Semigroup:\n\n def __init__(self, value):\n self.value = value\n\n def __eq__(self, other) -> bool:\n return self.value == other.value", "has_branch": false, "total_branches": 0} {"prompt_id": 303, "project": "pymonet", "module": "pymonet.semigroups", "class": "Semigroup", "method": "fold", "focal_method_txt": " def fold(self, fn):\n return fn(self.value)", "focal_method_lines": [15, 16], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Semigroup:\n\n def __init__(self, value):\n self.value = value\n\n def fold(self, fn):\n return fn(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 304, "project": "pymonet", "module": "pymonet.semigroups", "class": "Sum", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Sum[value={}]'.format(self.value)", "focal_method_lines": [30, 31], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Sum(Semigroup):\n\n neutral_element = 0\n\n def __str__(self) -> str: # pragma: no cover\n return 'Sum[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 305, "project": "pymonet", "module": "pymonet.semigroups", "class": "Sum", "method": "concat", "focal_method_txt": " def concat(self, semigroup: 'Sum') -> 'Sum':\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Sum[B]\n :returns: new Sum with sum of concat semigroups values\n :rtype: Sum[A]\n \"\"\"\n return Sum(self.value + semigroup.value)", "focal_method_lines": [33, 40], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Sum(Semigroup):\n\n neutral_element = 0\n\n def concat(self, semigroup: 'Sum') -> 'Sum':\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Sum[B]\n :returns: new Sum with sum of concat semigroups values\n :rtype: Sum[A]\n \"\"\"\n return Sum(self.value + semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 306, "project": "pymonet", "module": "pymonet.semigroups", "class": "All", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'All[value={}]'.format(self.value)", "focal_method_lines": [50, 51], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass All(Semigroup):\n\n neutral_element = True\n\n def __str__(self) -> str: # pragma: no cover\n return 'All[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 307, "project": "pymonet", "module": "pymonet.semigroups", "class": "All", "method": "concat", "focal_method_txt": " def concat(self, semigroup: 'All') -> 'All':\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: All[B]\n :returns: new All with last truly value or first falsy\n :rtype: All[A | B]\n \"\"\"\n return All(self.value and semigroup.value)", "focal_method_lines": [53, 60], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass All(Semigroup):\n\n neutral_element = True\n\n def concat(self, semigroup: 'All') -> 'All':\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: All[B]\n :returns: new All with last truly value or first falsy\n :rtype: All[A | B]\n \"\"\"\n return All(self.value and semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 308, "project": "pymonet", "module": "pymonet.semigroups", "class": "One", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'One[value={}]'.format(self.value)", "focal_method_lines": [70, 71], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass One(Semigroup):\n\n neutral_element = False\n\n def __str__(self) -> str: # pragma: no cover\n return 'One[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 309, "project": "pymonet", "module": "pymonet.semigroups", "class": "One", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: One[B]\n :returns: new One with first truly value or last falsy\n :rtype: One[A | B]\n \"\"\"\n return One(self.value or semigroup.value)", "focal_method_lines": [73, 80], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass One(Semigroup):\n\n neutral_element = False\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: One[B]\n :returns: new One with first truly value or last falsy\n :rtype: One[A | B]\n \"\"\"\n return One(self.value or semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 310, "project": "pymonet", "module": "pymonet.semigroups", "class": "First", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Fist[value={}]'.format(self.value)", "focal_method_lines": [88, 89], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass First(Semigroup):\n\n def __str__(self) -> str: # pragma: no cover\n return 'Fist[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 311, "project": "pymonet", "module": "pymonet.semigroups", "class": "First", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: First[B]\n :returns: new First with first value\n :rtype: First[A]\n \"\"\"\n return First(self.value)", "focal_method_lines": [91, 98], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass First(Semigroup):\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: First[B]\n :returns: new First with first value\n :rtype: First[A]\n \"\"\"\n return First(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 312, "project": "pymonet", "module": "pymonet.semigroups", "class": "Last", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Last[value={}]'.format(self.value)", "focal_method_lines": [106, 107], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Last(Semigroup):\n\n def __str__(self) -> str: # pragma: no cover\n return 'Last[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 313, "project": "pymonet", "module": "pymonet.semigroups", "class": "Last", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Last[B]\n :returns: new Last with last value\n :rtype: Last[A]\n \"\"\"\n return Last(semigroup.value)", "focal_method_lines": [109, 116], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Last(Semigroup):\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Last[B]\n :returns: new Last with last value\n :rtype: Last[A]\n \"\"\"\n return Last(semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 314, "project": "pymonet", "module": "pymonet.semigroups", "class": "Map", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Map[value={}]'.format(self.value)", "focal_method_lines": [124, 125], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Map(Semigroup):\n\n def __str__(self) -> str: # pragma: no cover\n return 'Map[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 315, "project": "pymonet", "module": "pymonet.semigroups", "class": "Map", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Map[B]\n :returns: new Map with concated all values\n :rtype: Map[A]\n \"\"\"\n return Map(\n {key: value.concat(semigroup.value[key]) for key, value in self.value.items()}\n )", "focal_method_lines": [127, 134], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Map(Semigroup):\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Map[B]\n :returns: new Map with concated all values\n :rtype: Map[A]\n \"\"\"\n return Map(\n {key: value.concat(semigroup.value[key]) for key, value in self.value.items()}\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 316, "project": "pymonet", "module": "pymonet.semigroups", "class": "Max", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Max[value={}]'.format(self.value)", "focal_method_lines": [146, 147], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Max(Semigroup):\n\n neutral_element = -float(\"inf\")\n\n def __str__(self) -> str: # pragma: no cover\n return 'Max[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 317, "project": "pymonet", "module": "pymonet.semigroups", "class": "Max", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Max[B]\n :returns: new Max with largest value\n :rtype: Max[A | B]\n \"\"\"\n return Max(self.value if self.value > semigroup.value else semigroup.value)", "focal_method_lines": [149, 156], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Max(Semigroup):\n\n neutral_element = -float(\"inf\")\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Max[B]\n :returns: new Max with largest value\n :rtype: Max[A | B]\n \"\"\"\n return Max(self.value if self.value > semigroup.value else semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 318, "project": "pymonet", "module": "pymonet.semigroups", "class": "Min", "method": "__str__", "focal_method_txt": " def __str__(self) -> str: # pragma: no cover\n return 'Min[value={}]'.format(self.value)", "focal_method_lines": [166, 167], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Min(Semigroup):\n\n neutral_element = float(\"inf\")\n\n def __str__(self) -> str: # pragma: no cover\n return 'Min[value={}]'.format(self.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 319, "project": "pymonet", "module": "pymonet.semigroups", "class": "Min", "method": "concat", "focal_method_txt": " def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Min[B]\n :returns: new Min with smallest value\n :rtype: Min[A | B]\n \"\"\"\n return Min(self.value if self.value <= semigroup.value else semigroup.value)", "focal_method_lines": [169, 176], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Min(Semigroup):\n\n neutral_element = float(\"inf\")\n\n def concat(self, semigroup):\n \"\"\"\n :param semigroup: other semigroup to concat\n :type semigroup: Min[B]\n :returns: new Min with smallest value\n :rtype: Min[A | B]\n \"\"\"\n return Min(self.value if self.value <= semigroup.value else semigroup.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 320, "project": "pymonet", "module": "pymonet.task", "class": "Task", "method": "map", "focal_method_txt": " def map(self, fn):\n \"\"\"\n Take function, store it and call with Task value during calling fork function.\n Return new Task with result of called.\n\n :param fn: mapper function\n :type fn: Function(value) -> B\n :returns: new Task with mapped resolve attribute\n :rtype: Task[Function(resolve, reject -> A | B]\n \"\"\"\n def result(reject, resolve):\n return self.fork(\n lambda arg: reject(arg),\n lambda arg: resolve(fn(arg))\n )\n\n return Task(result)", "focal_method_lines": [37, 53], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Task:\n\n def __init__(self, fork):\n \"\"\"\n :param fork: function to call during fork\n :type fork: Function(reject, resolve) -> Any\n \"\"\"\n self.fork = fork\n\n def map(self, fn):\n \"\"\"\n Take function, store it and call with Task value during calling fork function.\n Return new Task with result of called.\n\n :param fn: mapper function\n :type fn: Function(value) -> B\n :returns: new Task with mapped resolve attribute\n :rtype: Task[Function(resolve, reject -> A | B]\n \"\"\"\n def result(reject, resolve):\n return self.fork(\n lambda arg: reject(arg),\n lambda arg: resolve(fn(arg))\n )\n\n return Task(result)", "has_branch": true, "total_branches": 3} {"prompt_id": 321, "project": "pymonet", "module": "pymonet.task", "class": "Task", "method": "bind", "focal_method_txt": " def bind(self, fn):\n \"\"\"\n Take function, store it and call with Task value during calling fork function.\n Return result of called.\n\n :param fn: mapper function\n :type fn: Function(value) -> Task[reject, mapped_value]\n :returns: new Task with mapper resolve attribute\n :rtype: Task[reject, mapped_value]\n \"\"\"\n def result(reject, resolve):\n return self.fork(\n lambda arg: reject(arg),\n lambda arg: fn(arg).fork(reject, resolve)\n )\n\n return Task(result)", "focal_method_lines": [55, 71], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Task:\n\n def __init__(self, fork):\n \"\"\"\n :param fork: function to call during fork\n :type fork: Function(reject, resolve) -> Any\n \"\"\"\n self.fork = fork\n\n def bind(self, fn):\n \"\"\"\n Take function, store it and call with Task value during calling fork function.\n Return result of called.\n\n :param fn: mapper function\n :type fn: Function(value) -> Task[reject, mapped_value]\n :returns: new Task with mapper resolve attribute\n :rtype: Task[reject, mapped_value]\n \"\"\"\n def result(reject, resolve):\n return self.fork(\n lambda arg: reject(arg),\n lambda arg: fn(arg).fork(reject, resolve)\n )\n\n return Task(result)", "has_branch": true, "total_branches": 3} {"prompt_id": 322, "project": "pymonet", "module": "pymonet.utils", "class": "", "method": "curry", "focal_method_txt": "def curry(x, args_count=None):\n \"\"\"\n In mathematics and computer science, currying is the technique of translating the evaluation of a function.\n It that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions.\n each with a single argument.\n \"\"\"\n if args_count is None:\n args_count = x.__code__.co_argcount\n\n def fn(*args):\n if len(args) == args_count:\n return x(*args)\n return curry(lambda *args1: x(*(args + args1)), args_count - len(args))\n return fn", "focal_method_lines": [8, 21], "in_stack": false, "globals": ["T"], "type_context": "from functools import reduce\nfrom typing import TypeVar, Callable, List, Tuple, Any\n\nT = TypeVar('T')\n\ndef curry(x, args_count=None):\n \"\"\"\n In mathematics and computer science, currying is the technique of translating the evaluation of a function.\n It that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions.\n each with a single argument.\n \"\"\"\n if args_count is None:\n args_count = x.__code__.co_argcount\n\n def fn(*args):\n if len(args) == args_count:\n return x(*args)\n return curry(lambda *args1: x(*(args + args1)), args_count - len(args))\n return fn", "has_branch": true, "total_branches": 2} {"prompt_id": 323, "project": "pymonet", "module": "pymonet.utils", "class": "", "method": "cond", "focal_method_txt": "def cond(condition_list: List[Tuple[\n Callable[[T], bool],\n Callable,\n]]):\n \"\"\"\n Function for return function depended on first function argument\n cond get list of two-item tuples,\n first is condition_function, second is execute_function.\n Returns this execute_function witch first condition_function return truly value.\n\n :param condition_list: list of two-item tuples (condition_function, execute_function)\n :type condition_list: List[(Function, Function)]\n :returns: Returns this execute_function witch first condition_function return truly value\n :rtype: Function\n \"\"\"\n def result(*args):\n for (condition_function, execute_function) in condition_list:\n if condition_function(*args):\n return execute_function(*args)\n\n return result", "focal_method_lines": [116, 136], "in_stack": false, "globals": ["T"], "type_context": "from functools import reduce\nfrom typing import TypeVar, Callable, List, Tuple, Any\n\nT = TypeVar('T')\n\ndef cond(condition_list: List[Tuple[\n Callable[[T], bool],\n Callable,\n]]):\n \"\"\"\n Function for return function depended on first function argument\n cond get list of two-item tuples,\n first is condition_function, second is execute_function.\n Returns this execute_function witch first condition_function return truly value.\n\n :param condition_list: list of two-item tuples (condition_function, execute_function)\n :type condition_list: List[(Function, Function)]\n :returns: Returns this execute_function witch first condition_function return truly value\n :rtype: Function\n \"\"\"\n def result(*args):\n for (condition_function, execute_function) in condition_list:\n if condition_function(*args):\n return execute_function(*args)\n\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 324, "project": "pymonet", "module": "pymonet.utils", "class": "", "method": "memoize", "focal_method_txt": "def memoize(fn: Callable, key=eq) -> Callable:\n \"\"\"\n Create a new function that, when invoked,\n caches the result of calling fn for a given argument set and returns the result.\n Subsequent calls to the memoized fn with the same argument set will not result in an additional call to fn;\n instead, the cached result for that set of arguments will be returned.\n\n :param fn: function to invoke\n :type fn: Function(A) -> B\n :param key: function to decide if result should be taken from cache\n :type key: Function(A, A) -> Boolean\n :returns: new function invoking old one\n :rtype: Function(A) -> B\n \"\"\"\n cache: List[Any] = []\n\n def memoized_fn(argument):\n cached_result = find(cache, lambda cacheItem: key(cacheItem[0], argument))\n if cached_result is not None:\n return cached_result[1]\n fn_result = fn(argument)\n cache.append((argument, fn_result))\n\n return fn_result\n\n return memoized_fn", "focal_method_lines": [139, 164], "in_stack": false, "globals": ["T"], "type_context": "from functools import reduce\nfrom typing import TypeVar, Callable, List, Tuple, Any\n\nT = TypeVar('T')\n\ndef memoize(fn: Callable, key=eq) -> Callable:\n \"\"\"\n Create a new function that, when invoked,\n caches the result of calling fn for a given argument set and returns the result.\n Subsequent calls to the memoized fn with the same argument set will not result in an additional call to fn;\n instead, the cached result for that set of arguments will be returned.\n\n :param fn: function to invoke\n :type fn: Function(A) -> B\n :param key: function to decide if result should be taken from cache\n :type key: Function(A, A) -> Boolean\n :returns: new function invoking old one\n :rtype: Function(A) -> B\n \"\"\"\n cache: List[Any] = []\n\n def memoized_fn(argument):\n cached_result = find(cache, lambda cacheItem: key(cacheItem[0], argument))\n if cached_result is not None:\n return cached_result[1]\n fn_result = fn(argument)\n cache.append((argument, fn_result))\n\n return fn_result\n\n return memoized_fn", "has_branch": true, "total_branches": 2} {"prompt_id": 325, "project": "pymonet", "module": "pymonet.validation", "class": "Validation", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n \"\"\"\n Two Validations are equals when values and errors lists are equal.\n \"\"\"\n return (isinstance(other, Validation) and\n self.errors == other.errors and\n self.value == other.value)", "focal_method_lines": [7, 11], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Validation:\n\n def __init__(self, value, errors):\n self.value = value\n self.errors = errors\n\n def __eq__(self, other):\n \"\"\"\n Two Validations are equals when values and errors lists are equal.\n \"\"\"\n return (isinstance(other, Validation) and\n self.errors == other.errors and\n self.value == other.value)", "has_branch": false, "total_branches": 0} {"prompt_id": 326, "project": "pymonet", "module": "pymonet.validation", "class": "Validation", "method": "__str__", "focal_method_txt": " def __str__(self): # pragma: no cover\n if self.is_success():\n return 'Validation.success[{}]'.format(self.value)\n return 'Validation.fail[{}, {}]'.format(self.value, self.errors)", "focal_method_lines": [15, 18], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Validation:\n\n def __init__(self, value, errors):\n self.value = value\n self.errors = errors\n\n def __str__(self): # pragma: no cover\n if self.is_success():\n return 'Validation.success[{}]'.format(self.value)\n return 'Validation.fail[{}, {}]'.format(self.value, self.errors)", "has_branch": false, "total_branches": 0} {"prompt_id": 327, "project": "pymonet", "module": "pymonet.validation", "class": "Validation", "method": "to_maybe", "focal_method_txt": " def to_maybe(self):\n \"\"\"\n Transform Validation to Maybe.\n\n :returns: Maybe with Validation Value when Validation has no errors, in other case empty Maybe\n :rtype: Maybe[A | None]\n \"\"\"\n from pymonet.maybe import Maybe\n\n if self.is_success():\n return Maybe.just(self.value)\n return Maybe.nothing()", "focal_method_lines": [110, 121], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Validation:\n\n def __init__(self, value, errors):\n self.value = value\n self.errors = errors\n\n def to_maybe(self):\n \"\"\"\n Transform Validation to Maybe.\n\n :returns: Maybe with Validation Value when Validation has no errors, in other case empty Maybe\n :rtype: Maybe[A | None]\n \"\"\"\n from pymonet.maybe import Maybe\n\n if self.is_success():\n return Maybe.just(self.value)\n return Maybe.nothing()", "has_branch": true, "total_branches": 2} {"prompt_id": 328, "project": "pymonet", "module": "pymonet.validation", "class": "Validation", "method": "to_lazy", "focal_method_txt": " def to_lazy(self):\n \"\"\"\n Transform Validation to Try.\n\n :returns: Lazy monad with function returning Validation value\n :rtype: Lazy[Function() -> (A | None)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "focal_method_lines": [134, 143], "in_stack": false, "globals": [], "type_context": "\n\n\n\nclass Validation:\n\n def __init__(self, value, errors):\n self.value = value\n self.errors = errors\n\n def to_lazy(self):\n \"\"\"\n Transform Validation to Try.\n\n :returns: Lazy monad with function returning Validation value\n :rtype: Lazy[Function() -> (A | None)]\n \"\"\"\n from pymonet.lazy import Lazy\n\n return Lazy(lambda: self.value)", "has_branch": true, "total_branches": 2} {"prompt_id": 329, "project": "pypara", "module": "pypara.accounting.journaling", "class": "ReadJournalEntries", "method": "__call__", "focal_method_txt": " def __call__(self, period: DateRange) -> Iterable[JournalEntry[_T]]:\n pass", "focal_method_lines": [178, 179], "in_stack": false, "globals": ["__all__", "_T", "_debit_mapping"], "type_context": "import datetime\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Dict, Generic, Iterable, List, Protocol, Set, TypeVar\nfrom ..commons.numbers import Amount, Quantity, isum\nfrom ..commons.others import Guid, makeguid\nfrom ..commons.zeitgeist import DateRange\nfrom .accounts import Account, AccountType\n\n__all__ = [\n \"Direction\",\n \"JournalEntry\",\n \"Posting\",\n \"ReadJournalEntries\",\n]\n_T = TypeVar(\"_T\")\n_debit_mapping: Dict[Direction, Set[AccountType]] = {\n Direction.INC: {AccountType.ASSETS, AccountType.EQUITIES, AccountType.LIABILITIES},\n Direction.DEC: {AccountType.REVENUES, AccountType.EXPENSES},\n}\n\nclass ReadJournalEntries(Protocol[_T]):\n\n def __call__(self, period: DateRange) -> Iterable[JournalEntry[_T]]:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 330, "project": "pypara", "module": "pypara.accounting.ledger", "class": "", "method": "build_general_ledger", "focal_method_txt": "def build_general_ledger(\n period: DateRange, journal: Iterable[JournalEntry[_T]], initial: InitialBalances\n) -> GeneralLedger[_T]:\n \"\"\"\n Builds a general ledger.\n\n :param period: Accounting period.\n :param journal: All available journal entries.\n :param initial: Opening balances for terminal accounts, if any.\n :return: A :py:class:`GeneralLedger` instance.\n \"\"\"\n ## Initialize ledgers buffer as per available initial balances:\n ledgers: Dict[Account, Ledger[_T]] = {a: Ledger(a, b) for a, b in initial.items()}\n\n ## Iterate over journal postings and populate ledgers:\n for posting in (p for j in journal for p in j.postings if period.since <= j.date <= period.until):\n ## Check if we have the ledger yet, and create if not:\n if posting.account not in ledgers:\n ledgers[posting.account] = Ledger(posting.account, Balance(period.since, Quantity(Decimal(0))))\n\n ## Add the posting to the ledger:\n ledgers[posting.account].add(posting)\n\n ## Done, return general ledger.\n return GeneralLedger(period, ledgers)", "focal_method_lines": [161, 185], "in_stack": false, "globals": ["__all__", "_T", "InitialBalances"], "type_context": "import datetime\nfrom dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar\nfrom ..commons.numbers import Amount, Quantity\nfrom ..commons.zeitgeist import DateRange\nfrom .accounts import Account\nfrom .generic import Balance\nfrom .journaling import JournalEntry, Posting, ReadJournalEntries\n\n__all__ = [\n \"GeneralLedger\",\n \"GeneralLedgerProgram\",\n \"InitialBalances\",\n \"Ledger\",\n \"LedgerEntry\",\n \"ReadInitialBalances\",\n \"build_general_ledger\",\n \"compile_general_ledger_program\",\n]\n_T = TypeVar(\"_T\")\nInitialBalances = Dict[Account, Balance]\n\ndef build_general_ledger(\n period: DateRange, journal: Iterable[JournalEntry[_T]], initial: InitialBalances\n) -> GeneralLedger[_T]:\n \"\"\"\n Builds a general ledger.\n\n :param period: Accounting period.\n :param journal: All available journal entries.\n :param initial: Opening balances for terminal accounts, if any.\n :return: A :py:class:`GeneralLedger` instance.\n \"\"\"\n ## Initialize ledgers buffer as per available initial balances:\n ledgers: Dict[Account, Ledger[_T]] = {a: Ledger(a, b) for a, b in initial.items()}\n\n ## Iterate over journal postings and populate ledgers:\n for posting in (p for j in journal for p in j.postings if period.since <= j.date <= period.until):\n ## Check if we have the ledger yet, and create if not:\n if posting.account not in ledgers:\n ledgers[posting.account] = Ledger(posting.account, Balance(period.since, Quantity(Decimal(0))))\n\n ## Add the posting to the ledger:\n ledgers[posting.account].add(posting)\n\n ## Done, return general ledger.\n return GeneralLedger(period, ledgers)", "has_branch": true, "total_branches": 2} {"prompt_id": 331, "project": "pypara", "module": "pypara.accounting.ledger", "class": "", "method": "compile_general_ledger_program", "focal_method_txt": "def compile_general_ledger_program(\n read_initial_balances: ReadInitialBalances,\n read_journal_entries: ReadJournalEntries[_T],\n) -> GeneralLedgerProgram[_T]:\n \"\"\"\n Consumes implementations of the algebra and returns a program which consumes opening and closing dates and produces\n a general ledger.\n\n :param read_initial_balances: Algebra implementation which reads initial balances.\n :param read_journal_entries: Algebra implementation which reads journal entries.\n :return: A function which consumes opening and closing dates and produces a general ledger\n \"\"\"\n\n def _program(period: DateRange) -> GeneralLedger[_T]:\n \"\"\"\n Consumes the opening and closing dates and produces a general ledger.\n\n :param period: Accounting period.\n :return: A general ledger.\n \"\"\"\n ## Get initial balances as of the end of previous financial period:\n initial_balances = read_initial_balances(period)\n\n ## Read journal entries and post each of them:\n journal_entries = read_journal_entries(period)\n\n ## Build the general ledger and return:\n return build_general_ledger(period, journal_entries, initial_balances)\n\n ## Return the compiled program.\n return _program", "focal_method_lines": [206, 236], "in_stack": false, "globals": ["__all__", "_T", "InitialBalances"], "type_context": "import datetime\nfrom dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar\nfrom ..commons.numbers import Amount, Quantity\nfrom ..commons.zeitgeist import DateRange\nfrom .accounts import Account\nfrom .generic import Balance\nfrom .journaling import JournalEntry, Posting, ReadJournalEntries\n\n__all__ = [\n \"GeneralLedger\",\n \"GeneralLedgerProgram\",\n \"InitialBalances\",\n \"Ledger\",\n \"LedgerEntry\",\n \"ReadInitialBalances\",\n \"build_general_ledger\",\n \"compile_general_ledger_program\",\n]\n_T = TypeVar(\"_T\")\nInitialBalances = Dict[Account, Balance]\n\ndef compile_general_ledger_program(\n read_initial_balances: ReadInitialBalances,\n read_journal_entries: ReadJournalEntries[_T],\n) -> GeneralLedgerProgram[_T]:\n \"\"\"\n Consumes implementations of the algebra and returns a program which consumes opening and closing dates and produces\n a general ledger.\n\n :param read_initial_balances: Algebra implementation which reads initial balances.\n :param read_journal_entries: Algebra implementation which reads journal entries.\n :return: A function which consumes opening and closing dates and produces a general ledger\n \"\"\"\n\n def _program(period: DateRange) -> GeneralLedger[_T]:\n \"\"\"\n Consumes the opening and closing dates and produces a general ledger.\n\n :param period: Accounting period.\n :return: A general ledger.\n \"\"\"\n ## Get initial balances as of the end of previous financial period:\n initial_balances = read_initial_balances(period)\n\n ## Read journal entries and post each of them:\n journal_entries = read_journal_entries(period)\n\n ## Build the general ledger and return:\n return build_general_ledger(period, journal_entries, initial_balances)\n\n ## Return the compiled program.\n return _program", "has_branch": false, "total_branches": 0} {"prompt_id": 332, "project": "pypara", "module": "pypara.accounting.ledger", "class": "ReadInitialBalances", "method": "__call__", "focal_method_txt": " def __call__(self, period: DateRange) -> InitialBalances:\n pass", "focal_method_lines": [193, 194], "in_stack": false, "globals": ["__all__", "_T", "InitialBalances"], "type_context": "import datetime\nfrom dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar\nfrom ..commons.numbers import Amount, Quantity\nfrom ..commons.zeitgeist import DateRange\nfrom .accounts import Account\nfrom .generic import Balance\nfrom .journaling import JournalEntry, Posting, ReadJournalEntries\n\n__all__ = [\n \"GeneralLedger\",\n \"GeneralLedgerProgram\",\n \"InitialBalances\",\n \"Ledger\",\n \"LedgerEntry\",\n \"ReadInitialBalances\",\n \"build_general_ledger\",\n \"compile_general_ledger_program\",\n]\n_T = TypeVar(\"_T\")\nInitialBalances = Dict[Account, Balance]\n\nclass ReadInitialBalances(Protocol):\n\n def __call__(self, period: DateRange) -> InitialBalances:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 333, "project": "pypara", "module": "pypara.accounting.ledger", "class": "GeneralLedgerProgram", "method": "__call__", "focal_method_txt": " def __call__(self, period: DateRange) -> GeneralLedger[_T]:\n pass", "focal_method_lines": [202, 203], "in_stack": false, "globals": ["__all__", "_T", "InitialBalances"], "type_context": "import datetime\nfrom dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar\nfrom ..commons.numbers import Amount, Quantity\nfrom ..commons.zeitgeist import DateRange\nfrom .accounts import Account\nfrom .generic import Balance\nfrom .journaling import JournalEntry, Posting, ReadJournalEntries\n\n__all__ = [\n \"GeneralLedger\",\n \"GeneralLedgerProgram\",\n \"InitialBalances\",\n \"Ledger\",\n \"LedgerEntry\",\n \"ReadInitialBalances\",\n \"build_general_ledger\",\n \"compile_general_ledger_program\",\n]\n_T = TypeVar(\"_T\")\nInitialBalances = Dict[Account, Balance]\n\nclass GeneralLedgerProgram(Protocol[_T]):\n\n def __call__(self, period: DateRange) -> GeneralLedger[_T]:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 334, "project": "pypara", "module": "pypara.dcc", "class": "DCC", "method": "calculate_fraction", "focal_method_txt": " def calculate_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:\n \"\"\"\n Calculates the day count fraction based on the underlying methodology after performing some general checks.\n \"\"\"\n ## Checks if dates are provided properly:\n if not start <= asof <= end:\n ## Nope, return 0:\n return ZERO\n\n ## Cool, we can proceed with calculation based on the methodology:\n return self[3](start, asof, end, freq)", "focal_method_lines": [207, 217], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCC(NamedTuple):\n\n name: str\n\n altnames: Set[str]\n\n currencies: Set[Currency]\n\n calculate_fraction_method: DCFC\n\n def calculate_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:\n \"\"\"\n Calculates the day count fraction based on the underlying methodology after performing some general checks.\n \"\"\"\n ## Checks if dates are provided properly:\n if not start <= asof <= end:\n ## Nope, return 0:\n return ZERO\n\n ## Cool, we can proceed with calculation based on the methodology:\n return self[3](start, asof, end, freq)", "has_branch": true, "total_branches": 2} {"prompt_id": 335, "project": "pypara", "module": "pypara.dcc", "class": "DCC", "method": "calculate_daily_fraction", "focal_method_txt": " def calculate_daily_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:\n \"\"\"\n Calculates daily fraction.\n \"\"\"\n ## Get t-1 for asof:\n asof_minus_1 = asof - datetime.timedelta(days=1)\n\n ## Get the yesterday's factor:\n if asof_minus_1 < start:\n yfact = ZERO\n else:\n yfact = self.calculate_fraction_method(start, asof_minus_1, end, freq)\n\n ## Get today's factor:\n tfact = self.calculate_fraction_method(start, asof, end, freq)\n\n ## Get the factor and return:\n return tfact - yfact", "focal_method_lines": [219, 236], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCC(NamedTuple):\n\n name: str\n\n altnames: Set[str]\n\n currencies: Set[Currency]\n\n calculate_fraction_method: DCFC\n\n def calculate_daily_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:\n \"\"\"\n Calculates daily fraction.\n \"\"\"\n ## Get t-1 for asof:\n asof_minus_1 = asof - datetime.timedelta(days=1)\n\n ## Get the yesterday's factor:\n if asof_minus_1 < start:\n yfact = ZERO\n else:\n yfact = self.calculate_fraction_method(start, asof_minus_1, end, freq)\n\n ## Get today's factor:\n tfact = self.calculate_fraction_method(start, asof, end, freq)\n\n ## Get the factor and return:\n return tfact - yfact", "has_branch": true, "total_branches": 2} {"prompt_id": 336, "project": "pypara", "module": "pypara.dcc", "class": "DCC", "method": "interest", "focal_method_txt": " def interest(\n self,\n principal: Money,\n rate: Decimal,\n start: Date,\n asof: Date,\n end: Optional[Date] = None,\n freq: Optional[Decimal] = None,\n ) -> Money:\n \"\"\"\n Calculates the accrued interest.\n \"\"\"\n return principal * rate * self.calculate_fraction(start, asof, end or asof, freq)", "focal_method_lines": [238, 250], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCC(NamedTuple):\n\n name: str\n\n altnames: Set[str]\n\n currencies: Set[Currency]\n\n calculate_fraction_method: DCFC\n\n def interest(\n self,\n principal: Money,\n rate: Decimal,\n start: Date,\n asof: Date,\n end: Optional[Date] = None,\n freq: Optional[Decimal] = None,\n ) -> Money:\n \"\"\"\n Calculates the accrued interest.\n \"\"\"\n return principal * rate * self.calculate_fraction(start, asof, end or asof, freq)", "has_branch": false, "total_branches": 0} {"prompt_id": 337, "project": "pypara", "module": "pypara.dcc", "class": "DCC", "method": "coupon", "focal_method_txt": " def coupon(\n self,\n principal: Money,\n rate: Decimal,\n start: Date,\n asof: Date,\n end: Date,\n freq: Union[int, Decimal],\n eom: Optional[int] = None,\n ) -> Money:\n \"\"\"\n Calculates the accrued interest for the coupon payment.\n\n This method is primarily used for bond coupon accruals which assumes the start date to be the first of regular\n payment schedules.\n \"\"\"\n ## Find the previous and next payment dates:\n prevdate = _last_payment_date(start, asof, freq, eom)\n nextdate = _next_payment_date(prevdate, freq, eom)\n\n ## Calculate the interest and return:\n return self.interest(principal, rate, prevdate, asof, nextdate, Decimal(freq))", "focal_method_lines": [252, 273], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCC(NamedTuple):\n\n name: str\n\n altnames: Set[str]\n\n currencies: Set[Currency]\n\n calculate_fraction_method: DCFC\n\n def coupon(\n self,\n principal: Money,\n rate: Decimal,\n start: Date,\n asof: Date,\n end: Date,\n freq: Union[int, Decimal],\n eom: Optional[int] = None,\n ) -> Money:\n \"\"\"\n Calculates the accrued interest for the coupon payment.\n\n This method is primarily used for bond coupon accruals which assumes the start date to be the first of regular\n payment schedules.\n \"\"\"\n ## Find the previous and next payment dates:\n prevdate = _last_payment_date(start, asof, freq, eom)\n nextdate = _next_payment_date(prevdate, freq, eom)\n\n ## Calculate the interest and return:\n return self.interest(principal, rate, prevdate, asof, nextdate, Decimal(freq))", "has_branch": false, "total_branches": 0} {"prompt_id": 338, "project": "pypara", "module": "pypara.dcc", "class": "DCCRegistryMachinery", "method": "register", "focal_method_txt": " def register(self, dcc: DCC) -> None:\n \"\"\"\n Attempts to register the given day count convention.\n \"\"\"\n ## Check if the main name is ever registered before:\n if self._is_registered(dcc.name):\n ## Yep, raise a TypeError:\n raise TypeError(f\"Day count convention '{dcc.name}' is already registered\")\n\n ## Add to the main buffer:\n self._buffer_main[dcc.name] = dcc\n\n ## Check if there is any registry conflict:\n for name in dcc.altnames:\n ## Check if the name is ever registered:\n if self._is_registered(name):\n ## Yep, raise a TypeError:\n raise TypeError(f\"Day count convention '{dcc.name}' is already registered\")\n\n ## Register to the alternative buffer:\n self._buffer_altn[name] = dcc", "focal_method_lines": [309, 329], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCCRegistryMachinery:\n\n def __init__(self) -> None:\n \"\"\"\n Initializes the registry.\n \"\"\"\n ## Define the main registry buffer:\n self._buffer_main: Dict[str, DCC] = {}\n\n ## Defines the registry buffer for alternative DCC names:\n self._buffer_altn: Dict[str, DCC] = {}\n\n def register(self, dcc: DCC) -> None:\n \"\"\"\n Attempts to register the given day count convention.\n \"\"\"\n ## Check if the main name is ever registered before:\n if self._is_registered(dcc.name):\n ## Yep, raise a TypeError:\n raise TypeError(f\"Day count convention '{dcc.name}' is already registered\")\n\n ## Add to the main buffer:\n self._buffer_main[dcc.name] = dcc\n\n ## Check if there is any registry conflict:\n for name in dcc.altnames:\n ## Check if the name is ever registered:\n if self._is_registered(name):\n ## Yep, raise a TypeError:\n raise TypeError(f\"Day count convention '{dcc.name}' is already registered\")\n\n ## Register to the alternative buffer:\n self._buffer_altn[name] = dcc", "has_branch": true, "total_branches": 2} {"prompt_id": 339, "project": "pypara", "module": "pypara.dcc", "class": "DCCRegistryMachinery", "method": "find", "focal_method_txt": " def find(self, name: str) -> Optional[DCC]:\n \"\"\"\n Attempts to find the day count convention by the given name.\n\n Note that all day count conventions are registered under stripped, uppercased names. Therefore,\n the implementation will first attempt to find by given name as is. If it can not find it, it will\n strip and uppercase the name and try to find it as such as a last resort.\n \"\"\"\n return self._find_strict(name) or self._find_strict(name.strip().upper())", "focal_method_lines": [337, 345], "in_stack": false, "globals": ["__all__", "DCFC", "DCCRegistry"], "type_context": "import calendar\nimport datetime\nfrom decimal import Decimal\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union\nfrom dateutil.relativedelta import relativedelta\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currencies, Currency\nfrom .monetary import Money\n\n__all__ = [\"DCC\", \"DCCRegistry\"]\nDCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal]\nDCCRegistry = DCCRegistryMachinery()\n\nclass DCCRegistryMachinery:\n\n def __init__(self) -> None:\n \"\"\"\n Initializes the registry.\n \"\"\"\n ## Define the main registry buffer:\n self._buffer_main: Dict[str, DCC] = {}\n\n ## Defines the registry buffer for alternative DCC names:\n self._buffer_altn: Dict[str, DCC] = {}\n\n def find(self, name: str) -> Optional[DCC]:\n \"\"\"\n Attempts to find the day count convention by the given name.\n\n Note that all day count conventions are registered under stripped, uppercased names. Therefore,\n the implementation will first attempt to find by given name as is. If it can not find it, it will\n strip and uppercase the name and try to find it as such as a last resort.\n \"\"\"\n return self._find_strict(name) or self._find_strict(name.strip().upper())", "has_branch": false, "total_branches": 0} {"prompt_id": 340, "project": "pypara", "module": "pypara.exchange", "class": "FXRateLookupError", "method": "__init__", "focal_method_txt": " def __init__(self, ccy1: Currency, ccy2: Currency, asof: Date) -> None:\n \"\"\"\n Initializes the foreign exchange rate lookup error.\n \"\"\"\n ## Keep the slots:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.asof = asof\n\n ## Set the message:\n super().__init__(f\"Foreign exchange rate for {ccy1}/{ccy2} not found as of {asof}\")", "focal_method_lines": [20, 30], "in_stack": false, "globals": ["__all__"], "type_context": "from abc import ABCMeta, abstractmethod\nfrom decimal import Decimal\nfrom typing import Iterable, NamedTuple, Optional, Tuple\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\n\n__all__ = [\"FXRate\", \"FXRateLookupError\", \"FXRateService\"]\n\nclass FXRateLookupError(LookupError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, asof: Date) -> None:\n \"\"\"\n Initializes the foreign exchange rate lookup error.\n \"\"\"\n ## Keep the slots:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.asof = asof\n\n ## Set the message:\n super().__init__(f\"Foreign exchange rate for {ccy1}/{ccy2} not found as of {asof}\")", "has_branch": false, "total_branches": 0} {"prompt_id": 341, "project": "pypara", "module": "pypara.exchange", "class": "FXRate", "method": "__invert__", "focal_method_txt": " def __invert__(self) -> \"FXRate\":\n \"\"\"\n Returns the inverted foreign exchange rate.\n\n >>> import datetime\n >>> from decimal import Decimal\n >>> from pypara.currencies import Currencies\n >>> nrate = FXRate(Currencies[\"EUR\"], Currencies[\"USD\"], datetime.date.today(), Decimal(\"2\"))\n >>> rrate = FXRate(Currencies[\"USD\"], Currencies[\"EUR\"], datetime.date.today(), Decimal(\"0.5\"))\n >>> ~nrate == rrate\n True\n \"\"\"\n return FXRate(self[1], self[0], self[2], self[3] ** -1)", "focal_method_lines": [80, 92], "in_stack": false, "globals": ["__all__"], "type_context": "from abc import ABCMeta, abstractmethod\nfrom decimal import Decimal\nfrom typing import Iterable, NamedTuple, Optional, Tuple\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\n\n__all__ = [\"FXRate\", \"FXRateLookupError\", \"FXRateService\"]\n\nclass FXRate(NamedTuple):\n\n ccy1: Currency\n\n ccy2: Currency\n\n date: Date\n\n value: Decimal\n\n def __invert__(self) -> \"FXRate\":\n \"\"\"\n Returns the inverted foreign exchange rate.\n\n >>> import datetime\n >>> from decimal import Decimal\n >>> from pypara.currencies import Currencies\n >>> nrate = FXRate(Currencies[\"EUR\"], Currencies[\"USD\"], datetime.date.today(), Decimal(\"2\"))\n >>> rrate = FXRate(Currencies[\"USD\"], Currencies[\"EUR\"], datetime.date.today(), Decimal(\"0.5\"))\n >>> ~nrate == rrate\n True\n \"\"\"\n return FXRate(self[1], self[0], self[2], self[3] ** -1)", "has_branch": false, "total_branches": 0} {"prompt_id": 342, "project": "pypara", "module": "pypara.exchange", "class": "FXRateService", "method": "query", "focal_method_txt": " @abstractmethod\n def query(self, ccy1: Currency, ccy2: Currency, asof: Date, strict: bool = False) -> Optional[FXRate]:\n \"\"\"\n Returns the foreign exchange rate of a given currency pair as of a given date.\n\n :param ccy1: The first currency of foreign exchange rate.\n :param ccy2: The second currency of foreign exchange rate.\n :param asof: Temporal dimension the foreign exchange rate is effective as of.\n :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found.\n :return: The foreign exhange rate as a :class:`Decimal` instance or None.\n \"\"\"\n pass", "focal_method_lines": [141, 151], "in_stack": false, "globals": ["__all__"], "type_context": "from abc import ABCMeta, abstractmethod\nfrom decimal import Decimal\nfrom typing import Iterable, NamedTuple, Optional, Tuple\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\n\n__all__ = [\"FXRate\", \"FXRateLookupError\", \"FXRateService\"]\n\nclass FXRateService(metaclass=ABCMeta):\n\n default: Optional[\"FXRateService\"] = None\n\n TQuery = Tuple[Currency, Currency, Date]\n\n @abstractmethod\n def query(self, ccy1: Currency, ccy2: Currency, asof: Date, strict: bool = False) -> Optional[FXRate]:\n \"\"\"\n Returns the foreign exchange rate of a given currency pair as of a given date.\n\n :param ccy1: The first currency of foreign exchange rate.\n :param ccy2: The second currency of foreign exchange rate.\n :param asof: Temporal dimension the foreign exchange rate is effective as of.\n :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found.\n :return: The foreign exhange rate as a :class:`Decimal` instance or None.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 343, "project": "pypara", "module": "pypara.exchange", "class": "FXRateService", "method": "queries", "focal_method_txt": " @abstractmethod\n def queries(self, queries: Iterable[TQuery], strict: bool = False) -> Iterable[Optional[FXRate]]:\n \"\"\"\n Returns foreign exchange rates for a given collection of currency pairs and dates.\n\n :param queries: An iterable of :class:`Currency`, :class:`Currency` and :class:`Temporal` tuples.\n :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found.\n :return: An iterable of rates.\n \"\"\"\n pass", "focal_method_lines": [154, 162], "in_stack": false, "globals": ["__all__"], "type_context": "from abc import ABCMeta, abstractmethod\nfrom decimal import Decimal\nfrom typing import Iterable, NamedTuple, Optional, Tuple\nfrom .commons.numbers import ONE, ZERO\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\n\n__all__ = [\"FXRate\", \"FXRateLookupError\", \"FXRateService\"]\n\nclass FXRateService(metaclass=ABCMeta):\n\n default: Optional[\"FXRateService\"] = None\n\n TQuery = Tuple[Currency, Currency, Date]\n\n @abstractmethod\n def queries(self, queries: Iterable[TQuery], strict: bool = False) -> Iterable[Optional[FXRate]]:\n \"\"\"\n Returns foreign exchange rates for a given collection of currency pairs and dates.\n\n :param queries: An iterable of :class:`Currency`, :class:`Currency` and :class:`Temporal` tuples.\n :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found.\n :return: An iterable of rates.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 344, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "is_equal", "focal_method_txt": " @abstractmethod\n def is_equal(self, other: Any) -> bool:\n \"\"\"\n Checks the equality of two money objects.\n\n In particular:\n\n 1. ``True`` if ``other`` is a money object **and** all slots are same.\n 2. ``False`` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [88, 97], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def is_equal(self, other: Any) -> bool:\n \"\"\"\n Checks the equality of two money objects.\n\n In particular:\n\n 1. ``True`` if ``other`` is a money object **and** all slots are same.\n 2. ``False`` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 345, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "as_boolean", "focal_method_txt": " @abstractmethod\n def as_boolean(self) -> bool:\n \"\"\"\n Returns the logical representation of the money object.\n\n In particular:\n\n 1. ``False`` if money is *undefined* **or** money quantity is ``zero``.\n 2. ``True`` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [100, 109], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_boolean(self) -> bool:\n \"\"\"\n Returns the logical representation of the money object.\n\n In particular:\n\n 1. ``False`` if money is *undefined* **or** money quantity is ``zero``.\n 2. ``True`` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 346, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "as_float", "focal_method_txt": " @abstractmethod\n def as_float(self) -> float:\n \"\"\"\n Returns the quantity as a ``float`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [112, 116], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_float(self) -> float:\n \"\"\"\n Returns the quantity as a ``float`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 347, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "as_integer", "focal_method_txt": " @abstractmethod\n def as_integer(self) -> int:\n \"\"\"\n Returns the quantity as an ``int`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [119, 123], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_integer(self) -> int:\n \"\"\"\n Returns the quantity as an ``int`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 348, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "abs", "focal_method_txt": " @abstractmethod\n def abs(self) -> \"Money\":\n \"\"\"\n Returns the absolute money if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [126, 130], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def abs(self) -> \"Money\":\n \"\"\"\n Returns the absolute money if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 349, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "negative", "focal_method_txt": " @abstractmethod\n def negative(self) -> \"Money\":\n \"\"\"\n Negates the quantity of the monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [133, 137], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def negative(self) -> \"Money\":\n \"\"\"\n Negates the quantity of the monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 350, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "positive", "focal_method_txt": " @abstractmethod\n def positive(self) -> \"Money\":\n \"\"\"\n Returns same monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [140, 144], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def positive(self) -> \"Money\":\n \"\"\"\n Returns same monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 351, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "round", "focal_method_txt": " @abstractmethod\n def round(self, ndigits: int = 0) -> \"Money\":\n \"\"\"\n Rounds the quantity of the monetary value to ``ndigits`` by using ``HALF_EVEN`` method if *defined*, itself\n otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [147, 152], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def round(self, ndigits: int = 0) -> \"Money\":\n \"\"\"\n Rounds the quantity of the monetary value to ``ndigits`` by using ``HALF_EVEN`` method if *defined*, itself\n otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 352, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "add", "focal_method_txt": " @abstractmethod\n def add(self, other: \"Money\") -> \"Money\":\n \"\"\"\n Performs monetary addition on the money object and the given ``other`` money object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined money objects.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [155, 165], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def add(self, other: \"Money\") -> \"Money\":\n \"\"\"\n Performs monetary addition on the money object and the given ``other`` money object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined money objects.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 353, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "scalar_add", "focal_method_txt": " @abstractmethod\n def scalar_add(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar addition on the quantity of the money.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [168, 174], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def scalar_add(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar addition on the quantity of the money.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 354, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "subtract", "focal_method_txt": " @abstractmethod\n def subtract(self, other: \"Money\") -> \"Money\":\n \"\"\"\n Performs monetary subtraction on the money object and the given ``other`` money object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined money objects.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [177, 187], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def subtract(self, other: \"Money\") -> \"Money\":\n \"\"\"\n Performs monetary subtraction on the money object and the given ``other`` money object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined money objects.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 355, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "scalar_subtract", "focal_method_txt": " @abstractmethod\n def scalar_subtract(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar subtraction on the quantity of the money.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [190, 196], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def scalar_subtract(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar subtraction on the quantity of the money.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 356, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "multiply", "focal_method_txt": " @abstractmethod\n def multiply(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar multiplication.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [199, 205], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def multiply(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs scalar multiplication.\n\n Note that undefined money object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 357, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "divide", "focal_method_txt": " @abstractmethod\n def divide(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs ordinary division on the money object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined money object.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [208, 214], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def divide(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs ordinary division on the money object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined money object.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 358, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "floor_divide", "focal_method_txt": " @abstractmethod\n def floor_divide(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs floor division on the money object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined money object.\n\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [217, 224], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def floor_divide(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs floor division on the money object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined money object.\n\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 359, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "lt", "focal_method_txt": " @abstractmethod\n def lt(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"less than\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are always less than ``other`` if ``other`` is not undefined, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [227, 237], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def lt(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"less than\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are always less than ``other`` if ``other`` is not undefined, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 360, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "lte", "focal_method_txt": " @abstractmethod\n def lte(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"less than or equal to\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are always less than or equal to ``other``, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [240, 250], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def lte(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"less than or equal to\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are always less than or equal to ``other``, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 361, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "gt", "focal_method_txt": " @abstractmethod\n def gt(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"greater than\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are never greater than ``other``,\n 2. Defined money objects are always greater than ``other`` if other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [253, 264], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def gt(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"greater than\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are never greater than ``other``,\n 2. Defined money objects are always greater than ``other`` if other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 362, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "gte", "focal_method_txt": " @abstractmethod\n def gte(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"greater than or equal to\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are never greater than or equal to ``other`` if ``other`` is defined,\n 2. Undefined money objects are greater than or equal to ``other`` if ``other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [267, 278], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def gte(self, other: \"Money\") -> bool:\n \"\"\"\n Applies \"greater than or equal to\" comparison against ``other`` money.\n\n Note that::\n\n 1. Undefined money objects are never greater than or equal to ``other`` if ``other`` is defined,\n 2. Undefined money objects are greater than or equal to ``other`` if ``other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined money objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 363, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "with_ccy", "focal_method_txt": " @abstractmethod\n def with_ccy(self, ccy: Currency) -> \"Money\":\n \"\"\"\n Creates a new money object with the given currency if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [281, 285], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_ccy(self, ccy: Currency) -> \"Money\":\n \"\"\"\n Creates a new money object with the given currency if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 364, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "with_qty", "focal_method_txt": " @abstractmethod\n def with_qty(self, qty: Decimal) -> \"Money\":\n \"\"\"\n Creates a new money object with the given quantity if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [288, 292], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_qty(self, qty: Decimal) -> \"Money\":\n \"\"\"\n Creates a new money object with the given quantity if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 365, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "with_dov", "focal_method_txt": " @abstractmethod\n def with_dov(self, dov: Date) -> \"Money\":\n \"\"\"\n Creates a new money object with the given value date if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [295, 299], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_dov(self, dov: Date) -> \"Money\":\n \"\"\"\n Creates a new money object with the given value date if money is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 366, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "convert", "focal_method_txt": " @abstractmethod\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Money\":\n \"\"\"\n Converts the monetary value from one currency to another.\n\n Raises :class:`FXRateLookupError` if no foreign exchange rate can be found for conversion.\n\n Note that we will carry the date forward as per ``asof`` date.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [302, 310], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Money\":\n \"\"\"\n Converts the monetary value from one currency to another.\n\n Raises :class:`FXRateLookupError` if no foreign exchange rate can be found for conversion.\n\n Note that we will carry the date forward as per ``asof`` date.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 367, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__bool__", "focal_method_txt": " @abstractmethod\n def __bool__(self) -> bool:\n pass", "focal_method_lines": [330, 331], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __bool__(self) -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 368, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__eq__", "focal_method_txt": " @abstractmethod\n def __eq__(self, other: Any) -> bool:\n pass", "focal_method_lines": [334, 335], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __eq__(self, other: Any) -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 369, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__abs__", "focal_method_txt": " @abstractmethod\n def __abs__(self) -> \"Money\":\n pass", "focal_method_lines": [338, 339], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __abs__(self) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 370, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__float__", "focal_method_txt": " @abstractmethod\n def __float__(self) -> float:\n pass", "focal_method_lines": [342, 343], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __float__(self) -> float:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 371, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__int__", "focal_method_txt": " @abstractmethod\n def __int__(self) -> int:\n pass", "focal_method_lines": [346, 347], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __int__(self) -> int:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 372, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__neg__", "focal_method_txt": " @abstractmethod\n def __neg__(self) -> \"Money\":\n pass", "focal_method_lines": [365, 366], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __neg__(self) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 373, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__pos__", "focal_method_txt": " @abstractmethod\n def __pos__(self) -> \"Money\":\n pass", "focal_method_lines": [369, 370], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __pos__(self) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 374, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__add__", "focal_method_txt": " @abstractmethod\n def __add__(self, other: \"Money\") -> \"Money\":\n pass", "focal_method_lines": [373, 374], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __add__(self, other: \"Money\") -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 375, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__sub__", "focal_method_txt": " @abstractmethod\n def __sub__(self, other: \"Money\") -> \"Money\":\n pass", "focal_method_lines": [377, 378], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __sub__(self, other: \"Money\") -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 376, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__mul__", "focal_method_txt": " @abstractmethod\n def __mul__(self, other: Numeric) -> \"Money\":\n pass", "focal_method_lines": [381, 382], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __mul__(self, other: Numeric) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 377, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__truediv__", "focal_method_txt": " @abstractmethod\n def __truediv__(self, other: Numeric) -> \"Money\":\n pass", "focal_method_lines": [385, 386], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __truediv__(self, other: Numeric) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 378, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__floordiv__", "focal_method_txt": " @abstractmethod\n def __floordiv__(self, other: Numeric) -> \"Money\":\n pass", "focal_method_lines": [389, 390], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __floordiv__(self, other: Numeric) -> \"Money\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 379, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__lt__", "focal_method_txt": " @abstractmethod\n def __lt__(self, other: \"Money\") -> bool:\n pass", "focal_method_lines": [393, 394], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __lt__(self, other: \"Money\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 380, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__le__", "focal_method_txt": " @abstractmethod\n def __le__(self, other: \"Money\") -> bool:\n pass", "focal_method_lines": [397, 398], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __le__(self, other: \"Money\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 381, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__gt__", "focal_method_txt": " @abstractmethod\n def __gt__(self, other: \"Money\") -> bool:\n pass", "focal_method_lines": [401, 402], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __gt__(self, other: \"Money\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 382, "project": "pypara", "module": "pypara.monetary", "class": "Money", "method": "__ge__", "focal_method_txt": " @abstractmethod\n def __ge__(self, other: \"Money\") -> bool:\n pass", "focal_method_lines": [405, 406], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Money:\n\n __slots__ = ()\n\n NA: \"Money\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __ge__(self, other: \"Money\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 383, "project": "pypara", "module": "pypara.monetary", "class": "SomeMoney", "method": "round", "focal_method_txt": " def round(self, ndigits: int = 0) -> \"Money\":\n c, q, d = self\n dec = c.decimals\n return SomeMoney(c, q.__round__(ndigits if ndigits < dec else dec), d)", "focal_method_lines": [444, 447], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass SomeMoney(Money, NamedTuple(\"SomeMoney\", [(\"ccy\", Currency), (\"qty\", Decimal), (\"dov\", Date)])):\n\n __slots__ = ()\n\n defined = True\n\n undefined = False\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def round(self, ndigits: int = 0) -> \"Money\":\n c, q, d = self\n dec = c.decimals\n return SomeMoney(c, q.__round__(ndigits if ndigits < dec else dec), d)", "has_branch": false, "total_branches": 0} {"prompt_id": 384, "project": "pypara", "module": "pypara.monetary", "class": "SomeMoney", "method": "with_dov", "focal_method_txt": " def with_dov(self, dov: Date) -> \"Money\":\n return SomeMoney(self[0], self[1], dov)", "focal_method_lines": [551, 552], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass SomeMoney(Money, NamedTuple(\"SomeMoney\", [(\"ccy\", Currency), (\"qty\", Decimal), (\"dov\", Date)])):\n\n __slots__ = ()\n\n defined = True\n\n undefined = False\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def with_dov(self, dov: Date) -> \"Money\":\n return SomeMoney(self[0], self[1], dov)", "has_branch": false, "total_branches": 0} {"prompt_id": 385, "project": "pypara", "module": "pypara.monetary", "class": "SomeMoney", "method": "convert", "focal_method_txt": " def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Money\":\n ## Get slots:\n ccy, qty, dov = self\n\n ## Get date of conversion:\n asof = asof or dov\n\n ## Attempt to get the FX rate:\n try:\n rate = FXRateService.default.query(ccy, to, asof, strict) # type: ignore\n except AttributeError as exc:\n if FXRateService.default is None:\n raise ProgrammingError(\"Did you implement and set the default FX rate service?\")\n else:\n raise exc\n\n ## Do we have a rate?\n if rate is None:\n ## Nope, shall we raise exception?\n if strict:\n ## Yep:\n raise FXRateLookupError(ccy, to, asof)\n else:\n ## Just return NA:\n return NoMoney\n\n ## Compute and return:\n return SomeMoney(to, (qty * rate.value).quantize(to.quantizer), asof)", "focal_method_lines": [554, 581], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass SomeMoney(Money, NamedTuple(\"SomeMoney\", [(\"ccy\", Currency), (\"qty\", Decimal), (\"dov\", Date)])):\n\n __slots__ = ()\n\n defined = True\n\n undefined = False\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Money\":\n ## Get slots:\n ccy, qty, dov = self\n\n ## Get date of conversion:\n asof = asof or dov\n\n ## Attempt to get the FX rate:\n try:\n rate = FXRateService.default.query(ccy, to, asof, strict) # type: ignore\n except AttributeError as exc:\n if FXRateService.default is None:\n raise ProgrammingError(\"Did you implement and set the default FX rate service?\")\n else:\n raise exc\n\n ## Do we have a rate?\n if rate is None:\n ## Nope, shall we raise exception?\n if strict:\n ## Yep:\n raise FXRateLookupError(ccy, to, asof)\n else:\n ## Just return NA:\n return NoMoney\n\n ## Compute and return:\n return SomeMoney(to, (qty * rate.value).quantize(to.quantizer), asof)", "has_branch": true, "total_branches": 2} {"prompt_id": 386, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "is_equal", "focal_method_txt": " @abstractmethod\n def is_equal(self, other: Any) -> bool:\n \"\"\"\n Checks the equality of two price objects.\n\n In particular:\n\n 1. ``True`` if ``other`` is a price object **and** all slots are same.\n 2. ``False`` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [771, 780], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def is_equal(self, other: Any) -> bool:\n \"\"\"\n Checks the equality of two price objects.\n\n In particular:\n\n 1. ``True`` if ``other`` is a price object **and** all slots are same.\n 2. ``False`` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 387, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "as_boolean", "focal_method_txt": " @abstractmethod\n def as_boolean(self) -> bool:\n \"\"\"\n Returns the logical representation of the price object.\n\n In particular:\n\n 1. ``False`` if price is *undefined* **or** price quantity is ``zero``.\n 2. ``True`` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [783, 792], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_boolean(self) -> bool:\n \"\"\"\n Returns the logical representation of the price object.\n\n In particular:\n\n 1. ``False`` if price is *undefined* **or** price quantity is ``zero``.\n 2. ``True`` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 388, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "as_float", "focal_method_txt": " @abstractmethod\n def as_float(self) -> float:\n \"\"\"\n Returns the quantity as a ``float`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [795, 799], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_float(self) -> float:\n \"\"\"\n Returns the quantity as a ``float`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 389, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "as_integer", "focal_method_txt": " @abstractmethod\n def as_integer(self) -> int:\n \"\"\"\n Returns the quantity as an ``int`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [802, 806], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def as_integer(self) -> int:\n \"\"\"\n Returns the quantity as an ``int`` if *defined*, raises class:`MonetaryOperationException` otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 390, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "abs", "focal_method_txt": " @abstractmethod\n def abs(self) -> \"Price\":\n \"\"\"\n Returns the absolute price if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [809, 813], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def abs(self) -> \"Price\":\n \"\"\"\n Returns the absolute price if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 391, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "negative", "focal_method_txt": " @abstractmethod\n def negative(self) -> \"Price\":\n \"\"\"\n Negates the quantity of the monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [816, 820], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def negative(self) -> \"Price\":\n \"\"\"\n Negates the quantity of the monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 392, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "positive", "focal_method_txt": " @abstractmethod\n def positive(self) -> \"Price\":\n \"\"\"\n Returns same monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [823, 827], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def positive(self) -> \"Price\":\n \"\"\"\n Returns same monetary value if *defined*, itself otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 393, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "round", "focal_method_txt": " @abstractmethod\n def round(self, ndigits: int = 0) -> \"Price\":\n \"\"\"\n Rounds the quantity of the monetary value to ``ndigits`` by using ``HALF_EVEN`` method if *defined*, itself\n otherwise.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [830, 835], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def round(self, ndigits: int = 0) -> \"Price\":\n \"\"\"\n Rounds the quantity of the monetary value to ``ndigits`` by using ``HALF_EVEN`` method if *defined*, itself\n otherwise.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 394, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "add", "focal_method_txt": " @abstractmethod\n def add(self, other: \"Price\") -> \"Price\":\n \"\"\"\n Performs monetary addition on the price object and the given ``other`` price object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined price objects.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [838, 848], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def add(self, other: \"Price\") -> \"Price\":\n \"\"\"\n Performs monetary addition on the price object and the given ``other`` price object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined price objects.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 395, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "scalar_add", "focal_method_txt": " @abstractmethod\n def scalar_add(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar addition on the quantity of the price.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [851, 857], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def scalar_add(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar addition on the quantity of the price.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 396, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "subtract", "focal_method_txt": " @abstractmethod\n def subtract(self, other: \"Price\") -> \"Price\":\n \"\"\"\n Performs monetary subtraction on the price object and the given ``other`` price object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined price objects.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [860, 870], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def subtract(self, other: \"Price\") -> \"Price\":\n \"\"\"\n Performs monetary subtraction on the price object and the given ``other`` price object.\n\n Note that::\n\n 1. Raises :class:`IncompatibleCurrencyError` if currencies do not match.\n 2. If any of the operands are undefined, returns the other one conveniently.\n 3. Dates are carried forward as a result of addition of two defined price objects.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 397, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "scalar_subtract", "focal_method_txt": " @abstractmethod\n def scalar_subtract(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar subtraction on the quantity of the price.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [873, 879], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def scalar_subtract(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar subtraction on the quantity of the price.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 398, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "multiply", "focal_method_txt": " @abstractmethod\n def multiply(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar multiplication.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [882, 888], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def multiply(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs scalar multiplication.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 399, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "times", "focal_method_txt": " @abstractmethod\n def times(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs monetary multiplication operation.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [891, 897], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def times(self, other: Numeric) -> \"Money\":\n \"\"\"\n Performs monetary multiplication operation.\n\n Note that undefined price object is returned as is.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 400, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "divide", "focal_method_txt": " @abstractmethod\n def divide(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs ordinary division on the price object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined price object.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [900, 906], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def divide(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs ordinary division on the price object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined price object.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 401, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "floor_divide", "focal_method_txt": " @abstractmethod\n def floor_divide(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs floor division on the price object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined price object.\n\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [909, 916], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def floor_divide(self, other: Numeric) -> \"Price\":\n \"\"\"\n Performs floor division on the price object if *defined*, itself otherwise.\n\n Note that division by zero yields an undefined price object.\n\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 402, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "lt", "focal_method_txt": " @abstractmethod\n def lt(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"less than\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are always less than ``other`` if ``other`` is not undefined, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [919, 929], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def lt(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"less than\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are always less than ``other`` if ``other`` is not undefined, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 403, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "lte", "focal_method_txt": " @abstractmethod\n def lte(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"less than or equal to\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are always less than or equal to ``other``, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [932, 942], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def lte(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"less than or equal to\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are always less than or equal to ``other``, and\n 2. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 404, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "gt", "focal_method_txt": " @abstractmethod\n def gt(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"greater than\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are never greater than ``other``,\n 2. Defined price objects are always greater than ``other`` if other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [945, 956], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def gt(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"greater than\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are never greater than ``other``,\n 2. Defined price objects are always greater than ``other`` if other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 405, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "gte", "focal_method_txt": " @abstractmethod\n def gte(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"greater than or equal to\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are never greater than or equal to ``other`` if ``other`` is defined,\n 2. Undefined price objects are greater than or equal to ``other`` if ``other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "focal_method_lines": [959, 970], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass IncompatibleCurrencyError(ValueError):\n\n def __init__(self, ccy1: Currency, ccy2: Currency, operation: str = \"\") -> None:\n \"\"\"\n Initializes an incompatible currency error message.\n \"\"\"\n ## Keep sloys:\n self.ccy1 = ccy1\n self.ccy2 = ccy2\n self.operation = operation\n\n ## Call super:\n super().__init__(f\"{ccy1.code} vs {ccy2.code} are incompatible for operation '{operation}'.\")\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def gte(self, other: \"Price\") -> bool:\n \"\"\"\n Applies \"greater than or equal to\" comparison against ``other`` price.\n\n Note that::\n\n 1. Undefined price objects are never greater than or equal to ``other`` if ``other`` is defined,\n 2. Undefined price objects are greater than or equal to ``other`` if ``other is undefined, and\n 3. :class:`IncompatibleCurrencyError` is raised when comparing two defined price objects with different\n currencies.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 406, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "with_ccy", "focal_method_txt": " @abstractmethod\n def with_ccy(self, ccy: Currency) -> \"Price\":\n \"\"\"\n Creates a new price object with the given currency if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [973, 977], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_ccy(self, ccy: Currency) -> \"Price\":\n \"\"\"\n Creates a new price object with the given currency if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 407, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "with_qty", "focal_method_txt": " @abstractmethod\n def with_qty(self, qty: Decimal) -> \"Price\":\n \"\"\"\n Creates a new price object with the given quantity if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [980, 984], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_qty(self, qty: Decimal) -> \"Price\":\n \"\"\"\n Creates a new price object with the given quantity if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 408, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "with_dov", "focal_method_txt": " @abstractmethod\n def with_dov(self, dov: Date) -> \"Price\":\n \"\"\"\n Creates a new price object with the given value date if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "focal_method_lines": [987, 991], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def with_dov(self, dov: Date) -> \"Price\":\n \"\"\"\n Creates a new price object with the given value date if price is *defined*, returns itself otherwise.\n \"\"\"\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 409, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "convert", "focal_method_txt": " @abstractmethod\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Price\":\n \"\"\"\n Converts the monetary value from one currency to another.\n\n Raises :class:`FXRateLookupError` if no foreign exchange rate can be found for conversion.\n\n Note that we will carry the date forward as per ``asof`` date.\n \"\"\"\n raise NotImplementedError", "focal_method_lines": [994, 1002], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Price\":\n \"\"\"\n Converts the monetary value from one currency to another.\n\n Raises :class:`FXRateLookupError` if no foreign exchange rate can be found for conversion.\n\n Note that we will carry the date forward as per ``asof`` date.\n \"\"\"\n raise NotImplementedError", "has_branch": false, "total_branches": 0} {"prompt_id": 410, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__bool__", "focal_method_txt": " @abstractmethod\n def __bool__(self) -> bool:\n pass", "focal_method_lines": [1022, 1023], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __bool__(self) -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 411, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__eq__", "focal_method_txt": " @abstractmethod\n def __eq__(self, other: Any) -> bool:\n pass", "focal_method_lines": [1026, 1027], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __eq__(self, other: Any) -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 412, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__abs__", "focal_method_txt": " @abstractmethod\n def __abs__(self) -> \"Price\":\n pass", "focal_method_lines": [1030, 1031], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __abs__(self) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 413, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__float__", "focal_method_txt": " @abstractmethod\n def __float__(self) -> float:\n pass", "focal_method_lines": [1034, 1035], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __float__(self) -> float:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 414, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__int__", "focal_method_txt": " @abstractmethod\n def __int__(self) -> int:\n pass", "focal_method_lines": [1038, 1039], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __int__(self) -> int:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 415, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__neg__", "focal_method_txt": " @abstractmethod\n def __neg__(self) -> \"Price\":\n pass", "focal_method_lines": [1057, 1058], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __neg__(self) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 416, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__pos__", "focal_method_txt": " @abstractmethod\n def __pos__(self) -> \"Price\":\n pass", "focal_method_lines": [1061, 1062], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __pos__(self) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 417, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__add__", "focal_method_txt": " @abstractmethod\n def __add__(self, other: \"Price\") -> \"Price\":\n pass", "focal_method_lines": [1065, 1066], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __add__(self, other: \"Price\") -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 418, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__sub__", "focal_method_txt": " @abstractmethod\n def __sub__(self, other: \"Price\") -> \"Price\":\n pass", "focal_method_lines": [1069, 1070], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __sub__(self, other: \"Price\") -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 419, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__mul__", "focal_method_txt": " @abstractmethod\n def __mul__(self, other: Numeric) -> \"Price\":\n pass", "focal_method_lines": [1073, 1074], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __mul__(self, other: Numeric) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 420, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__truediv__", "focal_method_txt": " @abstractmethod\n def __truediv__(self, other: Numeric) -> \"Price\":\n pass", "focal_method_lines": [1077, 1078], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __truediv__(self, other: Numeric) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 421, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__floordiv__", "focal_method_txt": " @abstractmethod\n def __floordiv__(self, other: Numeric) -> \"Price\":\n pass", "focal_method_lines": [1081, 1082], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __floordiv__(self, other: Numeric) -> \"Price\":\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 422, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__lt__", "focal_method_txt": " @abstractmethod\n def __lt__(self, other: \"Price\") -> bool:\n pass", "focal_method_lines": [1085, 1086], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __lt__(self, other: \"Price\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 423, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__le__", "focal_method_txt": " @abstractmethod\n def __le__(self, other: \"Price\") -> bool:\n pass", "focal_method_lines": [1089, 1090], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __le__(self, other: \"Price\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 424, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__gt__", "focal_method_txt": " @abstractmethod\n def __gt__(self, other: \"Price\") -> bool:\n pass", "focal_method_lines": [1093, 1094], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __gt__(self, other: \"Price\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 425, "project": "pypara", "module": "pypara.monetary", "class": "Price", "method": "__ge__", "focal_method_txt": " @abstractmethod\n def __ge__(self, other: \"Price\") -> bool:\n pass", "focal_method_lines": [1097, 1098], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass Price:\n\n __slots__ = ()\n\n NA: \"Price\"\n\n ccy: Currency\n\n qty: Decimal\n\n dov: Date\n\n defined: bool\n\n undefined: bool\n\n @abstractmethod\n def __ge__(self, other: \"Price\") -> bool:\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 426, "project": "pypara", "module": "pypara.monetary", "class": "SomePrice", "method": "with_dov", "focal_method_txt": " def with_dov(self, dov: Date) -> \"Price\":\n return SomePrice(self[0], self[1], dov)", "focal_method_lines": [1245, 1246], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass SomePrice(Price, NamedTuple(\"SomePrice\", [(\"ccy\", Currency), (\"qty\", Decimal), (\"dov\", Date)])):\n\n __slots__ = ()\n\n defined = True\n\n undefined = False\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def with_dov(self, dov: Date) -> \"Price\":\n return SomePrice(self[0], self[1], dov)", "has_branch": false, "total_branches": 0} {"prompt_id": 427, "project": "pypara", "module": "pypara.monetary", "class": "SomePrice", "method": "convert", "focal_method_txt": " def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Price\":\n ## Get slots:\n ccy, qty, dov = self\n\n ## Get date of conversion:\n asof = asof or dov\n\n ## Attempt to get the FX rate:\n try:\n rate = FXRateService.default.query(ccy, to, asof, strict) # type: ignore\n except AttributeError as exc:\n if FXRateService.default is None:\n raise ProgrammingError(\"Did you implement and set the default FX rate service?\")\n else:\n raise exc\n\n ## Do we have a rate?\n if rate is None:\n ## Nope, shall we raise exception?\n if strict:\n ## Yep:\n raise FXRateLookupError(ccy, to, asof)\n else:\n ## Just return NA:\n return NoPrice\n\n ## Compute and return:\n return SomePrice(to, qty * rate.value, asof)", "focal_method_lines": [1248, 1275], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass SomePrice(Price, NamedTuple(\"SomePrice\", [(\"ccy\", Currency), (\"qty\", Decimal), (\"dov\", Date)])):\n\n __slots__ = ()\n\n defined = True\n\n undefined = False\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def convert(self, to: Currency, asof: Optional[Date] = None, strict: bool = False) -> \"Price\":\n ## Get slots:\n ccy, qty, dov = self\n\n ## Get date of conversion:\n asof = asof or dov\n\n ## Attempt to get the FX rate:\n try:\n rate = FXRateService.default.query(ccy, to, asof, strict) # type: ignore\n except AttributeError as exc:\n if FXRateService.default is None:\n raise ProgrammingError(\"Did you implement and set the default FX rate service?\")\n else:\n raise exc\n\n ## Do we have a rate?\n if rate is None:\n ## Nope, shall we raise exception?\n if strict:\n ## Yep:\n raise FXRateLookupError(ccy, to, asof)\n else:\n ## Just return NA:\n return NoPrice\n\n ## Compute and return:\n return SomePrice(to, qty * rate.value, asof)", "has_branch": true, "total_branches": 2} {"prompt_id": 428, "project": "pypara", "module": "pypara.monetary", "class": "NonePrice", "method": "with_dov", "focal_method_txt": " def with_dov(self, dov: Date) -> \"Price\":\n return self", "focal_method_lines": [1389, 1390], "in_stack": false, "globals": ["__all__", "Money", "NA", "Price"], "type_context": "from abc import abstractmethod\nfrom decimal import Decimal, DivisionByZero, InvalidOperation\nfrom typing import Any, NamedTuple, Optional, Union, overload\nfrom .commons.errors import ProgrammingError\nfrom .commons.numbers import Numeric\nfrom .commons.zeitgeist import Date\nfrom .currencies import Currency\nfrom .exchange import FXRateLookupError, FXRateService\n\n__all__ = [\n \"IncompatibleCurrencyError\",\n \"MonetaryOperationException\",\n \"Money\",\n \"NoMoney\",\n \"NoPrice\",\n \"NoneMoney\",\n \"NonePrice\",\n \"Price\",\n \"SomeMoney\",\n \"SomePrice\",\n]\nMoney.NA = NoMoney = NoneMoney()\nPrice.NA = NoPrice = NonePrice()\nPrice.NA = NoPrice = NonePrice()\n\nclass NonePrice(Price):\n\n __slots__ = ()\n\n defined = False\n\n undefined = True\n\n money = NoMoney\n\n __bool__ = as_boolean\n\n __eq__ = is_equal\n\n __abs__ = abs\n\n __float__ = as_float\n\n __int__ = as_integer\n\n __neg__ = negative\n\n __pos__ = positive\n\n __add__ = add\n\n __sub__ = subtract\n\n __mul__ = multiply\n\n __truediv__ = divide\n\n __floordiv__ = floor_divide\n\n __lt__ = lt\n\n __le__ = lte\n\n __gt__ = gt\n\n __ge__ = gte\n\n def with_dov(self, dov: Date) -> \"Price\":\n return self", "has_branch": false, "total_branches": 0} {"prompt_id": 429, "project": "pysnooper", "module": "pysnooper.pycompat", "class": "", "method": "timedelta_format", "focal_method_txt": "def timedelta_format(timedelta):\n time = (datetime_module.datetime.min + timedelta).time()\n return time_isoformat(time, timespec='microseconds')", "focal_method_lines": [85, 87], "in_stack": false, "globals": ["PY3", "PY2"], "type_context": "import abc\nimport os\nimport inspect\nimport sys\nimport datetime as datetime_module\n\nPY3 = (sys.version_info[0] == 3)\nPY2 = not PY3\n\ndef timedelta_format(timedelta):\n time = (datetime_module.datetime.min + timedelta).time()\n return time_isoformat(time, timespec='microseconds')", "has_branch": false, "total_branches": 0} {"prompt_id": 430, "project": "pysnooper", "module": "pysnooper.pycompat", "class": "", "method": "timedelta_parse", "focal_method_txt": "def timedelta_parse(s):\n hours, minutes, seconds, microseconds = map(\n int,\n s.replace('.', ':').split(':')\n )\n return datetime_module.timedelta(hours=hours, minutes=minutes,\n seconds=seconds,\n microseconds=microseconds)", "focal_method_lines": [89, 94], "in_stack": false, "globals": ["PY3", "PY2"], "type_context": "import abc\nimport os\nimport inspect\nimport sys\nimport datetime as datetime_module\n\nPY3 = (sys.version_info[0] == 3)\nPY2 = not PY3\n\ndef timedelta_parse(s):\n hours, minutes, seconds, microseconds = map(\n int,\n s.replace('.', ':').split(':')\n )\n return datetime_module.timedelta(hours=hours, minutes=minutes,\n seconds=seconds,\n microseconds=microseconds)", "has_branch": false, "total_branches": 0} {"prompt_id": 431, "project": "pysnooper", "module": "pysnooper.tracer", "class": "", "method": "get_local_reprs", "focal_method_txt": "def get_local_reprs(frame, watch=(), custom_repr=(), max_length=None, normalize=False):\n code = frame.f_code\n vars_order = (code.co_varnames + code.co_cellvars + code.co_freevars +\n tuple(frame.f_locals.keys()))\n\n result_items = [(key, utils.get_shortish_repr(value, custom_repr,\n max_length, normalize))\n for key, value in frame.f_locals.items()]\n result_items.sort(key=lambda key_value: vars_order.index(key_value[0]))\n result = collections.OrderedDict(result_items)\n\n for variable in watch:\n result.update(sorted(variable.items(frame, normalize)))\n return result", "focal_method_lines": [24, 37], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\ndef get_local_reprs(frame, watch=(), custom_repr=(), max_length=None, normalize=False):\n code = frame.f_code\n vars_order = (code.co_varnames + code.co_cellvars + code.co_freevars +\n tuple(frame.f_locals.keys()))\n\n result_items = [(key, utils.get_shortish_repr(value, custom_repr,\n max_length, normalize))\n for key, value in frame.f_locals.items()]\n result_items.sort(key=lambda key_value: vars_order.index(key_value[0]))\n result = collections.OrderedDict(result_items)\n\n for variable in watch:\n result.update(sorted(variable.items(frame, normalize)))\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 432, "project": "pysnooper", "module": "pysnooper.tracer", "class": "", "method": "get_path_and_source_from_frame", "focal_method_txt": "def get_path_and_source_from_frame(frame):\n globs = frame.f_globals or {}\n module_name = globs.get('__name__')\n file_name = frame.f_code.co_filename\n cache_key = (module_name, file_name)\n try:\n return source_and_path_cache[cache_key]\n except KeyError:\n pass\n loader = globs.get('__loader__')\n\n source = None\n if hasattr(loader, 'get_source'):\n try:\n source = loader.get_source(module_name)\n except ImportError:\n pass\n if source is not None:\n source = source.splitlines()\n if source is None:\n ipython_filename_match = ipython_filename_pattern.match(file_name)\n if ipython_filename_match:\n entry_number = int(ipython_filename_match.group(1))\n try:\n import IPython\n ipython_shell = IPython.get_ipython()\n ((_, _, source_chunk),) = ipython_shell.history_manager. \\\n get_range(0, entry_number, entry_number + 1)\n source = source_chunk.splitlines()\n except Exception:\n pass\n else:\n try:\n with open(file_name, 'rb') as fp:\n source = fp.read().splitlines()\n except utils.file_reading_errors:\n pass\n if not source:\n # We used to check `if source is None` but I found a rare bug where it\n # was empty, but not `None`, so now we check `if not source`.\n source = UnavailableSource()\n\n # If we just read the source from a file, or if the loader did not\n # apply tokenize.detect_encoding to decode the source into a\n # string, then we should do that ourselves.\n if isinstance(source[0], bytes):\n encoding = 'utf-8'\n for line in source[:2]:\n # File coding may be specified. Match pattern from PEP-263\n # (https://www.python.org/dev/peps/pep-0263/)\n match = re.search(br'coding[:=]\\s*([-\\w.]+)', line)\n if match:\n encoding = match.group(1).decode('ascii')\n break\n source = [pycompat.text_type(sline, encoding, 'replace') for sline in\n source]\n\n result = (file_name, source)\n source_and_path_cache[cache_key] = result\n return result", "focal_method_lines": [48, 107], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\ndef get_path_and_source_from_frame(frame):\n globs = frame.f_globals or {}\n module_name = globs.get('__name__')\n file_name = frame.f_code.co_filename\n cache_key = (module_name, file_name)\n try:\n return source_and_path_cache[cache_key]\n except KeyError:\n pass\n loader = globs.get('__loader__')\n\n source = None\n if hasattr(loader, 'get_source'):\n try:\n source = loader.get_source(module_name)\n except ImportError:\n pass\n if source is not None:\n source = source.splitlines()\n if source is None:\n ipython_filename_match = ipython_filename_pattern.match(file_name)\n if ipython_filename_match:\n entry_number = int(ipython_filename_match.group(1))\n try:\n import IPython\n ipython_shell = IPython.get_ipython()\n ((_, _, source_chunk),) = ipython_shell.history_manager. \\\n get_range(0, entry_number, entry_number + 1)\n source = source_chunk.splitlines()\n except Exception:\n pass\n else:\n try:\n with open(file_name, 'rb') as fp:\n source = fp.read().splitlines()\n except utils.file_reading_errors:\n pass\n if not source:\n # We used to check `if source is None` but I found a rare bug where it\n # was empty, but not `None`, so now we check `if not source`.\n source = UnavailableSource()\n\n # If we just read the source from a file, or if the loader did not\n # apply tokenize.detect_encoding to decode the source into a\n # string, then we should do that ourselves.\n if isinstance(source[0], bytes):\n encoding = 'utf-8'\n for line in source[:2]:\n # File coding may be specified. Match pattern from PEP-263\n # (https://www.python.org/dev/peps/pep-0263/)\n match = re.search(br'coding[:=]\\s*([-\\w.]+)', line)\n if match:\n encoding = match.group(1).decode('ascii')\n break\n source = [pycompat.text_type(sline, encoding, 'replace') for sline in\n source]\n\n result = (file_name, source)\n source_and_path_cache[cache_key] = result\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 433, "project": "pysnooper", "module": "pysnooper.tracer", "class": "", "method": "get_write_function", "focal_method_txt": "def get_write_function(output, overwrite):\n is_path = isinstance(output, (pycompat.PathLike, str))\n if overwrite and not is_path:\n raise Exception('`overwrite=True` can only be used when writing '\n 'content to file.')\n if output is None:\n def write(s):\n stderr = sys.stderr\n try:\n stderr.write(s)\n except UnicodeEncodeError:\n # God damn Python 2\n stderr.write(utils.shitcode(s))\n elif is_path:\n return FileWriter(output, overwrite).write\n elif callable(output):\n write = output\n else:\n assert isinstance(output, utils.WritableStream)\n\n def write(s):\n output.write(s)\n return write", "focal_method_lines": [110, 132], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass FileWriter(object):\n\n def __init__(self, path, overwrite):\n self.path = pycompat.text_type(path)\n self.overwrite = overwrite\n\ndef get_write_function(output, overwrite):\n is_path = isinstance(output, (pycompat.PathLike, str))\n if overwrite and not is_path:\n raise Exception('`overwrite=True` can only be used when writing '\n 'content to file.')\n if output is None:\n def write(s):\n stderr = sys.stderr\n try:\n stderr.write(s)\n except UnicodeEncodeError:\n # God damn Python 2\n stderr.write(utils.shitcode(s))\n elif is_path:\n return FileWriter(output, overwrite).write\n elif callable(output):\n write = output\n else:\n assert isinstance(output, utils.WritableStream)\n\n def write(s):\n output.write(s)\n return write", "has_branch": true, "total_branches": 2} {"prompt_id": 434, "project": "pysnooper", "module": "pysnooper.tracer", "class": "FileWriter", "method": "write", "focal_method_txt": " def write(self, s):\n with open(self.path, 'w' if self.overwrite else 'a',\n encoding='utf-8') as output_file:\n output_file.write(s)\n self.overwrite = False", "focal_method_lines": [140, 144], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass FileWriter(object):\n\n def __init__(self, path, overwrite):\n self.path = pycompat.text_type(path)\n self.overwrite = overwrite\n\n def write(self, s):\n with open(self.path, 'w' if self.overwrite else 'a',\n encoding='utf-8') as output_file:\n output_file.write(s)\n self.overwrite = False", "has_branch": false, "total_branches": 0} {"prompt_id": 435, "project": "pysnooper", "module": "pysnooper.tracer", "class": "Tracer", "method": "__init__", "focal_method_txt": " def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time", "focal_method_lines": [205, 234], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass Tracer:\n\n def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time", "has_branch": true, "total_branches": 2} {"prompt_id": 436, "project": "pysnooper", "module": "pysnooper.tracer", "class": "Tracer", "method": "__call__", "focal_method_txt": " def __call__(self, function_or_class):\n if DISABLED:\n return function_or_class\n\n if inspect.isclass(function_or_class):\n return self._wrap_class(function_or_class)\n else:\n return self._wrap_function(function_or_class)", "focal_method_lines": [236, 243], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass Tracer:\n\n def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time\n\n def __call__(self, function_or_class):\n if DISABLED:\n return function_or_class\n\n if inspect.isclass(function_or_class):\n return self._wrap_class(function_or_class)\n else:\n return self._wrap_function(function_or_class)", "has_branch": true, "total_branches": 2} {"prompt_id": 437, "project": "pysnooper", "module": "pysnooper.tracer", "class": "Tracer", "method": "__enter__", "focal_method_txt": " def __enter__(self):\n if DISABLED:\n return\n thread_global.__dict__.setdefault('depth', -1)\n calling_frame = inspect.currentframe().f_back\n if not self._is_internal_frame(calling_frame):\n calling_frame.f_trace = self.trace\n self.target_frames.add(calling_frame)\n\n stack = self.thread_local.__dict__.setdefault(\n 'original_trace_functions', []\n )\n stack.append(sys.gettrace())\n self.start_times[calling_frame] = datetime_module.datetime.now()\n sys.settrace(self.trace)", "focal_method_lines": [292, 306], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass Tracer:\n\n def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time\n\n def __enter__(self):\n if DISABLED:\n return\n thread_global.__dict__.setdefault('depth', -1)\n calling_frame = inspect.currentframe().f_back\n if not self._is_internal_frame(calling_frame):\n calling_frame.f_trace = self.trace\n self.target_frames.add(calling_frame)\n\n stack = self.thread_local.__dict__.setdefault(\n 'original_trace_functions', []\n )\n stack.append(sys.gettrace())\n self.start_times[calling_frame] = datetime_module.datetime.now()\n sys.settrace(self.trace)", "has_branch": true, "total_branches": 2} {"prompt_id": 438, "project": "pysnooper", "module": "pysnooper.tracer", "class": "Tracer", "method": "__exit__", "focal_method_txt": " def __exit__(self, exc_type, exc_value, exc_traceback):\n if DISABLED:\n return\n stack = self.thread_local.original_trace_functions\n sys.settrace(stack.pop())\n calling_frame = inspect.currentframe().f_back\n self.target_frames.discard(calling_frame)\n self.frame_to_local_reprs.pop(calling_frame, None)\n\n ### Writing elapsed time: #############################################\n # #\n start_time = self.start_times.pop(calling_frame)\n duration = datetime_module.datetime.now() - start_time\n elapsed_time_string = pycompat.timedelta_format(duration)\n indent = ' ' * 4 * (thread_global.depth + 1)\n self.write(\n '{indent}Elapsed time: {elapsed_time_string}'.format(**locals())\n )\n # #\n ### Finished writing elapsed time. ####################################", "focal_method_lines": [308, 323], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass Tracer:\n\n def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n if DISABLED:\n return\n stack = self.thread_local.original_trace_functions\n sys.settrace(stack.pop())\n calling_frame = inspect.currentframe().f_back\n self.target_frames.discard(calling_frame)\n self.frame_to_local_reprs.pop(calling_frame, None)\n\n ### Writing elapsed time: #############################################\n # #\n start_time = self.start_times.pop(calling_frame)\n duration = datetime_module.datetime.now() - start_time\n elapsed_time_string = pycompat.timedelta_format(duration)\n indent = ' ' * 4 * (thread_global.depth + 1)\n self.write(\n '{indent}Elapsed time: {elapsed_time_string}'.format(**locals())\n )\n # #\n ### Finished writing elapsed time. ####################################", "has_branch": true, "total_branches": 2} {"prompt_id": 439, "project": "pysnooper", "module": "pysnooper.tracer", "class": "Tracer", "method": "trace", "focal_method_txt": " def trace(self, frame, event, arg):\n\n ### Checking whether we should trace this line: #######################\n # #\n # We should trace this line either if it's in the decorated function,\n # or the user asked to go a few levels deeper and we're within that\n # number of levels deeper.\n\n if not (frame.f_code in self.target_codes or frame in self.target_frames):\n if self.depth == 1:\n # We did the most common and quickest check above, because the\n # trace function runs so incredibly often, therefore it's\n # crucial to hyper-optimize it for the common case.\n return None\n elif self._is_internal_frame(frame):\n return None\n else:\n _frame_candidate = frame\n for i in range(1, self.depth):\n _frame_candidate = _frame_candidate.f_back\n if _frame_candidate is None:\n return None\n elif _frame_candidate.f_code in self.target_codes or _frame_candidate in self.target_frames:\n break\n else:\n return None\n\n if event == 'call':\n thread_global.depth += 1\n indent = ' ' * 4 * thread_global.depth\n\n # #\n ### Finished checking whether we should trace this line. ##############\n\n ### Making timestamp: #################################################\n # #\n if self.normalize:\n timestamp = ' ' * 15\n elif self.relative_time:\n try:\n start_time = self.start_times[frame]\n except KeyError:\n start_time = self.start_times[frame] = \\\n datetime_module.datetime.now()\n duration = datetime_module.datetime.now() - start_time\n timestamp = pycompat.timedelta_format(duration)\n else:\n timestamp = pycompat.time_isoformat(\n datetime_module.datetime.now().time(),\n timespec='microseconds'\n )\n # #\n ### Finished making timestamp. ########################################\n\n line_no = frame.f_lineno\n source_path, source = get_path_and_source_from_frame(frame)\n source_path = source_path if not self.normalize else os.path.basename(source_path)\n if self.last_source_path != source_path:\n self.write(u'{indent}Source path:... {source_path}'.\n format(**locals()))\n self.last_source_path = source_path\n source_line = source[line_no - 1]\n thread_info = \"\"\n if self.thread_info:\n if self.normalize:\n raise NotImplementedError(\"normalize is not supported with \"\n \"thread_info\")\n current_thread = threading.current_thread()\n thread_info = \"{ident}-{name} \".format(\n ident=current_thread.ident, name=current_thread.getName())\n thread_info = self.set_thread_info_padding(thread_info)\n\n ### Reporting newish and modified variables: ##########################\n # #\n old_local_reprs = self.frame_to_local_reprs.get(frame, {})\n self.frame_to_local_reprs[frame] = local_reprs = \\\n get_local_reprs(frame,\n watch=self.watch, custom_repr=self.custom_repr,\n max_length=self.max_variable_length,\n normalize=self.normalize,\n )\n\n newish_string = ('Starting var:.. ' if event == 'call' else\n 'New var:....... ')\n\n for name, value_repr in local_reprs.items():\n if name not in old_local_reprs:\n self.write('{indent}{newish_string}{name} = {value_repr}'.format(\n **locals()))\n elif old_local_reprs[name] != value_repr:\n self.write('{indent}Modified var:.. {name} = {value_repr}'.format(\n **locals()))\n\n # #\n ### Finished newish and modified variables. ###########################\n\n\n ### Dealing with misplaced function definition: #######################\n # #\n if event == 'call' and source_line.lstrip().startswith('@'):\n # If a function decorator is found, skip lines until an actual\n # function definition is found.\n for candidate_line_no in itertools.count(line_no):\n try:\n candidate_source_line = source[candidate_line_no - 1]\n except IndexError:\n # End of source file reached without finding a function\n # definition. Fall back to original source line.\n break\n\n if candidate_source_line.lstrip().startswith('def'):\n # Found the def line!\n line_no = candidate_line_no\n source_line = candidate_source_line\n break\n # #\n ### Finished dealing with misplaced function definition. ##############\n\n # If a call ends due to an exception, we still get a 'return' event\n # with arg = None. This seems to be the only way to tell the difference\n # https://stackoverflow.com/a/12800909/2482744\n code_byte = frame.f_code.co_code[frame.f_lasti]\n if not isinstance(code_byte, int):\n code_byte = ord(code_byte)\n ended_by_exception = (\n event == 'return'\n and arg is None\n and (opcode.opname[code_byte]\n not in ('RETURN_VALUE', 'YIELD_VALUE'))\n )\n\n if ended_by_exception:\n self.write('{indent}Call ended by exception'.\n format(**locals()))\n else:\n self.write(u'{indent}{timestamp} {thread_info}{event:9} '\n u'{line_no:4} {source_line}'.format(**locals()))\n\n if event == 'return':\n self.frame_to_local_reprs.pop(frame, None)\n self.start_times.pop(frame, None)\n thread_global.depth -= 1\n\n if not ended_by_exception:\n return_value_repr = utils.get_shortish_repr(arg,\n custom_repr=self.custom_repr,\n max_length=self.max_variable_length,\n normalize=self.normalize,\n )\n self.write('{indent}Return value:.. {return_value_repr}'.\n format(**locals()))\n\n if event == 'exception':\n exception = '\\n'.join(traceback.format_exception_only(*arg[:2])).strip()\n if self.max_variable_length:\n exception = utils.truncate(exception, self.max_variable_length)\n self.write('{indent}Exception:..... {exception}'.\n format(**locals()))\n\n return self.trace", "focal_method_lines": [338, 497], "in_stack": false, "globals": ["ipython_filename_pattern", "source_and_path_cache", "thread_global", "DISABLED"], "type_context": "import functools\nimport inspect\nimport opcode\nimport os\nimport sys\nimport re\nimport collections\nimport datetime as datetime_module\nimport itertools\nimport threading\nimport traceback\nfrom .variables import CommonVariable, Exploding, BaseVariable\nfrom . import utils, pycompat\n\nipython_filename_pattern = re.compile('^$')\nsource_and_path_cache = {}\nthread_global = threading.local()\nDISABLED = bool(os.getenv('PYSNOOPER_DISABLED', ''))\n\nclass Tracer:\n\n def __init__(self, output=None, watch=(), watch_explode=(), depth=1,\n prefix='', overwrite=False, thread_info=False, custom_repr=(),\n max_variable_length=100, normalize=False, relative_time=False):\n self._write = get_write_function(output, overwrite)\n\n self.watch = [\n v if isinstance(v, BaseVariable) else CommonVariable(v)\n for v in utils.ensure_tuple(watch)\n ] + [\n v if isinstance(v, BaseVariable) else Exploding(v)\n for v in utils.ensure_tuple(watch_explode)\n ]\n self.frame_to_local_reprs = {}\n self.start_times = {}\n self.depth = depth\n self.prefix = prefix\n self.thread_info = thread_info\n self.thread_info_padding = 0\n assert self.depth >= 1\n self.target_codes = set()\n self.target_frames = set()\n self.thread_local = threading.local()\n if len(custom_repr) == 2 and not all(isinstance(x,\n pycompat.collections_abc.Iterable) for x in custom_repr):\n custom_repr = (custom_repr,)\n self.custom_repr = custom_repr\n self.last_source_path = None\n self.max_variable_length = max_variable_length\n self.normalize = normalize\n self.relative_time = relative_time\n\n def trace(self, frame, event, arg):\n\n ### Checking whether we should trace this line: #######################\n # #\n # We should trace this line either if it's in the decorated function,\n # or the user asked to go a few levels deeper and we're within that\n # number of levels deeper.\n\n if not (frame.f_code in self.target_codes or frame in self.target_frames):\n if self.depth == 1:\n # We did the most common and quickest check above, because the\n # trace function runs so incredibly often, therefore it's\n # crucial to hyper-optimize it for the common case.\n return None\n elif self._is_internal_frame(frame):\n return None\n else:\n _frame_candidate = frame\n for i in range(1, self.depth):\n _frame_candidate = _frame_candidate.f_back\n if _frame_candidate is None:\n return None\n elif _frame_candidate.f_code in self.target_codes or _frame_candidate in self.target_frames:\n break\n else:\n return None\n\n if event == 'call':\n thread_global.depth += 1\n indent = ' ' * 4 * thread_global.depth\n\n # #\n ### Finished checking whether we should trace this line. ##############\n\n ### Making timestamp: #################################################\n # #\n if self.normalize:\n timestamp = ' ' * 15\n elif self.relative_time:\n try:\n start_time = self.start_times[frame]\n except KeyError:\n start_time = self.start_times[frame] = \\\n datetime_module.datetime.now()\n duration = datetime_module.datetime.now() - start_time\n timestamp = pycompat.timedelta_format(duration)\n else:\n timestamp = pycompat.time_isoformat(\n datetime_module.datetime.now().time(),\n timespec='microseconds'\n )\n # #\n ### Finished making timestamp. ########################################\n\n line_no = frame.f_lineno\n source_path, source = get_path_and_source_from_frame(frame)\n source_path = source_path if not self.normalize else os.path.basename(source_path)\n if self.last_source_path != source_path:\n self.write(u'{indent}Source path:... {source_path}'.\n format(**locals()))\n self.last_source_path = source_path\n source_line = source[line_no - 1]\n thread_info = \"\"\n if self.thread_info:\n if self.normalize:\n raise NotImplementedError(\"normalize is not supported with \"\n \"thread_info\")\n current_thread = threading.current_thread()\n thread_info = \"{ident}-{name} \".format(\n ident=current_thread.ident, name=current_thread.getName())\n thread_info = self.set_thread_info_padding(thread_info)\n\n ### Reporting newish and modified variables: ##########################\n # #\n old_local_reprs = self.frame_to_local_reprs.get(frame, {})\n self.frame_to_local_reprs[frame] = local_reprs = \\\n get_local_reprs(frame,\n watch=self.watch, custom_repr=self.custom_repr,\n max_length=self.max_variable_length,\n normalize=self.normalize,\n )\n\n newish_string = ('Starting var:.. ' if event == 'call' else\n 'New var:....... ')\n\n for name, value_repr in local_reprs.items():\n if name not in old_local_reprs:\n self.write('{indent}{newish_string}{name} = {value_repr}'.format(\n **locals()))\n elif old_local_reprs[name] != value_repr:\n self.write('{indent}Modified var:.. {name} = {value_repr}'.format(\n **locals()))\n\n # #\n ### Finished newish and modified variables. ###########################\n\n\n ### Dealing with misplaced function definition: #######################\n # #\n if event == 'call' and source_line.lstrip().startswith('@'):\n # If a function decorator is found, skip lines until an actual\n # function definition is found.\n for candidate_line_no in itertools.count(line_no):\n try:\n candidate_source_line = source[candidate_line_no - 1]\n except IndexError:\n # End of source file reached without finding a function\n # definition. Fall back to original source line.\n break\n\n if candidate_source_line.lstrip().startswith('def'):\n # Found the def line!\n line_no = candidate_line_no\n source_line = candidate_source_line\n break\n # #\n ### Finished dealing with misplaced function definition. ##############\n\n # If a call ends due to an exception, we still get a 'return' event\n # with arg = None. This seems to be the only way to tell the difference\n # https://stackoverflow.com/a/12800909/2482744\n code_byte = frame.f_code.co_code[frame.f_lasti]\n if not isinstance(code_byte, int):\n code_byte = ord(code_byte)\n ended_by_exception = (\n event == 'return'\n and arg is None\n and (opcode.opname[code_byte]\n not in ('RETURN_VALUE', 'YIELD_VALUE'))\n )\n\n if ended_by_exception:\n self.write('{indent}Call ended by exception'.\n format(**locals()))\n else:\n self.write(u'{indent}{timestamp} {thread_info}{event:9} '\n u'{line_no:4} {source_line}'.format(**locals()))\n\n if event == 'return':\n self.frame_to_local_reprs.pop(frame, None)\n self.start_times.pop(frame, None)\n thread_global.depth -= 1\n\n if not ended_by_exception:\n return_value_repr = utils.get_shortish_repr(arg,\n custom_repr=self.custom_repr,\n max_length=self.max_variable_length,\n normalize=self.normalize,\n )\n self.write('{indent}Return value:.. {return_value_repr}'.\n format(**locals()))\n\n if event == 'exception':\n exception = '\\n'.join(traceback.format_exception_only(*arg[:2])).strip()\n if self.max_variable_length:\n exception = utils.truncate(exception, self.max_variable_length)\n self.write('{indent}Exception:..... {exception}'.\n format(**locals()))\n\n return self.trace", "has_branch": true, "total_branches": 2} {"prompt_id": 440, "project": "pysnooper", "module": "pysnooper.utils", "class": "", "method": "shitcode", "focal_method_txt": "def shitcode(s):\n return ''.join(\n (c if (0 < ord(c) < 256) else '?') for c in s\n )", "focal_method_lines": [43, 44], "in_stack": false, "globals": ["file_reading_errors", "DEFAULT_REPR_RE"], "type_context": "import abc\nimport re\nimport sys\nfrom .pycompat import ABC, string_types, collections_abc\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\nDEFAULT_REPR_RE = re.compile(r' at 0x[a-f0-9A-F]{4,}')\n\ndef shitcode(s):\n return ''.join(\n (c if (0 < ord(c) < 256) else '?') for c in s\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 441, "project": "pysnooper", "module": "pysnooper.utils", "class": "", "method": "get_repr_function", "focal_method_txt": "def get_repr_function(item, custom_repr):\n for condition, action in custom_repr:\n if isinstance(condition, type):\n condition = lambda x, y=condition: isinstance(x, y)\n if condition(item):\n return action\n return repr", "focal_method_lines": [49, 55], "in_stack": false, "globals": ["file_reading_errors", "DEFAULT_REPR_RE"], "type_context": "import abc\nimport re\nimport sys\nfrom .pycompat import ABC, string_types, collections_abc\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\nDEFAULT_REPR_RE = re.compile(r' at 0x[a-f0-9A-F]{4,}')\n\ndef get_repr_function(item, custom_repr):\n for condition, action in custom_repr:\n if isinstance(condition, type):\n condition = lambda x, y=condition: isinstance(x, y)\n if condition(item):\n return action\n return repr", "has_branch": true, "total_branches": 2} {"prompt_id": 442, "project": "pysnooper", "module": "pysnooper.utils", "class": "", "method": "get_shortish_repr", "focal_method_txt": "def get_shortish_repr(item, custom_repr=(), max_length=None, normalize=False):\n repr_function = get_repr_function(item, custom_repr)\n try:\n r = repr_function(item)\n except Exception:\n r = 'REPR FAILED'\n r = r.replace('\\r', '').replace('\\n', '')\n if normalize:\n r = normalize_repr(r)\n if max_length:\n r = truncate(r, max_length)\n return r", "focal_method_lines": [66, 77], "in_stack": false, "globals": ["file_reading_errors", "DEFAULT_REPR_RE"], "type_context": "import abc\nimport re\nimport sys\nfrom .pycompat import ABC, string_types, collections_abc\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\nDEFAULT_REPR_RE = re.compile(r' at 0x[a-f0-9A-F]{4,}')\n\ndef get_shortish_repr(item, custom_repr=(), max_length=None, normalize=False):\n repr_function = get_repr_function(item, custom_repr)\n try:\n r = repr_function(item)\n except Exception:\n r = 'REPR FAILED'\n r = r.replace('\\r', '').replace('\\n', '')\n if normalize:\n r = normalize_repr(r)\n if max_length:\n r = truncate(r, max_length)\n return r", "has_branch": true, "total_branches": 2} {"prompt_id": 443, "project": "pysnooper", "module": "pysnooper.utils", "class": "", "method": "truncate", "focal_method_txt": "def truncate(string, max_length):\n if (max_length is None) or (len(string) <= max_length):\n return string\n else:\n left = (max_length - 3) // 2\n right = max_length - 3 - left\n return u'{}...{}'.format(string[:left], string[-right:])", "focal_method_lines": [80, 86], "in_stack": false, "globals": ["file_reading_errors", "DEFAULT_REPR_RE"], "type_context": "import abc\nimport re\nimport sys\nfrom .pycompat import ABC, string_types, collections_abc\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\nDEFAULT_REPR_RE = re.compile(r' at 0x[a-f0-9A-F]{4,}')\n\ndef truncate(string, max_length):\n if (max_length is None) or (len(string) <= max_length):\n return string\n else:\n left = (max_length - 3) // 2\n right = max_length - 3 - left\n return u'{}...{}'.format(string[:left], string[-right:])", "has_branch": true, "total_branches": 2} {"prompt_id": 444, "project": "pysnooper", "module": "pysnooper.utils", "class": "WritableStream", "method": "write", "focal_method_txt": " @abc.abstractmethod\n def write(self, s):\n pass", "focal_method_lines": [24, 25], "in_stack": false, "globals": ["file_reading_errors", "DEFAULT_REPR_RE"], "type_context": "import abc\nimport re\nimport sys\nfrom .pycompat import ABC, string_types, collections_abc\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\nDEFAULT_REPR_RE = re.compile(r' at 0x[a-f0-9A-F]{4,}')\n\nclass WritableStream(ABC):\n\n @abc.abstractmethod\n def write(self, s):\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 445, "project": "pysnooper", "module": "pysnooper.variables", "class": "BaseVariable", "method": "__init__", "focal_method_txt": " def __init__(self, source, exclude=()):\n self.source = source\n self.exclude = utils.ensure_tuple(exclude)\n self.code = compile(source, '', 'eval')\n if needs_parentheses(source):\n self.unambiguous_source = '({})'.format(source)\n else:\n self.unambiguous_source = source", "focal_method_lines": [20, 27], "in_stack": false, "globals": [], "type_context": "import itertools\nimport abc\nfrom copy import deepcopy\nfrom . import utils\nfrom . import pycompat\n\n\n\nclass BaseVariable(pycompat.ABC):\n\n def __init__(self, source, exclude=()):\n self.source = source\n self.exclude = utils.ensure_tuple(exclude)\n self.code = compile(source, '', 'eval')\n if needs_parentheses(source):\n self.unambiguous_source = '({})'.format(source)\n else:\n self.unambiguous_source = source", "has_branch": true, "total_branches": 2} {"prompt_id": 446, "project": "pysnooper", "module": "pysnooper.variables", "class": "BaseVariable", "method": "items", "focal_method_txt": " def items(self, frame, normalize=False):\n try:\n main_value = eval(self.code, frame.f_globals or {}, frame.f_locals)\n except Exception:\n return ()\n return self._items(main_value, normalize)", "focal_method_lines": [29, 34], "in_stack": false, "globals": [], "type_context": "import itertools\nimport abc\nfrom copy import deepcopy\nfrom . import utils\nfrom . import pycompat\n\n\n\nclass BaseVariable(pycompat.ABC):\n\n def __init__(self, source, exclude=()):\n self.source = source\n self.exclude = utils.ensure_tuple(exclude)\n self.code = compile(source, '', 'eval')\n if needs_parentheses(source):\n self.unambiguous_source = '({})'.format(source)\n else:\n self.unambiguous_source = source\n\n def items(self, frame, normalize=False):\n try:\n main_value = eval(self.code, frame.f_globals or {}, frame.f_locals)\n except Exception:\n return ()\n return self._items(main_value, normalize)", "has_branch": false, "total_branches": 0} {"prompt_id": 447, "project": "pysnooper", "module": "pysnooper.variables", "class": "BaseVariable", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n return (isinstance(other, BaseVariable) and\n self._fingerprint == other._fingerprint)", "focal_method_lines": [47, 48], "in_stack": false, "globals": [], "type_context": "import itertools\nimport abc\nfrom copy import deepcopy\nfrom . import utils\nfrom . import pycompat\n\n\n\nclass BaseVariable(pycompat.ABC):\n\n def __init__(self, source, exclude=()):\n self.source = source\n self.exclude = utils.ensure_tuple(exclude)\n self.code = compile(source, '', 'eval')\n if needs_parentheses(source):\n self.unambiguous_source = '({})'.format(source)\n else:\n self.unambiguous_source = source\n\n def __eq__(self, other):\n return (isinstance(other, BaseVariable) and\n self._fingerprint == other._fingerprint)", "has_branch": false, "total_branches": 0} {"prompt_id": 448, "project": "pysnooper", "module": "pysnooper.variables", "class": "Indices", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, item):\n assert isinstance(item, slice)\n result = deepcopy(self)\n result._slice = item\n return result", "focal_method_lines": [116, 120], "in_stack": false, "globals": [], "type_context": "import itertools\nimport abc\nfrom copy import deepcopy\nfrom . import utils\nfrom . import pycompat\n\n\n\nclass Indices(Keys):\n\n _slice = slice(None)\n\n def __getitem__(self, item):\n assert isinstance(item, slice)\n result = deepcopy(self)\n result._slice = item\n return result", "has_branch": false, "total_branches": 0} {"prompt_id": 449, "project": "pytutils", "module": "pytutils.env", "class": "", "method": "parse_env_file_contents", "focal_method_txt": "def parse_env_file_contents(lines: typing.Iterable[str] = None) -> typing.Generator[typing.Tuple[str, str], None, None]:\n \"\"\"\n Parses env file content.\n\n From honcho.\n\n >>> lines = ['TEST=${HOME}/yeee', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST']\n >>> load_env_file(lines, write_environ=dict())\n OrderedDict([('TEST', '.../yeee'),\n ('THISIS', '.../a/test'),\n ('YOLO',\n '.../swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST')])\n\n \"\"\"\n for line in lines:\n m1 = re.match(r'\\A([A-Za-z_0-9]+)=(.*)\\Z', line)\n\n if m1:\n key, val = m1.group(1), m1.group(2)\n\n m2 = re.match(r\"\\A'(.*)'\\Z\", val)\n if m2:\n val = m2.group(1)\n\n m3 = re.match(r'\\A\"(.*)\"\\Z', val)\n if m3:\n val = re.sub(r'\\\\(.)', r'\\1', m3.group(1))\n\n yield key, val", "focal_method_lines": [12, 40], "in_stack": true, "globals": [], "type_context": "import collections\nimport os\nimport re\nimport typing\n\n\n\ndef parse_env_file_contents(lines: typing.Iterable[str] = None) -> typing.Generator[typing.Tuple[str, str], None, None]:\n \"\"\"\n Parses env file content.\n\n From honcho.\n\n >>> lines = ['TEST=${HOME}/yeee', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST']\n >>> load_env_file(lines, write_environ=dict())\n OrderedDict([('TEST', '.../yeee'),\n ('THISIS', '.../a/test'),\n ('YOLO',\n '.../swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST')])\n\n \"\"\"\n for line in lines:\n m1 = re.match(r'\\A([A-Za-z_0-9]+)=(.*)\\Z', line)\n\n if m1:\n key, val = m1.group(1), m1.group(2)\n\n m2 = re.match(r\"\\A'(.*)'\\Z\", val)\n if m2:\n val = m2.group(1)\n\n m3 = re.match(r'\\A\"(.*)\"\\Z', val)\n if m3:\n val = re.sub(r'\\\\(.)', r'\\1', m3.group(1))\n\n yield key, val", "has_branch": true, "total_branches": 2} {"prompt_id": 450, "project": "pytutils", "module": "pytutils.env", "class": "", "method": "load_env_file", "focal_method_txt": "def load_env_file(lines: typing.Iterable[str], write_environ: typing.MutableMapping = os.environ) -> collections.OrderedDict:\n \"\"\"\n Loads (and returns) an env file specified by `filename` into the mapping `environ`.\n\n >>> lines = ['TEST=${HOME}/yeee-$PATH', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST']\n >>> load_env_file(lines, write_environ=dict())\n OrderedDict([('TEST', '.../.../yeee-...:...'),\n ('THISIS', '.../a/test'),\n ('YOLO',\n '.../swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST')])\n \"\"\"\n values = parse_env_file_contents(lines)\n\n changes = collections.OrderedDict()\n\n for k, v in values:\n v = expand(v)\n\n changes[k] = v\n\n if write_environ is not None:\n write_environ[k] = v\n\n return changes", "focal_method_lines": [43, 66], "in_stack": true, "globals": [], "type_context": "import collections\nimport os\nimport re\nimport typing\n\n\n\ndef load_env_file(lines: typing.Iterable[str], write_environ: typing.MutableMapping = os.environ) -> collections.OrderedDict:\n \"\"\"\n Loads (and returns) an env file specified by `filename` into the mapping `environ`.\n\n >>> lines = ['TEST=${HOME}/yeee-$PATH', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST']\n >>> load_env_file(lines, write_environ=dict())\n OrderedDict([('TEST', '.../.../yeee-...:...'),\n ('THISIS', '.../a/test'),\n ('YOLO',\n '.../swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST')])\n \"\"\"\n values = parse_env_file_contents(lines)\n\n changes = collections.OrderedDict()\n\n for k, v in values:\n v = expand(v)\n\n changes[k] = v\n\n if write_environ is not None:\n write_environ[k] = v\n\n return changes", "has_branch": true, "total_branches": 2} {"prompt_id": 451, "project": "pytutils", "module": "pytutils.files", "class": "", "method": "islurp", "focal_method_txt": "def islurp(filename, mode='r', iter_by=LINEMODE, allow_stdin=True, expanduser=True, expandvars=True):\n \"\"\"\n Read [expanded] `filename` and yield each (line | chunk).\n\n :param str filename: File path\n :param str mode: Use this mode to open `filename`, ala `r` for text (default), `rb` for binary, etc.\n :param int iter_by: Iterate by this many bytes at a time. Default is by line.\n :param bool allow_stdin: If Truthy and filename is `-`, read from `sys.stdin`.\n :param bool expanduser: If Truthy, expand `~` in `filename`\n :param bool expandvars: If Truthy, expand env vars in `filename`\n \"\"\"\n if iter_by == 'LINEMODE':\n iter_by = LINEMODE\n\n fh = None\n try:\n if filename == '-' and allow_stdin:\n fh = sys.stdin\n else:\n if expanduser:\n filename = os.path.expanduser(filename)\n if expandvars:\n filename = os.path.expandvars(filename)\n\n fh = open(filename, mode)\n fh_next = fh.readline if iter_by == LINEMODE else functools.partial(fh.read, iter_by)\n\n while True:\n buf = fh_next()\n if buf == '': # EOF\n break\n yield buf\n finally:\n if fh and fh != sys.stdin:\n fh.close()", "focal_method_lines": [11, 45], "in_stack": true, "globals": ["LINEMODE", "islurp", "slurp"], "type_context": "import os\nimport sys\nimport functools\n\nislurp.LINEMODE = LINEMODE\nislurp.LINEMODE = LINEMODE\nslurp = islurp\n\ndef islurp(filename, mode='r', iter_by=LINEMODE, allow_stdin=True, expanduser=True, expandvars=True):\n \"\"\"\n Read [expanded] `filename` and yield each (line | chunk).\n\n :param str filename: File path\n :param str mode: Use this mode to open `filename`, ala `r` for text (default), `rb` for binary, etc.\n :param int iter_by: Iterate by this many bytes at a time. Default is by line.\n :param bool allow_stdin: If Truthy and filename is `-`, read from `sys.stdin`.\n :param bool expanduser: If Truthy, expand `~` in `filename`\n :param bool expandvars: If Truthy, expand env vars in `filename`\n \"\"\"\n if iter_by == 'LINEMODE':\n iter_by = LINEMODE\n\n fh = None\n try:\n if filename == '-' and allow_stdin:\n fh = sys.stdin\n else:\n if expanduser:\n filename = os.path.expanduser(filename)\n if expandvars:\n filename = os.path.expandvars(filename)\n\n fh = open(filename, mode)\n fh_next = fh.readline if iter_by == LINEMODE else functools.partial(fh.read, iter_by)\n\n while True:\n buf = fh_next()\n if buf == '': # EOF\n break\n yield buf\n finally:\n if fh and fh != sys.stdin:\n fh.close()", "has_branch": true, "total_branches": 2} {"prompt_id": 452, "project": "pytutils", "module": "pytutils.files", "class": "", "method": "burp", "focal_method_txt": "def burp(filename, contents, mode='w', allow_stdout=True, expanduser=True, expandvars=True):\n \"\"\"\n Write `contents` to `filename`.\n \"\"\"\n if filename == '-' and allow_stdout:\n sys.stdout.write(contents)\n else:\n if expanduser:\n filename = os.path.expanduser(filename)\n if expandvars:\n filename = os.path.expandvars(filename)\n\n with open(filename, mode) as fh:\n fh.write(contents)", "focal_method_lines": [54, 67], "in_stack": true, "globals": ["LINEMODE", "islurp", "slurp"], "type_context": "import os\nimport sys\nimport functools\n\nislurp.LINEMODE = LINEMODE\nislurp.LINEMODE = LINEMODE\nslurp = islurp\n\ndef burp(filename, contents, mode='w', allow_stdout=True, expanduser=True, expandvars=True):\n \"\"\"\n Write `contents` to `filename`.\n \"\"\"\n if filename == '-' and allow_stdout:\n sys.stdout.write(contents)\n else:\n if expanduser:\n filename = os.path.expanduser(filename)\n if expandvars:\n filename = os.path.expandvars(filename)\n\n with open(filename, mode) as fh:\n fh.write(contents)", "has_branch": true, "total_branches": 2} {"prompt_id": 453, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "IllegalUseOfScopeReplacer", "method": "__unicode__", "focal_method_txt": " def __unicode__(self):\n u = self._format()\n if isinstance(u, str):\n # Try decoding the str using the default encoding.\n u = unicode(u)\n elif not isinstance(u, unicode):\n # Try to make a unicode object from it, because __unicode__ must\n # return a unicode object.\n u = unicode(u)\n return u", "focal_method_lines": [84, 93], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass IllegalUseOfScopeReplacer(Exception):\n\n _fmt = (\"ScopeReplacer object %(name)r was used incorrectly:\"\n \" %(msg)s%(extra)s\")\n\n def __init__(self, name, msg, extra=None):\n self.name = name\n self.msg = msg\n if extra:\n self.extra = ': ' + str(extra)\n else:\n self.extra = ''\n\n super(IllegalUseOfScopeReplacer, self).__init__()\n\n def __unicode__(self):\n u = self._format()\n if isinstance(u, str):\n # Try decoding the str using the default encoding.\n u = unicode(u)\n elif not isinstance(u, unicode):\n # Try to make a unicode object from it, because __unicode__ must\n # return a unicode object.\n u = unicode(u)\n return u", "has_branch": true, "total_branches": 2} {"prompt_id": 454, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "IllegalUseOfScopeReplacer", "method": "__str__", "focal_method_txt": " def __str__(self):\n s = self._format()\n if isinstance(s, unicode):\n s = s.encode('utf8')\n else:\n # __str__ must return a str.\n s = str(s)\n return s", "focal_method_lines": [95, 102], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass IllegalUseOfScopeReplacer(Exception):\n\n _fmt = (\"ScopeReplacer object %(name)r was used incorrectly:\"\n \" %(msg)s%(extra)s\")\n\n def __init__(self, name, msg, extra=None):\n self.name = name\n self.msg = msg\n if extra:\n self.extra = ': ' + str(extra)\n else:\n self.extra = ''\n\n super(IllegalUseOfScopeReplacer, self).__init__()\n\n def __str__(self):\n s = self._format()\n if isinstance(s, unicode):\n s = s.encode('utf8')\n else:\n # __str__ must return a str.\n s = str(s)\n return s", "has_branch": true, "total_branches": 2} {"prompt_id": 455, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "IllegalUseOfScopeReplacer", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n if self.__class__ is not other.__class__:\n return NotImplemented\n return self.__dict__ == other.__dict__", "focal_method_lines": [114, 117], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass IllegalUseOfScopeReplacer(Exception):\n\n _fmt = (\"ScopeReplacer object %(name)r was used incorrectly:\"\n \" %(msg)s%(extra)s\")\n\n def __init__(self, name, msg, extra=None):\n self.name = name\n self.msg = msg\n if extra:\n self.extra = ': ' + str(extra)\n else:\n self.extra = ''\n\n super(IllegalUseOfScopeReplacer, self).__init__()\n\n def __eq__(self, other):\n if self.__class__ is not other.__class__:\n return NotImplemented\n return self.__dict__ == other.__dict__", "has_branch": true, "total_branches": 2} {"prompt_id": 456, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "ScopeReplacer", "method": "__getattribute__", "focal_method_txt": " def __getattribute__(self, attr):\n obj = object.__getattribute__(self, '_resolve')()\n return getattr(obj, attr)", "focal_method_lines": [180, 182], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass ScopeReplacer(object):\n\n __slots__ = ('_scope', '_factory', '_name', '_real_obj')\n\n _should_proxy = True\n\n def __init__(self, scope, factory, name):\n \"\"\"Create a temporary object in the specified scope.\n Once used, a real object will be placed in the scope.\n\n :param scope: The scope the object should appear in\n :param factory: A callable that will create the real object.\n It will be passed (self, scope, name)\n :param name: The variable name in the given scope.\n \"\"\"\n object.__setattr__(self, '_scope', scope)\n object.__setattr__(self, '_factory', factory)\n object.__setattr__(self, '_name', name)\n object.__setattr__(self, '_real_obj', None)\n scope[name] = self\n\n def __getattribute__(self, attr):\n obj = object.__getattribute__(self, '_resolve')()\n return getattr(obj, attr)", "has_branch": false, "total_branches": 0} {"prompt_id": 457, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "ScopeReplacer", "method": "__setattr__", "focal_method_txt": " def __setattr__(self, attr, value):\n obj = object.__getattribute__(self, '_resolve')()\n return setattr(obj, attr, value)", "focal_method_lines": [184, 186], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass ScopeReplacer(object):\n\n __slots__ = ('_scope', '_factory', '_name', '_real_obj')\n\n _should_proxy = True\n\n def __init__(self, scope, factory, name):\n \"\"\"Create a temporary object in the specified scope.\n Once used, a real object will be placed in the scope.\n\n :param scope: The scope the object should appear in\n :param factory: A callable that will create the real object.\n It will be passed (self, scope, name)\n :param name: The variable name in the given scope.\n \"\"\"\n object.__setattr__(self, '_scope', scope)\n object.__setattr__(self, '_factory', factory)\n object.__setattr__(self, '_name', name)\n object.__setattr__(self, '_real_obj', None)\n scope[name] = self\n\n def __setattr__(self, attr, value):\n obj = object.__getattribute__(self, '_resolve')()\n return setattr(obj, attr, value)", "has_branch": false, "total_branches": 0} {"prompt_id": 458, "project": "pytutils", "module": "pytutils.lazy.lazy_import", "class": "ScopeReplacer", "method": "__call__", "focal_method_txt": " def __call__(self, *args, **kwargs):\n obj = object.__getattribute__(self, '_resolve')()\n return obj(*args, **kwargs)", "focal_method_lines": [188, 190], "in_stack": true, "globals": [], "type_context": "\n\n\n\nclass ScopeReplacer(object):\n\n __slots__ = ('_scope', '_factory', '_name', '_real_obj')\n\n _should_proxy = True\n\n def __init__(self, scope, factory, name):\n \"\"\"Create a temporary object in the specified scope.\n Once used, a real object will be placed in the scope.\n\n :param scope: The scope the object should appear in\n :param factory: A callable that will create the real object.\n It will be passed (self, scope, name)\n :param name: The variable name in the given scope.\n \"\"\"\n object.__setattr__(self, '_scope', scope)\n object.__setattr__(self, '_factory', factory)\n object.__setattr__(self, '_name', name)\n object.__setattr__(self, '_real_obj', None)\n scope[name] = self\n\n def __call__(self, *args, **kwargs):\n obj = object.__getattribute__(self, '_resolve')()\n return obj(*args, **kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 459, "project": "pytutils", "module": "pytutils.lazy.lazy_regex", "class": "InvalidPattern", "method": "__unicode__", "focal_method_txt": " def __unicode__(self):\n u = self._format()\n if isinstance(u, str):\n # Try decoding the str using the default encoding.\n u = unicode(u)\n elif not isinstance(u, unicode):\n # Try to make a unicode object from it, because __unicode__ must\n # return a unicode object.\n u = unicode(u)\n return u", "focal_method_lines": [61, 70], "in_stack": true, "globals": ["_real_re_compile"], "type_context": "import re\n\n_real_re_compile = re.compile\n\nclass InvalidPattern(ValueError):\n\n _fmt = ('Invalid pattern(s) found. %(msg)s')\n\n def __init__(self, msg):\n self.msg = msg\n\n def __unicode__(self):\n u = self._format()\n if isinstance(u, str):\n # Try decoding the str using the default encoding.\n u = unicode(u)\n elif not isinstance(u, unicode):\n # Try to make a unicode object from it, because __unicode__ must\n # return a unicode object.\n u = unicode(u)\n return u", "has_branch": true, "total_branches": 2} {"prompt_id": 460, "project": "pytutils", "module": "pytutils.lazy.lazy_regex", "class": "InvalidPattern", "method": "__str__", "focal_method_txt": " def __str__(self):\n s = self._format()\n if isinstance(s, unicode):\n s = s.encode('utf8')\n else:\n # __str__ must return a str.\n s = str(s)\n return s", "focal_method_lines": [72, 79], "in_stack": true, "globals": ["_real_re_compile"], "type_context": "import re\n\n_real_re_compile = re.compile\n\nclass InvalidPattern(ValueError):\n\n _fmt = ('Invalid pattern(s) found. %(msg)s')\n\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n s = self._format()\n if isinstance(s, unicode):\n s = s.encode('utf8')\n else:\n # __str__ must return a str.\n s = str(s)\n return s", "has_branch": true, "total_branches": 2} {"prompt_id": 461, "project": "pytutils", "module": "pytutils.lazy.lazy_regex", "class": "LazyRegex", "method": "__setstate__", "focal_method_txt": " def __setstate__(self, dict):\n \"\"\"Restore from a pickled state.\"\"\"\n self._real_regex = None\n setattr(self, \"_regex_args\", dict[\"args\"])\n setattr(self, \"_regex_kwargs\", dict[\"kwargs\"])", "focal_method_lines": [146, 150], "in_stack": true, "globals": ["_real_re_compile"], "type_context": "import re\n\n_real_re_compile = re.compile\n\nclass LazyRegex(object):\n\n _regex_attributes_to_copy = [\n '__copy__', '__deepcopy__', 'findall', 'finditer', 'match',\n 'scanner', 'search', 'split', 'sub', 'subn'\n ]\n\n __slots__ = ['_real_regex', '_regex_args', '_regex_kwargs',\n ] + _regex_attributes_to_copy\n\n def __init__(self, args=(), kwargs={}):\n \"\"\"Create a new proxy object, passing in the args to pass to re.compile\n\n :param args: The `*args` to pass to re.compile\n :param kwargs: The `**kwargs` to pass to re.compile\n \"\"\"\n self._real_regex = None\n self._regex_args = args\n self._regex_kwargs = kwargs\n\n def __setstate__(self, dict):\n \"\"\"Restore from a pickled state.\"\"\"\n self._real_regex = None\n setattr(self, \"_regex_args\", dict[\"args\"])\n setattr(self, \"_regex_kwargs\", dict[\"kwargs\"])", "has_branch": false, "total_branches": 0} {"prompt_id": 462, "project": "pytutils", "module": "pytutils.lazy.lazy_regex", "class": "LazyRegex", "method": "__getattr__", "focal_method_txt": " def __getattr__(self, attr):\n \"\"\"Return a member from the proxied regex object.\n\n If the regex hasn't been compiled yet, compile it\n \"\"\"\n if self._real_regex is None:\n self._compile_and_collapse()\n # Once we have compiled, the only time we should come here\n # is actually if the attribute is missing.\n return getattr(self._real_regex, attr)", "focal_method_lines": [152, 161], "in_stack": true, "globals": ["_real_re_compile"], "type_context": "import re\n\n_real_re_compile = re.compile\n\nclass LazyRegex(object):\n\n _regex_attributes_to_copy = [\n '__copy__', '__deepcopy__', 'findall', 'finditer', 'match',\n 'scanner', 'search', 'split', 'sub', 'subn'\n ]\n\n __slots__ = ['_real_regex', '_regex_args', '_regex_kwargs',\n ] + _regex_attributes_to_copy\n\n def __init__(self, args=(), kwargs={}):\n \"\"\"Create a new proxy object, passing in the args to pass to re.compile\n\n :param args: The `*args` to pass to re.compile\n :param kwargs: The `**kwargs` to pass to re.compile\n \"\"\"\n self._real_regex = None\n self._regex_args = args\n self._regex_kwargs = kwargs\n\n def __getattr__(self, attr):\n \"\"\"Return a member from the proxied regex object.\n\n If the regex hasn't been compiled yet, compile it\n \"\"\"\n if self._real_regex is None:\n self._compile_and_collapse()\n # Once we have compiled, the only time we should come here\n # is actually if the attribute is missing.\n return getattr(self._real_regex, attr)", "has_branch": true, "total_branches": 2} {"prompt_id": 463, "project": "pytutils", "module": "pytutils.lazy.simple_import", "class": "", "method": "make_lazy", "focal_method_txt": "def make_lazy(module_path):\n \"\"\"\n Mark that this module should not be imported until an\n attribute is needed off of it.\n \"\"\"\n sys_modules = sys.modules # cache in the locals\n\n # store our 'instance' data in the closure.\n module = NonLocal(None)\n\n class LazyModule(_LazyModuleMarker):\n \"\"\"\n A standin for a module to prevent it from being imported\n \"\"\"\n def __mro__(self):\n \"\"\"\n Override the __mro__ to fool `isinstance`.\n \"\"\"\n # We don't use direct subclassing because `ModuleType` has an\n # incompatible metaclass base with object (they are both in c)\n # and we are overridding __getattribute__.\n # By putting a __mro__ method here, we can pass `isinstance`\n # checks without ever invoking our __getattribute__ function.\n return (LazyModule, ModuleType)\n\n def __getattribute__(self, attr):\n \"\"\"\n Override __getattribute__ to hide the implementation details.\n \"\"\"\n if module.value is None:\n del sys_modules[module_path]\n module.value = __import__(module_path)\n\n sys_modules[module_path] = __import__(module_path)\n\n return getattr(module.value, attr)\n\n sys_modules[module_path] = LazyModule()", "focal_method_lines": [23, 60], "in_stack": true, "globals": [], "type_context": "import sys\nfrom types import ModuleType\n\n\n\nclass NonLocal(object):\n\n __slots__ = ['value']\n\n def __init__(self, value):\n self.value = value\n\ndef make_lazy(module_path):\n \"\"\"\n Mark that this module should not be imported until an\n attribute is needed off of it.\n \"\"\"\n sys_modules = sys.modules # cache in the locals\n\n # store our 'instance' data in the closure.\n module = NonLocal(None)\n\n class LazyModule(_LazyModuleMarker):\n \"\"\"\n A standin for a module to prevent it from being imported\n \"\"\"\n def __mro__(self):\n \"\"\"\n Override the __mro__ to fool `isinstance`.\n \"\"\"\n # We don't use direct subclassing because `ModuleType` has an\n # incompatible metaclass base with object (they are both in c)\n # and we are overridding __getattribute__.\n # By putting a __mro__ method here, we can pass `isinstance`\n # checks without ever invoking our __getattribute__ function.\n return (LazyModule, ModuleType)\n\n def __getattribute__(self, attr):\n \"\"\"\n Override __getattribute__ to hide the implementation details.\n \"\"\"\n if module.value is None:\n del sys_modules[module_path]\n module.value = __import__(module_path)\n\n sys_modules[module_path] = __import__(module_path)\n\n return getattr(module.value, attr)\n\n sys_modules[module_path] = LazyModule()", "has_branch": true, "total_branches": 2} {"prompt_id": 464, "project": "pytutils", "module": "pytutils.log", "class": "", "method": "configure", "focal_method_txt": "def configure(config=None, env_var='LOGGING', default=DEFAULT_CONFIG):\n \"\"\"\n\n >>> log = logging.getLogger(__name__)\n >>> configure()\n >>> log.info('test')\n\n \"\"\"\n cfg = get_config(config, env_var, default)\n\n try:\n logging.config.dictConfig(cfg)\n except TypeError as exc:\n try:\n logging.basicConfig(**cfg)\n except Exception as inner_exc:\n raise inner_exc from exc", "focal_method_lines": [80, 96], "in_stack": true, "globals": ["DEFAULT_CONFIG", "_CONFIGURED", "getLogger"], "type_context": "import logging\nimport logging.config\nimport inspect\nimport sys\nimport os\nfrom contextlib import contextmanager\n\nDEFAULT_CONFIG = dict(\n version=1,\n disable_existing_loggers=False,\n formatters={\n 'colored': {\n '()': 'colorlog.ColoredFormatter',\n 'format':\n '%(bg_black)s%(log_color)s'\n '[%(asctime)s] '\n '[%(name)s/%(process)d] '\n '%(message)s '\n '%(blue)s@%(funcName)s:%(lineno)d '\n '#%(levelname)s'\n '%(reset)s',\n 'datefmt': '%H:%M:%S',\n },\n 'simple': {\n # format=' '.join(\n # [\n # '%(asctime)s|',\n # '%(name)s/%(processName)s[%(process)d]-%(threadName)s[%(thread)d]:'\n # '%(message)s @%(funcName)s:%(lineno)d #%(levelname)s',\n # ]\n # ),\n 'format':\n '%(asctime)s| %(name)s/%(processName)s[%(process)d]-%(threadName)s[%(thread)d]: '\n '%(message)s @%(funcName)s:%(lineno)d #%(levelname)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n },\n },\n handlers={\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'colored',\n 'level': logging.DEBUG,\n },\n },\n root=dict(handlers=['console'], level=logging.DEBUG),\n loggers={\n 'requests': dict(level=logging.INFO),\n },\n)\n_CONFIGURED = []\ngetLogger = get_logger\n\ndef configure(config=None, env_var='LOGGING', default=DEFAULT_CONFIG):\n \"\"\"\n\n >>> log = logging.getLogger(__name__)\n >>> configure()\n >>> log.info('test')\n\n \"\"\"\n cfg = get_config(config, env_var, default)\n\n try:\n logging.config.dictConfig(cfg)\n except TypeError as exc:\n try:\n logging.basicConfig(**cfg)\n except Exception as inner_exc:\n raise inner_exc from exc", "has_branch": false, "total_branches": 0} {"prompt_id": 465, "project": "pytutils", "module": "pytutils.log", "class": "", "method": "get_config", "focal_method_txt": "def get_config(given=None, env_var=None, default=None):\n config = given\n\n if not config and env_var:\n config = os.environ.get(env_var)\n\n if not config and default:\n config = default\n\n if config is None:\n raise ValueError('Invalid logging config: %s' % config)\n\n if isinstance(config, _PyInfo.string_types):\n import json\n\n try:\n config = json.loads(config)\n except ValueError:\n import yaml\n\n try:\n config = yaml.load(config)\n except ValueError:\n raise ValueError(\n \"Could not parse logging config as bare, json,\"\n \" or yaml: %s\" % config\n )\n\n return config", "focal_method_lines": [99, 127], "in_stack": true, "globals": ["DEFAULT_CONFIG", "_CONFIGURED", "getLogger"], "type_context": "import logging\nimport logging.config\nimport inspect\nimport sys\nimport os\nfrom contextlib import contextmanager\n\nDEFAULT_CONFIG = dict(\n version=1,\n disable_existing_loggers=False,\n formatters={\n 'colored': {\n '()': 'colorlog.ColoredFormatter',\n 'format':\n '%(bg_black)s%(log_color)s'\n '[%(asctime)s] '\n '[%(name)s/%(process)d] '\n '%(message)s '\n '%(blue)s@%(funcName)s:%(lineno)d '\n '#%(levelname)s'\n '%(reset)s',\n 'datefmt': '%H:%M:%S',\n },\n 'simple': {\n # format=' '.join(\n # [\n # '%(asctime)s|',\n # '%(name)s/%(processName)s[%(process)d]-%(threadName)s[%(thread)d]:'\n # '%(message)s @%(funcName)s:%(lineno)d #%(levelname)s',\n # ]\n # ),\n 'format':\n '%(asctime)s| %(name)s/%(processName)s[%(process)d]-%(threadName)s[%(thread)d]: '\n '%(message)s @%(funcName)s:%(lineno)d #%(levelname)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n },\n },\n handlers={\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'colored',\n 'level': logging.DEBUG,\n },\n },\n root=dict(handlers=['console'], level=logging.DEBUG),\n loggers={\n 'requests': dict(level=logging.INFO),\n },\n)\n_CONFIGURED = []\ngetLogger = get_logger\n\ndef get_config(given=None, env_var=None, default=None):\n config = given\n\n if not config and env_var:\n config = os.environ.get(env_var)\n\n if not config and default:\n config = default\n\n if config is None:\n raise ValueError('Invalid logging config: %s' % config)\n\n if isinstance(config, _PyInfo.string_types):\n import json\n\n try:\n config = json.loads(config)\n except ValueError:\n import yaml\n\n try:\n config = yaml.load(config)\n except ValueError:\n raise ValueError(\n \"Could not parse logging config as bare, json,\"\n \" or yaml: %s\" % config\n )\n\n return config", "has_branch": true, "total_branches": 2} {"prompt_id": 466, "project": "pytutils", "module": "pytutils.path", "class": "", "method": "join_each", "focal_method_txt": "def join_each(parent, iterable):\n for p in iterable:\n yield os.path.join(parent, p)", "focal_method_lines": [3, 5], "in_stack": true, "globals": [], "type_context": "import os\n\n\n\ndef join_each(parent, iterable):\n for p in iterable:\n yield os.path.join(parent, p)", "has_branch": true, "total_branches": 2} {"prompt_id": 467, "project": "pytutils", "module": "pytutils.props", "class": "", "method": "lazyperclassproperty", "focal_method_txt": "def lazyperclassproperty(fn):\n \"\"\"\n Lazy/Cached class property that stores separate instances per class/inheritor so there's no overlap.\n \"\"\"\n\n @classproperty\n def _lazyclassprop(cls):\n attr_name = '_%s_lazy_%s' % (cls.__name__, fn.__name__)\n if not hasattr(cls, attr_name):\n setattr(cls, attr_name, fn(cls))\n return getattr(cls, attr_name)\n\n return _lazyclassprop", "focal_method_lines": [24, 36], "in_stack": true, "globals": ["classproperty"], "type_context": "\n\nclassproperty = roclassproperty\n\ndef lazyperclassproperty(fn):\n \"\"\"\n Lazy/Cached class property that stores separate instances per class/inheritor so there's no overlap.\n \"\"\"\n\n @classproperty\n def _lazyclassprop(cls):\n attr_name = '_%s_lazy_%s' % (cls.__name__, fn.__name__)\n if not hasattr(cls, attr_name):\n setattr(cls, attr_name, fn(cls))\n return getattr(cls, attr_name)\n\n return _lazyclassprop", "has_branch": true, "total_branches": 2} {"prompt_id": 468, "project": "pytutils", "module": "pytutils.props", "class": "", "method": "lazyclassproperty", "focal_method_txt": "def lazyclassproperty(fn):\n \"\"\"\n Lazy/Cached class property.\n \"\"\"\n attr_name = '_lazy_' + fn.__name__\n\n @classproperty\n def _lazyclassprop(cls):\n if not hasattr(cls, attr_name):\n setattr(cls, attr_name, fn(cls))\n return getattr(cls, attr_name)\n\n return _lazyclassprop", "focal_method_lines": [39, 51], "in_stack": true, "globals": ["classproperty"], "type_context": "\n\nclassproperty = roclassproperty\n\ndef lazyclassproperty(fn):\n \"\"\"\n Lazy/Cached class property.\n \"\"\"\n attr_name = '_lazy_' + fn.__name__\n\n @classproperty\n def _lazyclassprop(cls):\n if not hasattr(cls, attr_name):\n setattr(cls, attr_name, fn(cls))\n return getattr(cls, attr_name)\n\n return _lazyclassprop", "has_branch": true, "total_branches": 2} {"prompt_id": 469, "project": "pytutils", "module": "pytutils.trees", "class": "", "method": "get_tree_node", "focal_method_txt": "def get_tree_node(mapping, key, default=_sentinel, parent=False):\n \"\"\"\n Fetch arbitrary node from a tree-like mapping structure with traversal help:\n Dimension can be specified via ':'\n\n Arguments:\n mapping collections.Mapping: Mapping to fetch from\n key str|unicode: Key to lookup, allowing for : notation\n default object: Default value. If set to `:module:_sentinel`, raise KeyError if not found.\n parent bool: If True, return parent node. Defaults to False.\n\n Returns:\n object: Value at specified key\n \"\"\"\n key = key.split(':')\n if parent:\n key = key[:-1]\n\n # TODO Unlist my shit. Stop calling me please.\n\n node = mapping\n for node in key.split(':'):\n try:\n node = node[node]\n except KeyError as exc:\n node = default\n break\n\n if node is _sentinel:\n raise exc\n return node", "focal_method_lines": [5, 35], "in_stack": true, "globals": ["_sentinel"], "type_context": "import collections\n\n_sentinel = object()\n\ndef get_tree_node(mapping, key, default=_sentinel, parent=False):\n \"\"\"\n Fetch arbitrary node from a tree-like mapping structure with traversal help:\n Dimension can be specified via ':'\n\n Arguments:\n mapping collections.Mapping: Mapping to fetch from\n key str|unicode: Key to lookup, allowing for : notation\n default object: Default value. If set to `:module:_sentinel`, raise KeyError if not found.\n parent bool: If True, return parent node. Defaults to False.\n\n Returns:\n object: Value at specified key\n \"\"\"\n key = key.split(':')\n if parent:\n key = key[:-1]\n\n # TODO Unlist my shit. Stop calling me please.\n\n node = mapping\n for node in key.split(':'):\n try:\n node = node[node]\n except KeyError as exc:\n node = default\n break\n\n if node is _sentinel:\n raise exc\n return node", "has_branch": true, "total_branches": 2} {"prompt_id": 470, "project": "pytutils", "module": "pytutils.trees", "class": "", "method": "set_tree_node", "focal_method_txt": "def set_tree_node(mapping, key, value):\n \"\"\"\n Set arbitrary node on a tree-like mapping structure, allowing for : notation to signify dimension.\n\n Arguments:\n mapping collections.Mapping: Mapping to fetch from\n key str|unicode: Key to set, allowing for : notation\n value str|unicode: Value to set `key` to\n parent bool: If True, return parent node. Defaults to False.\n\n Returns:\n object: Parent node.\n\n \"\"\"\n basename, dirname = key.rsplit(':', 2)\n parent_node = get_tree_node(mapping, dirname)\n parent_node[basename] = value\n return parent_node", "focal_method_lines": [38, 55], "in_stack": true, "globals": ["_sentinel"], "type_context": "import collections\n\n_sentinel = object()\n\ndef set_tree_node(mapping, key, value):\n \"\"\"\n Set arbitrary node on a tree-like mapping structure, allowing for : notation to signify dimension.\n\n Arguments:\n mapping collections.Mapping: Mapping to fetch from\n key str|unicode: Key to set, allowing for : notation\n value str|unicode: Value to set `key` to\n parent bool: If True, return parent node. Defaults to False.\n\n Returns:\n object: Parent node.\n\n \"\"\"\n basename, dirname = key.rsplit(':', 2)\n parent_node = get_tree_node(mapping, dirname)\n parent_node[basename] = value\n return parent_node", "has_branch": false, "total_branches": 0} {"prompt_id": 471, "project": "pytutils", "module": "pytutils.trees", "class": "Tree", "method": "__init__", "focal_method_txt": " def __init__(self, initial=None, namespace='', initial_is_ref=False):\n if initial is not None and initial_is_ref:\n self.data = initial_is_ref\n self.namespace = namespace\n super(Tree, self).__init__(self.__class__)\n if initial is not None:\n self.update(initial)", "focal_method_lines": [71, 77], "in_stack": true, "globals": ["_sentinel"], "type_context": "import collections\n\n_sentinel = object()\n\nclass Tree(collections.defaultdict):\n\n namespace = None\n\n get = __getitem__\n\n def __init__(self, initial=None, namespace='', initial_is_ref=False):\n if initial is not None and initial_is_ref:\n self.data = initial_is_ref\n self.namespace = namespace\n super(Tree, self).__init__(self.__class__)\n if initial is not None:\n self.update(initial)", "has_branch": true, "total_branches": 2} {"prompt_id": 472, "project": "pytutils", "module": "pytutils.urls", "class": "", "method": "update_query_params", "focal_method_txt": "def update_query_params(url, params, doseq=True):\n \"\"\"\n Update and/or insert query parameters in a URL.\n\n >>> update_query_params('http://example.com?foo=bar&biz=baz', dict(foo='stuff'))\n 'http://example.com?...foo=stuff...'\n\n :param url: URL\n :type url: str\n :param kwargs: Query parameters\n :type kwargs: dict\n :return: Modified URL\n :rtype: str\n \"\"\"\n scheme, netloc, path, query_string, fragment = urlparse.urlsplit(url)\n\n query_params = urlparse.parse_qs(query_string)\n query_params.update(**params)\n\n new_query_string = urlencode(query_params, doseq=doseq)\n\n new_url = urlparse.urlunsplit([scheme, netloc, path, new_query_string, fragment])\n return new_url", "focal_method_lines": [8, 30], "in_stack": true, "globals": [], "type_context": "\n\n\n\ndef update_query_params(url, params, doseq=True):\n \"\"\"\n Update and/or insert query parameters in a URL.\n\n >>> update_query_params('http://example.com?foo=bar&biz=baz', dict(foo='stuff'))\n 'http://example.com?...foo=stuff...'\n\n :param url: URL\n :type url: str\n :param kwargs: Query parameters\n :type kwargs: dict\n :return: Modified URL\n :rtype: str\n \"\"\"\n scheme, netloc, path, query_string, fragment = urlparse.urlsplit(url)\n\n query_params = urlparse.parse_qs(query_string)\n query_params.update(**params)\n\n new_query_string = urlencode(query_params, doseq=doseq)\n\n new_url = urlparse.urlunsplit([scheme, netloc, path, new_query_string, fragment])\n return new_url", "has_branch": false, "total_branches": 0} {"prompt_id": 473, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__init__", "focal_method_txt": " def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes", "focal_method_lines": [58, 70], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes", "has_branch": false, "total_branches": 0} {"prompt_id": 474, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__iter__", "focal_method_txt": " def __iter__(self):\n \"\"\"\n Tun the class Blueprint Group into an Iterable item\n \"\"\"\n return iter(self._blueprints)", "focal_method_lines": [109, 113], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def __iter__(self):\n \"\"\"\n Tun the class Blueprint Group into an Iterable item\n \"\"\"\n return iter(self._blueprints)", "has_branch": false, "total_branches": 0} {"prompt_id": 475, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, item):\n \"\"\"\n This method returns a blueprint inside the group specified by\n an index value. This will enable indexing, splice and slicing\n of the blueprint group like we can do with regular list/tuple.\n\n This method is provided to ensure backward compatibility with\n any of the pre-existing usage that might break.\n\n :param item: Index of the Blueprint item in the group\n :return: Blueprint object\n \"\"\"\n return self._blueprints[item]", "focal_method_lines": [115, 127], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def __getitem__(self, item):\n \"\"\"\n This method returns a blueprint inside the group specified by\n an index value. This will enable indexing, splice and slicing\n of the blueprint group like we can do with regular list/tuple.\n\n This method is provided to ensure backward compatibility with\n any of the pre-existing usage that might break.\n\n :param item: Index of the Blueprint item in the group\n :return: Blueprint object\n \"\"\"\n return self._blueprints[item]", "has_branch": false, "total_branches": 0} {"prompt_id": 476, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__setitem__", "focal_method_txt": " def __setitem__(self, index, item) -> None:\n \"\"\"\n Abstract method implemented to turn the `BlueprintGroup` class\n into a list like object to support all the existing behavior.\n\n This method is used to perform the list's indexed setter operation.\n\n :param index: Index to use for inserting a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints[index] = item", "focal_method_lines": [129, 140], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def __setitem__(self, index, item) -> None:\n \"\"\"\n Abstract method implemented to turn the `BlueprintGroup` class\n into a list like object to support all the existing behavior.\n\n This method is used to perform the list's indexed setter operation.\n\n :param index: Index to use for inserting a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints[index] = item", "has_branch": false, "total_branches": 0} {"prompt_id": 477, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__delitem__", "focal_method_txt": " def __delitem__(self, index) -> None:\n \"\"\"\n Abstract method implemented to turn the `BlueprintGroup` class\n into a list like object to support all the existing behavior.\n\n This method is used to delete an item from the list of blueprint\n groups like it can be done on a regular list with index.\n\n :param index: Index to use for removing a new Blueprint item\n :return: None\n \"\"\"\n del self._blueprints[index]", "focal_method_lines": [142, 153], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def __delitem__(self, index) -> None:\n \"\"\"\n Abstract method implemented to turn the `BlueprintGroup` class\n into a list like object to support all the existing behavior.\n\n This method is used to delete an item from the list of blueprint\n groups like it can be done on a regular list with index.\n\n :param index: Index to use for removing a new Blueprint item\n :return: None\n \"\"\"\n del self._blueprints[index]", "has_branch": false, "total_branches": 0} {"prompt_id": 478, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "__len__", "focal_method_txt": " def __len__(self) -> int:\n \"\"\"\n Get the Length of the blueprint group object.\n\n :return: Length of Blueprint group object\n \"\"\"\n return len(self._blueprints)", "focal_method_lines": [155, 161], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def __len__(self) -> int:\n \"\"\"\n Get the Length of the blueprint group object.\n\n :return: Length of Blueprint group object\n \"\"\"\n return len(self._blueprints)", "has_branch": false, "total_branches": 0} {"prompt_id": 479, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "append", "focal_method_txt": " def append(self, value: \"sanic.Blueprint\") -> None:\n \"\"\"\n The Abstract class `MutableSequence` leverages this append method to\n perform the `BlueprintGroup.append` operation.\n :param value: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints.append(self._sanitize_blueprint(bp=value))", "focal_method_lines": [181, 188], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def append(self, value: \"sanic.Blueprint\") -> None:\n \"\"\"\n The Abstract class `MutableSequence` leverages this append method to\n perform the `BlueprintGroup.append` operation.\n :param value: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints.append(self._sanitize_blueprint(bp=value))", "has_branch": false, "total_branches": 0} {"prompt_id": 480, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "insert", "focal_method_txt": " def insert(self, index: int, item: \"sanic.Blueprint\") -> None:\n \"\"\"\n The Abstract class `MutableSequence` leverages this insert method to\n perform the `BlueprintGroup.append` operation.\n\n :param index: Index to use for removing a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints.insert(index, self._sanitize_blueprint(item))", "focal_method_lines": [190, 199], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def insert(self, index: int, item: \"sanic.Blueprint\") -> None:\n \"\"\"\n The Abstract class `MutableSequence` leverages this insert method to\n perform the `BlueprintGroup.append` operation.\n\n :param index: Index to use for removing a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n \"\"\"\n self._blueprints.insert(index, self._sanitize_blueprint(item))", "has_branch": false, "total_branches": 0} {"prompt_id": 481, "project": "sanic", "module": "sanic.blueprint_group", "class": "BlueprintGroup", "method": "middleware", "focal_method_txt": " def middleware(self, *args, **kwargs):\n \"\"\"\n A decorator that can be used to implement a Middleware plugin to\n all of the Blueprints that belongs to this specific Blueprint Group.\n\n In case of nested Blueprint Groups, the same middleware is applied\n across each of the Blueprints recursively.\n\n :param args: Optional positional Parameters to be use middleware\n :param kwargs: Optional Keyword arg to use with Middleware\n :return: Partial function to apply the middleware\n \"\"\"\n\n def register_middleware_for_blueprints(fn):\n for blueprint in self.blueprints:\n blueprint.middleware(fn, *args, **kwargs)\n\n if args and callable(args[0]):\n fn = args[0]\n args = list(args)[1:]\n return register_middleware_for_blueprints(fn)\n return register_middleware_for_blueprints", "focal_method_lines": [201, 222], "in_stack": false, "globals": [], "type_context": "from collections.abc import MutableSequence\nfrom typing import List, Optional, Union\nimport sanic\n\n\n\nclass BlueprintGroup(MutableSequence):\n\n __slots__ = (\"_blueprints\", \"_url_prefix\", \"_version\", \"_strict_slashes\")\n\n def __init__(self, url_prefix=None, version=None, strict_slashes=None):\n \"\"\"\n Create a new Blueprint Group\n\n :param url_prefix: URL: to be prefixed before all the Blueprint Prefix\n :param version: API Version for the blueprint group. This will be\n inherited by each of the Blueprint\n :param strict_slashes: URL Strict slash behavior indicator\n \"\"\"\n self._blueprints = []\n self._url_prefix = url_prefix\n self._version = version\n self._strict_slashes = strict_slashes\n\n def middleware(self, *args, **kwargs):\n \"\"\"\n A decorator that can be used to implement a Middleware plugin to\n all of the Blueprints that belongs to this specific Blueprint Group.\n\n In case of nested Blueprint Groups, the same middleware is applied\n across each of the Blueprints recursively.\n\n :param args: Optional positional Parameters to be use middleware\n :param kwargs: Optional Keyword arg to use with Middleware\n :return: Partial function to apply the middleware\n \"\"\"\n\n def register_middleware_for_blueprints(fn):\n for blueprint in self.blueprints:\n blueprint.middleware(fn, *args, **kwargs)\n\n if args and callable(args[0]):\n fn = args[0]\n args = list(args)[1:]\n return register_middleware_for_blueprints(fn)\n return register_middleware_for_blueprints", "has_branch": true, "total_branches": 2} {"prompt_id": 482, "project": "sanic", "module": "sanic.cookies", "class": "CookieJar", "method": "__setitem__", "focal_method_txt": " def __setitem__(self, key, value):\n # If this cookie doesn't exist, add it to the header keys\n if not self.cookie_headers.get(key):\n cookie = Cookie(key, value)\n cookie[\"path\"] = \"/\"\n self.cookie_headers[key] = self.header_key\n self.headers.add(self.header_key, cookie)\n return super().__setitem__(key, cookie)\n else:\n self[key].value = value", "focal_method_lines": [56, 65], "in_stack": false, "globals": ["DEFAULT_MAX_AGE", "_LegalChars", "_UnescapedChars", "_Translator", "_is_legal_key"], "type_context": "import re\nimport string\nfrom datetime import datetime\nfrom typing import Dict\n\nDEFAULT_MAX_AGE = 0\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + \" ()/<=>?@[]{}\"\n_Translator = {\n n: \"\\\\%03o\" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))\n}\n_is_legal_key = re.compile(\"[%s]+\" % re.escape(_LegalChars)).fullmatch\n\nclass Cookie(dict):\n\n _keys = {\n \"expires\": \"expires\",\n \"path\": \"Path\",\n \"comment\": \"Comment\",\n \"domain\": \"Domain\",\n \"max-age\": \"Max-Age\",\n \"secure\": \"Secure\",\n \"httponly\": \"HttpOnly\",\n \"version\": \"Version\",\n \"samesite\": \"SameSite\",\n }\n\n _flags = {\"secure\", \"httponly\"}\n\n def __init__(self, key, value):\n if key in self._keys:\n raise KeyError(\"Cookie name is a reserved word\")\n if not _is_legal_key(key):\n raise KeyError(\"Cookie key contains illegal characters\")\n self.key = key\n self.value = value\n super().__init__()\n\nclass CookieJar(dict):\n\n def __init__(self, headers):\n super().__init__()\n self.headers: Dict[str, str] = headers\n self.cookie_headers: Dict[str, str] = {}\n self.header_key: str = \"Set-Cookie\"\n\n def __setitem__(self, key, value):\n # If this cookie doesn't exist, add it to the header keys\n if not self.cookie_headers.get(key):\n cookie = Cookie(key, value)\n cookie[\"path\"] = \"/\"\n self.cookie_headers[key] = self.header_key\n self.headers.add(self.header_key, cookie)\n return super().__setitem__(key, cookie)\n else:\n self[key].value = value", "has_branch": true, "total_branches": 2} {"prompt_id": 483, "project": "sanic", "module": "sanic.cookies", "class": "CookieJar", "method": "__delitem__", "focal_method_txt": " def __delitem__(self, key):\n if key not in self.cookie_headers:\n self[key] = \"\"\n self[key][\"max-age\"] = 0\n else:\n cookie_header = self.cookie_headers[key]\n # remove it from header\n cookies = self.headers.popall(cookie_header)\n for cookie in cookies:\n if cookie.key != key:\n self.headers.add(cookie_header, cookie)\n del self.cookie_headers[key]\n return super().__delitem__(key)", "focal_method_lines": [67, 79], "in_stack": false, "globals": ["DEFAULT_MAX_AGE", "_LegalChars", "_UnescapedChars", "_Translator", "_is_legal_key"], "type_context": "import re\nimport string\nfrom datetime import datetime\nfrom typing import Dict\n\nDEFAULT_MAX_AGE = 0\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + \" ()/<=>?@[]{}\"\n_Translator = {\n n: \"\\\\%03o\" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))\n}\n_is_legal_key = re.compile(\"[%s]+\" % re.escape(_LegalChars)).fullmatch\n\nclass CookieJar(dict):\n\n def __init__(self, headers):\n super().__init__()\n self.headers: Dict[str, str] = headers\n self.cookie_headers: Dict[str, str] = {}\n self.header_key: str = \"Set-Cookie\"\n\n def __delitem__(self, key):\n if key not in self.cookie_headers:\n self[key] = \"\"\n self[key][\"max-age\"] = 0\n else:\n cookie_header = self.cookie_headers[key]\n # remove it from header\n cookies = self.headers.popall(cookie_header)\n for cookie in cookies:\n if cookie.key != key:\n self.headers.add(cookie_header, cookie)\n del self.cookie_headers[key]\n return super().__delitem__(key)", "has_branch": true, "total_branches": 2} {"prompt_id": 484, "project": "sanic", "module": "sanic.cookies", "class": "Cookie", "method": "__setitem__", "focal_method_txt": " def __setitem__(self, key, value):\n if key not in self._keys:\n raise KeyError(\"Unknown cookie property\")\n if value is not False:\n if key.lower() == \"max-age\":\n if not str(value).isdigit():\n raise ValueError(\"Cookie max-age must be an integer\")\n elif key.lower() == \"expires\":\n if not isinstance(value, datetime):\n raise TypeError(\n \"Cookie 'expires' property must be a datetime\"\n )\n return super().__setitem__(key, value)", "focal_method_lines": [107, 119], "in_stack": false, "globals": ["DEFAULT_MAX_AGE", "_LegalChars", "_UnescapedChars", "_Translator", "_is_legal_key"], "type_context": "import re\nimport string\nfrom datetime import datetime\nfrom typing import Dict\n\nDEFAULT_MAX_AGE = 0\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + \" ()/<=>?@[]{}\"\n_Translator = {\n n: \"\\\\%03o\" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))\n}\n_is_legal_key = re.compile(\"[%s]+\" % re.escape(_LegalChars)).fullmatch\n\nclass Cookie(dict):\n\n _keys = {\n \"expires\": \"expires\",\n \"path\": \"Path\",\n \"comment\": \"Comment\",\n \"domain\": \"Domain\",\n \"max-age\": \"Max-Age\",\n \"secure\": \"Secure\",\n \"httponly\": \"HttpOnly\",\n \"version\": \"Version\",\n \"samesite\": \"SameSite\",\n }\n\n _flags = {\"secure\", \"httponly\"}\n\n def __init__(self, key, value):\n if key in self._keys:\n raise KeyError(\"Cookie name is a reserved word\")\n if not _is_legal_key(key):\n raise KeyError(\"Cookie key contains illegal characters\")\n self.key = key\n self.value = value\n super().__init__()\n\n def __setitem__(self, key, value):\n if key not in self._keys:\n raise KeyError(\"Unknown cookie property\")\n if value is not False:\n if key.lower() == \"max-age\":\n if not str(value).isdigit():\n raise ValueError(\"Cookie max-age must be an integer\")\n elif key.lower() == \"expires\":\n if not isinstance(value, datetime):\n raise TypeError(\n \"Cookie 'expires' property must be a datetime\"\n )\n return super().__setitem__(key, value)", "has_branch": true, "total_branches": 2} {"prompt_id": 485, "project": "sanic", "module": "sanic.cookies", "class": "Cookie", "method": "encode", "focal_method_txt": " def encode(self, encoding):\n \"\"\"\n Encode the cookie content in a specific type of encoding instructed\n by the developer. Leverages the :func:`str.encode` method provided\n by python.\n\n This method can be used to encode and embed ``utf-8`` content into\n the cookies.\n\n :param encoding: Encoding to be used with the cookie\n :return: Cookie encoded in a codec of choosing.\n :except: UnicodeEncodeError\n \"\"\"\n return str(self).encode(encoding)", "focal_method_lines": [121, 134], "in_stack": false, "globals": ["DEFAULT_MAX_AGE", "_LegalChars", "_UnescapedChars", "_Translator", "_is_legal_key"], "type_context": "import re\nimport string\nfrom datetime import datetime\nfrom typing import Dict\n\nDEFAULT_MAX_AGE = 0\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + \" ()/<=>?@[]{}\"\n_Translator = {\n n: \"\\\\%03o\" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))\n}\n_is_legal_key = re.compile(\"[%s]+\" % re.escape(_LegalChars)).fullmatch\n\nclass Cookie(dict):\n\n _keys = {\n \"expires\": \"expires\",\n \"path\": \"Path\",\n \"comment\": \"Comment\",\n \"domain\": \"Domain\",\n \"max-age\": \"Max-Age\",\n \"secure\": \"Secure\",\n \"httponly\": \"HttpOnly\",\n \"version\": \"Version\",\n \"samesite\": \"SameSite\",\n }\n\n _flags = {\"secure\", \"httponly\"}\n\n def __init__(self, key, value):\n if key in self._keys:\n raise KeyError(\"Cookie name is a reserved word\")\n if not _is_legal_key(key):\n raise KeyError(\"Cookie key contains illegal characters\")\n self.key = key\n self.value = value\n super().__init__()\n\n def encode(self, encoding):\n \"\"\"\n Encode the cookie content in a specific type of encoding instructed\n by the developer. Leverages the :func:`str.encode` method provided\n by python.\n\n This method can be used to encode and embed ``utf-8`` content into\n the cookies.\n\n :param encoding: Encoding to be used with the cookie\n :return: Cookie encoded in a codec of choosing.\n :except: UnicodeEncodeError\n \"\"\"\n return str(self).encode(encoding)", "has_branch": false, "total_branches": 0} {"prompt_id": 486, "project": "sanic", "module": "sanic.cookies", "class": "Cookie", "method": "__str__", "focal_method_txt": " def __str__(self):\n \"\"\"Format as a Set-Cookie header value.\"\"\"\n output = [\"%s=%s\" % (self.key, _quote(self.value))]\n for key, value in self.items():\n if key == \"max-age\":\n try:\n output.append(\"%s=%d\" % (self._keys[key], value))\n except TypeError:\n output.append(\"%s=%s\" % (self._keys[key], value))\n elif key == \"expires\":\n output.append(\n \"%s=%s\"\n % (self._keys[key], value.strftime(\"%a, %d-%b-%Y %T GMT\"))\n )\n elif key in self._flags and self[key]:\n output.append(self._keys[key])\n else:\n output.append(\"%s=%s\" % (self._keys[key], value))\n\n return \"; \".join(output)", "focal_method_lines": [136, 155], "in_stack": false, "globals": ["DEFAULT_MAX_AGE", "_LegalChars", "_UnescapedChars", "_Translator", "_is_legal_key"], "type_context": "import re\nimport string\nfrom datetime import datetime\nfrom typing import Dict\n\nDEFAULT_MAX_AGE = 0\n_LegalChars = string.ascii_letters + string.digits + \"!#$%&'*+-.^_`|~:\"\n_UnescapedChars = _LegalChars + \" ()/<=>?@[]{}\"\n_Translator = {\n n: \"\\\\%03o\" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))\n}\n_is_legal_key = re.compile(\"[%s]+\" % re.escape(_LegalChars)).fullmatch\n\nclass Cookie(dict):\n\n _keys = {\n \"expires\": \"expires\",\n \"path\": \"Path\",\n \"comment\": \"Comment\",\n \"domain\": \"Domain\",\n \"max-age\": \"Max-Age\",\n \"secure\": \"Secure\",\n \"httponly\": \"HttpOnly\",\n \"version\": \"Version\",\n \"samesite\": \"SameSite\",\n }\n\n _flags = {\"secure\", \"httponly\"}\n\n def __init__(self, key, value):\n if key in self._keys:\n raise KeyError(\"Cookie name is a reserved word\")\n if not _is_legal_key(key):\n raise KeyError(\"Cookie key contains illegal characters\")\n self.key = key\n self.value = value\n super().__init__()\n\n def __str__(self):\n \"\"\"Format as a Set-Cookie header value.\"\"\"\n output = [\"%s=%s\" % (self.key, _quote(self.value))]\n for key, value in self.items():\n if key == \"max-age\":\n try:\n output.append(\"%s=%d\" % (self._keys[key], value))\n except TypeError:\n output.append(\"%s=%s\" % (self._keys[key], value))\n elif key == \"expires\":\n output.append(\n \"%s=%s\"\n % (self._keys[key], value.strftime(\"%a, %d-%b-%Y %T GMT\"))\n )\n elif key in self._flags and self[key]:\n output.append(self._keys[key])\n else:\n output.append(\"%s=%s\" % (self._keys[key], value))\n\n return \"; \".join(output)", "has_branch": true, "total_branches": 2} {"prompt_id": 487, "project": "sanic", "module": "sanic.exceptions", "class": "", "method": "add_status_code", "focal_method_txt": "def add_status_code(code, quiet=None):\n \"\"\"\n Decorator used for adding exceptions to :class:`SanicException`.\n \"\"\"\n\n def class_decorator(cls):\n cls.status_code = code\n if quiet or quiet is None and code != 500:\n cls.quiet = True\n _sanic_exceptions[code] = cls\n return cls\n\n return class_decorator", "focal_method_lines": [8, 20], "in_stack": false, "globals": ["_sanic_exceptions"], "type_context": "from typing import Optional, Union\nfrom sanic.helpers import STATUS_CODES\n\n_sanic_exceptions = {}\n\nclass SanicException(Exception):\n\n def __init__(self, message, status_code=None, quiet=None):\n super().__init__(message)\n\n if status_code is not None:\n self.status_code = status_code\n\n # quiet=None/False/True with None meaning choose by status\n if quiet or quiet is None and status_code not in (None, 500):\n self.quiet = True\n\ndef add_status_code(code, quiet=None):\n \"\"\"\n Decorator used for adding exceptions to :class:`SanicException`.\n \"\"\"\n\n def class_decorator(cls):\n cls.status_code = code\n if quiet or quiet is None and code != 500:\n cls.quiet = True\n _sanic_exceptions[code] = cls\n return cls\n\n return class_decorator", "has_branch": true, "total_branches": 2} {"prompt_id": 488, "project": "sanic", "module": "sanic.exceptions", "class": "", "method": "abort", "focal_method_txt": "def abort(status_code: int, message: Optional[Union[str, bytes]] = None):\n \"\"\"\n Raise an exception based on SanicException. Returns the HTTP response\n message appropriate for the given status code, unless provided.\n\n STATUS_CODES from sanic.helpers for the given status code.\n\n :param status_code: The HTTP status code to return.\n :param message: The HTTP response body. Defaults to the messages in\n \"\"\"\n if message is None:\n msg: bytes = STATUS_CODES[status_code]\n # These are stored as bytes in the STATUS_CODES dict\n message = msg.decode(\"utf8\")\n sanic_exception = _sanic_exceptions.get(status_code, SanicException)\n raise sanic_exception(message=message, status_code=status_code)", "focal_method_lines": [233, 248], "in_stack": false, "globals": ["_sanic_exceptions"], "type_context": "from typing import Optional, Union\nfrom sanic.helpers import STATUS_CODES\n\n_sanic_exceptions = {}\n\nclass SanicException(Exception):\n\n def __init__(self, message, status_code=None, quiet=None):\n super().__init__(message)\n\n if status_code is not None:\n self.status_code = status_code\n\n # quiet=None/False/True with None meaning choose by status\n if quiet or quiet is None and status_code not in (None, 500):\n self.quiet = True\n\ndef abort(status_code: int, message: Optional[Union[str, bytes]] = None):\n \"\"\"\n Raise an exception based on SanicException. Returns the HTTP response\n message appropriate for the given status code, unless provided.\n\n STATUS_CODES from sanic.helpers for the given status code.\n\n :param status_code: The HTTP status code to return.\n :param message: The HTTP response body. Defaults to the messages in\n \"\"\"\n if message is None:\n msg: bytes = STATUS_CODES[status_code]\n # These are stored as bytes in the STATUS_CODES dict\n message = msg.decode(\"utf8\")\n sanic_exception = _sanic_exceptions.get(status_code, SanicException)\n raise sanic_exception(message=message, status_code=status_code)", "has_branch": true, "total_branches": 2} {"prompt_id": 489, "project": "sanic", "module": "sanic.headers", "class": "", "method": "parse_content_header", "focal_method_txt": "def parse_content_header(value: str) -> Tuple[str, Options]:\n \"\"\"Parse content-type and content-disposition header values.\n\n E.g. 'form-data; name=upload; filename=\\\"file.txt\\\"' to\n ('form-data', {'name': 'upload', 'filename': 'file.txt'})\n\n Mostly identical to cgi.parse_header and werkzeug.parse_options_header\n but runs faster and handles special characters better. Unescapes quotes.\n \"\"\"\n value = _firefox_quote_escape.sub(\"%22\", value)\n pos = value.find(\";\")\n if pos == -1:\n options: Dict[str, Union[int, str]] = {}\n else:\n options = {\n m.group(1).lower(): m.group(2) or m.group(3).replace(\"%22\", '\"')\n for m in _param.finditer(value[pos:])\n }\n value = value[:pos]\n return value.strip().lower(), options", "focal_method_lines": [32, 51], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef parse_content_header(value: str) -> Tuple[str, Options]:\n \"\"\"Parse content-type and content-disposition header values.\n\n E.g. 'form-data; name=upload; filename=\\\"file.txt\\\"' to\n ('form-data', {'name': 'upload', 'filename': 'file.txt'})\n\n Mostly identical to cgi.parse_header and werkzeug.parse_options_header\n but runs faster and handles special characters better. Unescapes quotes.\n \"\"\"\n value = _firefox_quote_escape.sub(\"%22\", value)\n pos = value.find(\";\")\n if pos == -1:\n options: Dict[str, Union[int, str]] = {}\n else:\n options = {\n m.group(1).lower(): m.group(2) or m.group(3).replace(\"%22\", '\"')\n for m in _param.finditer(value[pos:])\n }\n value = value[:pos]\n return value.strip().lower(), options", "has_branch": true, "total_branches": 2} {"prompt_id": 490, "project": "sanic", "module": "sanic.headers", "class": "", "method": "parse_forwarded", "focal_method_txt": "def parse_forwarded(headers, config) -> Optional[Options]:\n \"\"\"Parse RFC 7239 Forwarded headers.\n The value of `by` or `secret` must match `config.FORWARDED_SECRET`\n :return: dict with keys and values, or None if nothing matched\n \"\"\"\n header = headers.getall(\"forwarded\", None)\n secret = config.FORWARDED_SECRET\n if header is None or not secret:\n return None\n header = \",\".join(header) # Join multiple header lines\n if secret not in header:\n return None\n # Loop over = elements from right to left\n sep = pos = None\n options: List[Tuple[str, str]] = []\n found = False\n for m in _rparam.finditer(header[::-1]):\n # Start of new element? (on parser skips and non-semicolon right sep)\n if m.start() != pos or sep != \";\":\n # Was the previous element (from right) what we wanted?\n if found:\n break\n # Clear values and parse as new element\n del options[:]\n pos = m.end()\n val_token, val_quoted, key, sep = m.groups()\n key = key.lower()[::-1]\n val = (val_token or val_quoted.replace('\"\\\\', '\"'))[::-1]\n options.append((key, val))\n if key in (\"secret\", \"by\") and val == secret:\n found = True\n # Check if we would return on next round, to avoid useless parse\n if found and sep != \";\":\n break\n # If secret was found, return the matching options in left-to-right order\n return fwd_normalize(reversed(options)) if found else None", "focal_method_lines": [62, 97], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef parse_forwarded(headers, config) -> Optional[Options]:\n \"\"\"Parse RFC 7239 Forwarded headers.\n The value of `by` or `secret` must match `config.FORWARDED_SECRET`\n :return: dict with keys and values, or None if nothing matched\n \"\"\"\n header = headers.getall(\"forwarded\", None)\n secret = config.FORWARDED_SECRET\n if header is None or not secret:\n return None\n header = \",\".join(header) # Join multiple header lines\n if secret not in header:\n return None\n # Loop over = elements from right to left\n sep = pos = None\n options: List[Tuple[str, str]] = []\n found = False\n for m in _rparam.finditer(header[::-1]):\n # Start of new element? (on parser skips and non-semicolon right sep)\n if m.start() != pos or sep != \";\":\n # Was the previous element (from right) what we wanted?\n if found:\n break\n # Clear values and parse as new element\n del options[:]\n pos = m.end()\n val_token, val_quoted, key, sep = m.groups()\n key = key.lower()[::-1]\n val = (val_token or val_quoted.replace('\"\\\\', '\"'))[::-1]\n options.append((key, val))\n if key in (\"secret\", \"by\") and val == secret:\n found = True\n # Check if we would return on next round, to avoid useless parse\n if found and sep != \";\":\n break\n # If secret was found, return the matching options in left-to-right order\n return fwd_normalize(reversed(options)) if found else None", "has_branch": true, "total_branches": 2} {"prompt_id": 491, "project": "sanic", "module": "sanic.headers", "class": "", "method": "parse_xforwarded", "focal_method_txt": "def parse_xforwarded(headers, config) -> Optional[Options]:\n \"\"\"Parse traditional proxy headers.\"\"\"\n real_ip_header = config.REAL_IP_HEADER\n proxies_count = config.PROXIES_COUNT\n addr = real_ip_header and headers.get(real_ip_header)\n if not addr and proxies_count:\n assert proxies_count > 0\n try:\n # Combine, split and filter multiple headers' entries\n forwarded_for = headers.getall(config.FORWARDED_FOR_HEADER)\n proxies = [\n p\n for p in (\n p.strip() for h in forwarded_for for p in h.split(\",\")\n )\n if p\n ]\n addr = proxies[-proxies_count]\n except (KeyError, IndexError):\n pass\n # No processing of other headers if no address is found\n if not addr:\n return None\n\n def options():\n yield \"for\", addr\n for key, header in (\n (\"proto\", \"x-scheme\"),\n (\"proto\", \"x-forwarded-proto\"), # Overrides X-Scheme if present\n (\"host\", \"x-forwarded-host\"),\n (\"port\", \"x-forwarded-port\"),\n (\"path\", \"x-forwarded-path\"),\n ):\n yield key, headers.get(header)\n\n return fwd_normalize(options())", "focal_method_lines": [100, 135], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef parse_xforwarded(headers, config) -> Optional[Options]:\n \"\"\"Parse traditional proxy headers.\"\"\"\n real_ip_header = config.REAL_IP_HEADER\n proxies_count = config.PROXIES_COUNT\n addr = real_ip_header and headers.get(real_ip_header)\n if not addr and proxies_count:\n assert proxies_count > 0\n try:\n # Combine, split and filter multiple headers' entries\n forwarded_for = headers.getall(config.FORWARDED_FOR_HEADER)\n proxies = [\n p\n for p in (\n p.strip() for h in forwarded_for for p in h.split(\",\")\n )\n if p\n ]\n addr = proxies[-proxies_count]\n except (KeyError, IndexError):\n pass\n # No processing of other headers if no address is found\n if not addr:\n return None\n\n def options():\n yield \"for\", addr\n for key, header in (\n (\"proto\", \"x-scheme\"),\n (\"proto\", \"x-forwarded-proto\"), # Overrides X-Scheme if present\n (\"host\", \"x-forwarded-host\"),\n (\"port\", \"x-forwarded-port\"),\n (\"path\", \"x-forwarded-path\"),\n ):\n yield key, headers.get(header)\n\n return fwd_normalize(options())", "has_branch": true, "total_branches": 2} {"prompt_id": 492, "project": "sanic", "module": "sanic.headers", "class": "", "method": "fwd_normalize", "focal_method_txt": "def fwd_normalize(fwd: OptionsIterable) -> Options:\n \"\"\"Normalize and convert values extracted from forwarded headers.\"\"\"\n ret: Dict[str, Union[int, str]] = {}\n for key, val in fwd:\n if val is not None:\n try:\n if key in (\"by\", \"for\"):\n ret[key] = fwd_normalize_address(val)\n elif key in (\"host\", \"proto\"):\n ret[key] = val.lower()\n elif key == \"port\":\n ret[key] = int(val)\n elif key == \"path\":\n ret[key] = unquote(val)\n else:\n ret[key] = val\n except ValueError:\n pass\n return ret", "focal_method_lines": [138, 156], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef fwd_normalize(fwd: OptionsIterable) -> Options:\n \"\"\"Normalize and convert values extracted from forwarded headers.\"\"\"\n ret: Dict[str, Union[int, str]] = {}\n for key, val in fwd:\n if val is not None:\n try:\n if key in (\"by\", \"for\"):\n ret[key] = fwd_normalize_address(val)\n elif key in (\"host\", \"proto\"):\n ret[key] = val.lower()\n elif key == \"port\":\n ret[key] = int(val)\n elif key == \"path\":\n ret[key] = unquote(val)\n else:\n ret[key] = val\n except ValueError:\n pass\n return ret", "has_branch": true, "total_branches": 2} {"prompt_id": 493, "project": "sanic", "module": "sanic.headers", "class": "", "method": "fwd_normalize_address", "focal_method_txt": "def fwd_normalize_address(addr: str) -> str:\n \"\"\"Normalize address fields of proxy headers.\"\"\"\n if addr == \"unknown\":\n raise ValueError() # omit unknown value identifiers\n if addr.startswith(\"_\"):\n return addr # do not lower-case obfuscated strings\n if _ipv6_re.fullmatch(addr):\n addr = f\"[{addr}]\" # bracket IPv6\n return addr.lower()", "focal_method_lines": [159, 167], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef fwd_normalize_address(addr: str) -> str:\n \"\"\"Normalize address fields of proxy headers.\"\"\"\n if addr == \"unknown\":\n raise ValueError() # omit unknown value identifiers\n if addr.startswith(\"_\"):\n return addr # do not lower-case obfuscated strings\n if _ipv6_re.fullmatch(addr):\n addr = f\"[{addr}]\" # bracket IPv6\n return addr.lower()", "has_branch": true, "total_branches": 2} {"prompt_id": 494, "project": "sanic", "module": "sanic.headers", "class": "", "method": "parse_host", "focal_method_txt": "def parse_host(host: str) -> Tuple[Optional[str], Optional[int]]:\n \"\"\"Split host:port into hostname and port.\n :return: None in place of missing elements\n \"\"\"\n m = _host_re.fullmatch(host)\n if not m:\n return None, None\n host, port = m.groups()\n return host.lower(), int(port) if port is not None else None", "focal_method_lines": [170, 178], "in_stack": false, "globals": ["HeaderIterable", "HeaderBytesIterable", "Options", "OptionsIterable", "_token", "_quoted", "_param", "_firefox_quote_escape", "_ipv6", "_ipv6_re", "_host_re", "_rparam", "_HTTP1_STATUSLINES"], "type_context": "import re\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom urllib.parse import unquote\nfrom sanic.helpers import STATUS_CODES\n\nHeaderIterable = Iterable[Tuple[str, Any]]\nHeaderBytesIterable = Iterable[Tuple[bytes, bytes]]\nOptions = Dict[str, Union[int, str]]\nOptionsIterable = Iterable[Tuple[str, str]]\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_token, _quoted = r\"([\\w!#$%&'*+\\-.^_`|~]+)\", r'\"([^\"]*)\"'\n_param = re.compile(fr\";\\s*{_token}=(?:{_token}|{_quoted})\", re.ASCII)\n_firefox_quote_escape = re.compile(r'\\\\\"(?!; |\\s*$)')\n_ipv6 = \"(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}\"\n_ipv6_re = re.compile(_ipv6)\n_host_re = re.compile(\n r\"((?:\\[\" + _ipv6 + r\"\\])|[a-zA-Z0-9.\\-]{1,253})(?::(\\d{1,5}))?\"\n)\n_rparam = re.compile(f\"(?:{_token}|{_quoted})={_token}\\\\s*($|[;,])\", re.ASCII)\n_HTTP1_STATUSLINES = [\n b\"HTTP/1.1 %d %b\\r\\n\" % (status, STATUS_CODES.get(status, b\"UNKNOWN\"))\n for status in range(1000)\n]\n\ndef parse_host(host: str) -> Tuple[Optional[str], Optional[int]]:\n \"\"\"Split host:port into hostname and port.\n :return: None in place of missing elements\n \"\"\"\n m = _host_re.fullmatch(host)\n if not m:\n return None, None\n host, port = m.groups()\n return host.lower(), int(port) if port is not None else None", "has_branch": true, "total_branches": 2} {"prompt_id": 495, "project": "sanic", "module": "sanic.helpers", "class": "", "method": "has_message_body", "focal_method_txt": "def has_message_body(status):\n \"\"\"\n According to the following RFC message body and length SHOULD NOT\n be included in responses status 1XX, 204 and 304.\n https://tools.ietf.org/html/rfc2616#section-4.4\n https://tools.ietf.org/html/rfc2616#section-4.3\n \"\"\"\n return status not in (204, 304) and not (100 <= status < 200)", "focal_method_lines": [102, 109], "in_stack": false, "globals": ["STATUS_CODES", "_ENTITY_HEADERS", "_HOP_BY_HOP_HEADERS"], "type_context": "from importlib import import_module\nfrom inspect import ismodule\nfrom typing import Dict\n\nSTATUS_CODES: Dict[int, bytes] = {\n 100: b\"Continue\",\n 101: b\"Switching Protocols\",\n 102: b\"Processing\",\n 103: b\"Early Hints\",\n 200: b\"OK\",\n 201: b\"Created\",\n 202: b\"Accepted\",\n 203: b\"Non-Authoritative Information\",\n 204: b\"No Content\",\n 205: b\"Reset Content\",\n 206: b\"Partial Content\",\n 207: b\"Multi-Status\",\n 208: b\"Already Reported\",\n 226: b\"IM Used\",\n 300: b\"Multiple Choices\",\n 301: b\"Moved Permanently\",\n 302: b\"Found\",\n 303: b\"See Other\",\n 304: b\"Not Modified\",\n 305: b\"Use Proxy\",\n 307: b\"Temporary Redirect\",\n 308: b\"Permanent Redirect\",\n 400: b\"Bad Request\",\n 401: b\"Unauthorized\",\n 402: b\"Payment Required\",\n 403: b\"Forbidden\",\n 404: b\"Not Found\",\n 405: b\"Method Not Allowed\",\n 406: b\"Not Acceptable\",\n 407: b\"Proxy Authentication Required\",\n 408: b\"Request Timeout\",\n 409: b\"Conflict\",\n 410: b\"Gone\",\n 411: b\"Length Required\",\n 412: b\"Precondition Failed\",\n 413: b\"Request Entity Too Large\",\n 414: b\"Request-URI Too Long\",\n 415: b\"Unsupported Media Type\",\n 416: b\"Requested Range Not Satisfiable\",\n 417: b\"Expectation Failed\",\n 418: b\"I'm a teapot\",\n 422: b\"Unprocessable Entity\",\n 423: b\"Locked\",\n 424: b\"Failed Dependency\",\n 426: b\"Upgrade Required\",\n 428: b\"Precondition Required\",\n 429: b\"Too Many Requests\",\n 431: b\"Request Header Fields Too Large\",\n 451: b\"Unavailable For Legal Reasons\",\n 500: b\"Internal Server Error\",\n 501: b\"Not Implemented\",\n 502: b\"Bad Gateway\",\n 503: b\"Service Unavailable\",\n 504: b\"Gateway Timeout\",\n 505: b\"HTTP Version Not Supported\",\n 506: b\"Variant Also Negotiates\",\n 507: b\"Insufficient Storage\",\n 508: b\"Loop Detected\",\n 510: b\"Not Extended\",\n 511: b\"Network Authentication Required\",\n}\n_ENTITY_HEADERS = frozenset(\n [\n \"allow\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-md5\",\n \"content-range\",\n \"content-type\",\n \"expires\",\n \"last-modified\",\n \"extension-header\",\n ]\n)\n_HOP_BY_HOP_HEADERS = frozenset(\n [\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n ]\n)\n\ndef has_message_body(status):\n \"\"\"\n According to the following RFC message body and length SHOULD NOT\n be included in responses status 1XX, 204 and 304.\n https://tools.ietf.org/html/rfc2616#section-4.4\n https://tools.ietf.org/html/rfc2616#section-4.3\n \"\"\"\n return status not in (204, 304) and not (100 <= status < 200)", "has_branch": false, "total_branches": 0} {"prompt_id": 496, "project": "sanic", "module": "sanic.helpers", "class": "", "method": "remove_entity_headers", "focal_method_txt": "def remove_entity_headers(headers, allowed=(\"content-location\", \"expires\")):\n \"\"\"\n Removes all the entity headers present in the headers given.\n According to RFC 2616 Section 10.3.5,\n Content-Location and Expires are allowed as for the\n \"strong cache validator\".\n https://tools.ietf.org/html/rfc2616#section-10.3.5\n\n returns the headers without the entity headers\n \"\"\"\n allowed = set([h.lower() for h in allowed])\n headers = {\n header: value\n for header, value in headers.items()\n if not is_entity_header(header) or header.lower() in allowed\n }\n return headers", "focal_method_lines": [122, 138], "in_stack": false, "globals": ["STATUS_CODES", "_ENTITY_HEADERS", "_HOP_BY_HOP_HEADERS"], "type_context": "from importlib import import_module\nfrom inspect import ismodule\nfrom typing import Dict\n\nSTATUS_CODES: Dict[int, bytes] = {\n 100: b\"Continue\",\n 101: b\"Switching Protocols\",\n 102: b\"Processing\",\n 103: b\"Early Hints\",\n 200: b\"OK\",\n 201: b\"Created\",\n 202: b\"Accepted\",\n 203: b\"Non-Authoritative Information\",\n 204: b\"No Content\",\n 205: b\"Reset Content\",\n 206: b\"Partial Content\",\n 207: b\"Multi-Status\",\n 208: b\"Already Reported\",\n 226: b\"IM Used\",\n 300: b\"Multiple Choices\",\n 301: b\"Moved Permanently\",\n 302: b\"Found\",\n 303: b\"See Other\",\n 304: b\"Not Modified\",\n 305: b\"Use Proxy\",\n 307: b\"Temporary Redirect\",\n 308: b\"Permanent Redirect\",\n 400: b\"Bad Request\",\n 401: b\"Unauthorized\",\n 402: b\"Payment Required\",\n 403: b\"Forbidden\",\n 404: b\"Not Found\",\n 405: b\"Method Not Allowed\",\n 406: b\"Not Acceptable\",\n 407: b\"Proxy Authentication Required\",\n 408: b\"Request Timeout\",\n 409: b\"Conflict\",\n 410: b\"Gone\",\n 411: b\"Length Required\",\n 412: b\"Precondition Failed\",\n 413: b\"Request Entity Too Large\",\n 414: b\"Request-URI Too Long\",\n 415: b\"Unsupported Media Type\",\n 416: b\"Requested Range Not Satisfiable\",\n 417: b\"Expectation Failed\",\n 418: b\"I'm a teapot\",\n 422: b\"Unprocessable Entity\",\n 423: b\"Locked\",\n 424: b\"Failed Dependency\",\n 426: b\"Upgrade Required\",\n 428: b\"Precondition Required\",\n 429: b\"Too Many Requests\",\n 431: b\"Request Header Fields Too Large\",\n 451: b\"Unavailable For Legal Reasons\",\n 500: b\"Internal Server Error\",\n 501: b\"Not Implemented\",\n 502: b\"Bad Gateway\",\n 503: b\"Service Unavailable\",\n 504: b\"Gateway Timeout\",\n 505: b\"HTTP Version Not Supported\",\n 506: b\"Variant Also Negotiates\",\n 507: b\"Insufficient Storage\",\n 508: b\"Loop Detected\",\n 510: b\"Not Extended\",\n 511: b\"Network Authentication Required\",\n}\n_ENTITY_HEADERS = frozenset(\n [\n \"allow\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-md5\",\n \"content-range\",\n \"content-type\",\n \"expires\",\n \"last-modified\",\n \"extension-header\",\n ]\n)\n_HOP_BY_HOP_HEADERS = frozenset(\n [\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n ]\n)\n\ndef remove_entity_headers(headers, allowed=(\"content-location\", \"expires\")):\n \"\"\"\n Removes all the entity headers present in the headers given.\n According to RFC 2616 Section 10.3.5,\n Content-Location and Expires are allowed as for the\n \"strong cache validator\".\n https://tools.ietf.org/html/rfc2616#section-10.3.5\n\n returns the headers without the entity headers\n \"\"\"\n allowed = set([h.lower() for h in allowed])\n headers = {\n header: value\n for header, value in headers.items()\n if not is_entity_header(header) or header.lower() in allowed\n }\n return headers", "has_branch": false, "total_branches": 0} {"prompt_id": 497, "project": "sanic", "module": "sanic.helpers", "class": "", "method": "import_string", "focal_method_txt": "def import_string(module_name, package=None):\n \"\"\"\n import a module or class by string path.\n\n :module_name: str with path of module or path to import and\n instanciate a class\n :returns: a module object or one instance from class if\n module_name is a valid path to class\n\n \"\"\"\n module, klass = module_name.rsplit(\".\", 1)\n module = import_module(module, package=package)\n obj = getattr(module, klass)\n if ismodule(obj):\n return obj\n return obj()", "focal_method_lines": [141, 156], "in_stack": false, "globals": ["STATUS_CODES", "_ENTITY_HEADERS", "_HOP_BY_HOP_HEADERS"], "type_context": "from importlib import import_module\nfrom inspect import ismodule\nfrom typing import Dict\n\nSTATUS_CODES: Dict[int, bytes] = {\n 100: b\"Continue\",\n 101: b\"Switching Protocols\",\n 102: b\"Processing\",\n 103: b\"Early Hints\",\n 200: b\"OK\",\n 201: b\"Created\",\n 202: b\"Accepted\",\n 203: b\"Non-Authoritative Information\",\n 204: b\"No Content\",\n 205: b\"Reset Content\",\n 206: b\"Partial Content\",\n 207: b\"Multi-Status\",\n 208: b\"Already Reported\",\n 226: b\"IM Used\",\n 300: b\"Multiple Choices\",\n 301: b\"Moved Permanently\",\n 302: b\"Found\",\n 303: b\"See Other\",\n 304: b\"Not Modified\",\n 305: b\"Use Proxy\",\n 307: b\"Temporary Redirect\",\n 308: b\"Permanent Redirect\",\n 400: b\"Bad Request\",\n 401: b\"Unauthorized\",\n 402: b\"Payment Required\",\n 403: b\"Forbidden\",\n 404: b\"Not Found\",\n 405: b\"Method Not Allowed\",\n 406: b\"Not Acceptable\",\n 407: b\"Proxy Authentication Required\",\n 408: b\"Request Timeout\",\n 409: b\"Conflict\",\n 410: b\"Gone\",\n 411: b\"Length Required\",\n 412: b\"Precondition Failed\",\n 413: b\"Request Entity Too Large\",\n 414: b\"Request-URI Too Long\",\n 415: b\"Unsupported Media Type\",\n 416: b\"Requested Range Not Satisfiable\",\n 417: b\"Expectation Failed\",\n 418: b\"I'm a teapot\",\n 422: b\"Unprocessable Entity\",\n 423: b\"Locked\",\n 424: b\"Failed Dependency\",\n 426: b\"Upgrade Required\",\n 428: b\"Precondition Required\",\n 429: b\"Too Many Requests\",\n 431: b\"Request Header Fields Too Large\",\n 451: b\"Unavailable For Legal Reasons\",\n 500: b\"Internal Server Error\",\n 501: b\"Not Implemented\",\n 502: b\"Bad Gateway\",\n 503: b\"Service Unavailable\",\n 504: b\"Gateway Timeout\",\n 505: b\"HTTP Version Not Supported\",\n 506: b\"Variant Also Negotiates\",\n 507: b\"Insufficient Storage\",\n 508: b\"Loop Detected\",\n 510: b\"Not Extended\",\n 511: b\"Network Authentication Required\",\n}\n_ENTITY_HEADERS = frozenset(\n [\n \"allow\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-md5\",\n \"content-range\",\n \"content-type\",\n \"expires\",\n \"last-modified\",\n \"extension-header\",\n ]\n)\n_HOP_BY_HOP_HEADERS = frozenset(\n [\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n ]\n)\n\ndef import_string(module_name, package=None):\n \"\"\"\n import a module or class by string path.\n\n :module_name: str with path of module or path to import and\n instanciate a class\n :returns: a module object or one instance from class if\n module_name is a valid path to class\n\n \"\"\"\n module, klass = module_name.rsplit(\".\", 1)\n module = import_module(module, package=package)\n obj = getattr(module, klass)\n if ismodule(obj):\n return obj\n return obj()", "has_branch": true, "total_branches": 2} {"prompt_id": 498, "project": "sanic", "module": "sanic.mixins.exceptions", "class": "ExceptionMixin", "method": "exception", "focal_method_txt": " def exception(self, *exceptions, apply=True):\n \"\"\"\n This method enables the process of creating a global exception\n handler for the current blueprint under question.\n\n :param args: List of Python exceptions to be caught by the handler\n :param kwargs: Additional optional arguments to be passed to the\n exception handler\n\n :return a decorated method to handle global exceptions for any\n route registered under this blueprint.\n \"\"\"\n\n def decorator(handler):\n nonlocal apply\n nonlocal exceptions\n\n if isinstance(exceptions[0], list):\n exceptions = tuple(*exceptions)\n\n future_exception = FutureException(handler, exceptions)\n self._future_exceptions.add(future_exception)\n if apply:\n self._apply_exception_handler(future_exception)\n return handler\n\n return decorator", "focal_method_lines": [12, 38], "in_stack": false, "globals": [], "type_context": "from typing import Set\nfrom sanic.models.futures import FutureException\n\n\n\nclass ExceptionMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_exceptions: Set[FutureException] = set()\n\n def exception(self, *exceptions, apply=True):\n \"\"\"\n This method enables the process of creating a global exception\n handler for the current blueprint under question.\n\n :param args: List of Python exceptions to be caught by the handler\n :param kwargs: Additional optional arguments to be passed to the\n exception handler\n\n :return a decorated method to handle global exceptions for any\n route registered under this blueprint.\n \"\"\"\n\n def decorator(handler):\n nonlocal apply\n nonlocal exceptions\n\n if isinstance(exceptions[0], list):\n exceptions = tuple(*exceptions)\n\n future_exception = FutureException(handler, exceptions)\n self._future_exceptions.add(future_exception)\n if apply:\n self._apply_exception_handler(future_exception)\n return handler\n\n return decorator", "has_branch": true, "total_branches": 2} {"prompt_id": 499, "project": "sanic", "module": "sanic.mixins.middleware", "class": "MiddlewareMixin", "method": "middleware", "focal_method_txt": " def middleware(\n self, middleware_or_request, attach_to=\"request\", apply=True\n ):\n \"\"\"\n Decorate and register middleware to be called before a request.\n Can either be called as *@app.middleware* or\n *@app.middleware('request')*\n\n `See user guide re: middleware\n `__\n\n :param: middleware_or_request: Optional parameter to use for\n identifying which type of middleware is being registered.\n \"\"\"\n\n def register_middleware(middleware, attach_to=\"request\"):\n nonlocal apply\n\n future_middleware = FutureMiddleware(middleware, attach_to)\n self._future_middleware.append(future_middleware)\n if apply:\n self._apply_middleware(future_middleware)\n return middleware\n\n # Detect which way this was called, @middleware or @middleware('AT')\n if callable(middleware_or_request):\n return register_middleware(\n middleware_or_request, attach_to=attach_to\n )\n else:\n return partial(\n register_middleware, attach_to=middleware_or_request\n )", "focal_method_lines": [13, 43], "in_stack": false, "globals": [], "type_context": "from functools import partial\nfrom typing import List\nfrom sanic.models.futures import FutureMiddleware\n\n\n\nclass MiddlewareMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_middleware: List[FutureMiddleware] = []\n\n def middleware(\n self, middleware_or_request, attach_to=\"request\", apply=True\n ):\n \"\"\"\n Decorate and register middleware to be called before a request.\n Can either be called as *@app.middleware* or\n *@app.middleware('request')*\n\n `See user guide re: middleware\n `__\n\n :param: middleware_or_request: Optional parameter to use for\n identifying which type of middleware is being registered.\n \"\"\"\n\n def register_middleware(middleware, attach_to=\"request\"):\n nonlocal apply\n\n future_middleware = FutureMiddleware(middleware, attach_to)\n self._future_middleware.append(future_middleware)\n if apply:\n self._apply_middleware(future_middleware)\n return middleware\n\n # Detect which way this was called, @middleware or @middleware('AT')\n if callable(middleware_or_request):\n return register_middleware(\n middleware_or_request, attach_to=attach_to\n )\n else:\n return partial(\n register_middleware, attach_to=middleware_or_request\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 500, "project": "sanic", "module": "sanic.mixins.middleware", "class": "MiddlewareMixin", "method": "on_request", "focal_method_txt": " def on_request(self, middleware=None):\n if callable(middleware):\n return self.middleware(middleware, \"request\")\n else:\n return partial(self.middleware, attach_to=\"request\")", "focal_method_lines": [47, 51], "in_stack": false, "globals": [], "type_context": "from functools import partial\nfrom typing import List\nfrom sanic.models.futures import FutureMiddleware\n\n\n\nclass MiddlewareMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_middleware: List[FutureMiddleware] = []\n\n def on_request(self, middleware=None):\n if callable(middleware):\n return self.middleware(middleware, \"request\")\n else:\n return partial(self.middleware, attach_to=\"request\")", "has_branch": true, "total_branches": 2} {"prompt_id": 501, "project": "sanic", "module": "sanic.mixins.middleware", "class": "MiddlewareMixin", "method": "on_response", "focal_method_txt": " def on_response(self, middleware=None):\n if callable(middleware):\n return self.middleware(middleware, \"response\")\n else:\n return partial(self.middleware, attach_to=\"response\")", "focal_method_lines": [53, 57], "in_stack": false, "globals": [], "type_context": "from functools import partial\nfrom typing import List\nfrom sanic.models.futures import FutureMiddleware\n\n\n\nclass MiddlewareMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_middleware: List[FutureMiddleware] = []\n\n def on_response(self, middleware=None):\n if callable(middleware):\n return self.middleware(middleware, \"response\")\n else:\n return partial(self.middleware, attach_to=\"response\")", "has_branch": true, "total_branches": 2} {"prompt_id": 502, "project": "sanic", "module": "sanic.mixins.routes", "class": "RouteMixin", "method": "route", "focal_method_txt": " def route(\n self,\n uri: str,\n methods: Optional[Iterable[str]] = None,\n host: Optional[str] = None,\n strict_slashes: Optional[bool] = None,\n stream: bool = False,\n version: Optional[int] = None,\n name: Optional[str] = None,\n ignore_body: bool = False,\n apply: bool = True,\n subprotocols: Optional[List[str]] = None,\n websocket: bool = False,\n unquote: bool = False,\n static: bool = False,\n ):\n \"\"\"\n Decorate a function to be registered as a route\n\n :param uri: path of the URL\n :param methods: list or tuple of methods allowed\n :param host: the host, if required\n :param strict_slashes: whether to apply strict slashes to the route\n :param stream: whether to allow the request to stream its body\n :param version: route specific versioning\n :param name: user defined route name for url_for\n :param ignore_body: whether the handler should ignore request\n body (eg. GET requests)\n :return: tuple of routes, decorated function\n \"\"\"\n\n # Fix case where the user did not prefix the URL with a /\n # and will probably get confused as to why it's not working\n if not uri.startswith(\"/\") and (uri or hasattr(self, \"router\")):\n uri = \"/\" + uri\n\n if strict_slashes is None:\n strict_slashes = self.strict_slashes\n\n if not methods and not websocket:\n methods = frozenset({\"GET\"})\n\n def decorator(handler):\n nonlocal uri\n nonlocal methods\n nonlocal host\n nonlocal strict_slashes\n nonlocal stream\n nonlocal version\n nonlocal name\n nonlocal ignore_body\n nonlocal subprotocols\n nonlocal websocket\n nonlocal static\n\n if isinstance(handler, tuple):\n # if a handler fn is already wrapped in a route, the handler\n # variable will be a tuple of (existing routes, handler fn)\n _, handler = handler\n\n name = self._generate_name(name, handler)\n\n if isinstance(host, str):\n host = frozenset([host])\n elif host and not isinstance(host, frozenset):\n try:\n host = frozenset(host)\n except TypeError:\n raise ValueError(\n \"Expected either string or Iterable of host strings, \"\n \"not %s\" % host\n )\n\n if isinstance(subprotocols, (list, tuple, set)):\n subprotocols = frozenset(subprotocols)\n\n route = FutureRoute(\n handler,\n uri,\n None if websocket else frozenset([x.upper() for x in methods]),\n host,\n strict_slashes,\n stream,\n version,\n name,\n ignore_body,\n websocket,\n subprotocols,\n unquote,\n static,\n )\n\n self._future_routes.add(route)\n\n args = list(signature(handler).parameters.keys())\n if websocket and len(args) < 2:\n handler_name = handler.__name__\n\n raise ValueError(\n f\"Required parameter `request` and/or `ws` missing \"\n f\"in the {handler_name}() route?\"\n )\n elif not args:\n handler_name = handler.__name__\n\n raise ValueError(\n f\"Required parameter `request` missing \"\n f\"in the {handler_name}() route?\"\n )\n\n if not websocket and stream:\n handler.is_stream = stream\n\n if apply:\n self._apply_route(route)\n\n return route, handler\n\n return decorator", "focal_method_lines": [40, 158], "in_stack": false, "globals": [], "type_context": "from functools import partial, wraps\nfrom inspect import signature\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom re import sub\nfrom time import gmtime, strftime\nfrom typing import Iterable, List, Optional, Set, Union\nfrom urllib.parse import unquote\nfrom sanic_routing.route import Route\nfrom sanic.compat import stat_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS\nfrom sanic.exceptions import (\n ContentRangeError,\n FileNotFound,\n HeaderNotFound,\n InvalidUsage,\n)\nfrom sanic.handlers import ContentRangeHandler\nfrom sanic.log import error_logger\nfrom sanic.models.futures import FutureRoute, FutureStatic\nfrom sanic.response import HTTPResponse, file, file_stream\nfrom sanic.views import CompositionView\n\n\n\nclass RouteMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_routes: Set[FutureRoute] = set()\n self._future_statics: Set[FutureStatic] = set()\n self.name = \"\"\n self.strict_slashes: Optional[bool] = False\n\n def route(\n self,\n uri: str,\n methods: Optional[Iterable[str]] = None,\n host: Optional[str] = None,\n strict_slashes: Optional[bool] = None,\n stream: bool = False,\n version: Optional[int] = None,\n name: Optional[str] = None,\n ignore_body: bool = False,\n apply: bool = True,\n subprotocols: Optional[List[str]] = None,\n websocket: bool = False,\n unquote: bool = False,\n static: bool = False,\n ):\n \"\"\"\n Decorate a function to be registered as a route\n\n :param uri: path of the URL\n :param methods: list or tuple of methods allowed\n :param host: the host, if required\n :param strict_slashes: whether to apply strict slashes to the route\n :param stream: whether to allow the request to stream its body\n :param version: route specific versioning\n :param name: user defined route name for url_for\n :param ignore_body: whether the handler should ignore request\n body (eg. GET requests)\n :return: tuple of routes, decorated function\n \"\"\"\n\n # Fix case where the user did not prefix the URL with a /\n # and will probably get confused as to why it's not working\n if not uri.startswith(\"/\") and (uri or hasattr(self, \"router\")):\n uri = \"/\" + uri\n\n if strict_slashes is None:\n strict_slashes = self.strict_slashes\n\n if not methods and not websocket:\n methods = frozenset({\"GET\"})\n\n def decorator(handler):\n nonlocal uri\n nonlocal methods\n nonlocal host\n nonlocal strict_slashes\n nonlocal stream\n nonlocal version\n nonlocal name\n nonlocal ignore_body\n nonlocal subprotocols\n nonlocal websocket\n nonlocal static\n\n if isinstance(handler, tuple):\n # if a handler fn is already wrapped in a route, the handler\n # variable will be a tuple of (existing routes, handler fn)\n _, handler = handler\n\n name = self._generate_name(name, handler)\n\n if isinstance(host, str):\n host = frozenset([host])\n elif host and not isinstance(host, frozenset):\n try:\n host = frozenset(host)\n except TypeError:\n raise ValueError(\n \"Expected either string or Iterable of host strings, \"\n \"not %s\" % host\n )\n\n if isinstance(subprotocols, (list, tuple, set)):\n subprotocols = frozenset(subprotocols)\n\n route = FutureRoute(\n handler,\n uri,\n None if websocket else frozenset([x.upper() for x in methods]),\n host,\n strict_slashes,\n stream,\n version,\n name,\n ignore_body,\n websocket,\n subprotocols,\n unquote,\n static,\n )\n\n self._future_routes.add(route)\n\n args = list(signature(handler).parameters.keys())\n if websocket and len(args) < 2:\n handler_name = handler.__name__\n\n raise ValueError(\n f\"Required parameter `request` and/or `ws` missing \"\n f\"in the {handler_name}() route?\"\n )\n elif not args:\n handler_name = handler.__name__\n\n raise ValueError(\n f\"Required parameter `request` missing \"\n f\"in the {handler_name}() route?\"\n )\n\n if not websocket and stream:\n handler.is_stream = stream\n\n if apply:\n self._apply_route(route)\n\n return route, handler\n\n return decorator", "has_branch": true, "total_branches": 2} {"prompt_id": 503, "project": "sanic", "module": "sanic.mixins.routes", "class": "RouteMixin", "method": "add_route", "focal_method_txt": " def add_route(\n self,\n handler,\n uri: str,\n methods: Iterable[str] = frozenset({\"GET\"}),\n host: Optional[str] = None,\n strict_slashes: Optional[bool] = None,\n version: Optional[int] = None,\n name: Optional[str] = None,\n stream: bool = False,\n ):\n \"\"\"A helper method to register class instance or\n functions as a handler to the application url\n routes.\n\n :param handler: function or class instance\n :param uri: path of the URL\n :param methods: list or tuple of methods allowed, these are overridden\n if using a HTTPMethodView\n :param host:\n :param strict_slashes:\n :param version:\n :param name: user defined route name for url_for\n :param stream: boolean specifying if the handler is a stream handler\n :return: function or class instance\n \"\"\"\n # Handle HTTPMethodView differently\n if hasattr(handler, \"view_class\"):\n methods = set()\n\n for method in HTTP_METHODS:\n _handler = getattr(handler.view_class, method.lower(), None)\n if _handler:\n methods.add(method)\n if hasattr(_handler, \"is_stream\"):\n stream = True\n\n # handle composition view differently\n if isinstance(handler, CompositionView):\n methods = handler.handlers.keys()\n for _handler in handler.handlers.values():\n if hasattr(_handler, \"is_stream\"):\n stream = True\n break\n\n if strict_slashes is None:\n strict_slashes = self.strict_slashes\n\n self.route(\n uri=uri,\n methods=methods,\n host=host,\n strict_slashes=strict_slashes,\n stream=stream,\n version=version,\n name=name,\n )(handler)\n return handler", "focal_method_lines": [160, 217], "in_stack": false, "globals": [], "type_context": "from functools import partial, wraps\nfrom inspect import signature\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom re import sub\nfrom time import gmtime, strftime\nfrom typing import Iterable, List, Optional, Set, Union\nfrom urllib.parse import unquote\nfrom sanic_routing.route import Route\nfrom sanic.compat import stat_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS\nfrom sanic.exceptions import (\n ContentRangeError,\n FileNotFound,\n HeaderNotFound,\n InvalidUsage,\n)\nfrom sanic.handlers import ContentRangeHandler\nfrom sanic.log import error_logger\nfrom sanic.models.futures import FutureRoute, FutureStatic\nfrom sanic.response import HTTPResponse, file, file_stream\nfrom sanic.views import CompositionView\n\n\n\nclass RouteMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_routes: Set[FutureRoute] = set()\n self._future_statics: Set[FutureStatic] = set()\n self.name = \"\"\n self.strict_slashes: Optional[bool] = False\n\n def add_route(\n self,\n handler,\n uri: str,\n methods: Iterable[str] = frozenset({\"GET\"}),\n host: Optional[str] = None,\n strict_slashes: Optional[bool] = None,\n version: Optional[int] = None,\n name: Optional[str] = None,\n stream: bool = False,\n ):\n \"\"\"A helper method to register class instance or\n functions as a handler to the application url\n routes.\n\n :param handler: function or class instance\n :param uri: path of the URL\n :param methods: list or tuple of methods allowed, these are overridden\n if using a HTTPMethodView\n :param host:\n :param strict_slashes:\n :param version:\n :param name: user defined route name for url_for\n :param stream: boolean specifying if the handler is a stream handler\n :return: function or class instance\n \"\"\"\n # Handle HTTPMethodView differently\n if hasattr(handler, \"view_class\"):\n methods = set()\n\n for method in HTTP_METHODS:\n _handler = getattr(handler.view_class, method.lower(), None)\n if _handler:\n methods.add(method)\n if hasattr(_handler, \"is_stream\"):\n stream = True\n\n # handle composition view differently\n if isinstance(handler, CompositionView):\n methods = handler.handlers.keys()\n for _handler in handler.handlers.values():\n if hasattr(_handler, \"is_stream\"):\n stream = True\n break\n\n if strict_slashes is None:\n strict_slashes = self.strict_slashes\n\n self.route(\n uri=uri,\n methods=methods,\n host=host,\n strict_slashes=strict_slashes,\n stream=stream,\n version=version,\n name=name,\n )(handler)\n return handler", "has_branch": true, "total_branches": 2} {"prompt_id": 504, "project": "sanic", "module": "sanic.mixins.routes", "class": "RouteMixin", "method": "static", "focal_method_txt": " def static(\n self,\n uri,\n file_or_directory: Union[str, bytes, PurePath],\n pattern=r\"/?.+\",\n use_modified_since=True,\n use_content_range=False,\n stream_large_files=False,\n name=\"static\",\n host=None,\n strict_slashes=None,\n content_type=None,\n apply=True,\n ):\n \"\"\"\n Register a root to serve files from. The input can either be a\n file or a directory. This method will enable an easy and simple way\n to setup the :class:`Route` necessary to serve the static files.\n\n :param uri: URL path to be used for serving static content\n :param file_or_directory: Path for the Static file/directory with\n static files\n :param pattern: Regex Pattern identifying the valid static files\n :param use_modified_since: If true, send file modified time, and return\n not modified if the browser's matches the server's\n :param use_content_range: If true, process header for range requests\n and sends the file part that is requested\n :param stream_large_files: If true, use the\n :func:`StreamingHTTPResponse.file_stream` handler rather\n than the :func:`HTTPResponse.file` handler to send the file.\n If this is an integer, this represents the threshold size to\n switch to :func:`StreamingHTTPResponse.file_stream`\n :param name: user defined name used for url_for\n :param host: Host IP or FQDN for the service to use\n :param strict_slashes: Instruct :class:`Sanic` to check if the request\n URLs need to terminate with a */*\n :param content_type: user defined content type for header\n :return: routes registered on the router\n :rtype: List[sanic.router.Route]\n \"\"\"\n\n name = self._generate_name(name)\n\n if strict_slashes is None and self.strict_slashes is not None:\n strict_slashes = self.strict_slashes\n\n if not isinstance(file_or_directory, (str, bytes, PurePath)):\n raise ValueError(\n f\"Static route must be a valid path, not {file_or_directory}\"\n )\n\n static = FutureStatic(\n uri,\n file_or_directory,\n pattern,\n use_modified_since,\n use_content_range,\n stream_large_files,\n name,\n host,\n strict_slashes,\n content_type,\n )\n self._future_statics.add(static)\n\n if apply:\n self._apply_static(static)", "focal_method_lines": [526, 592], "in_stack": false, "globals": [], "type_context": "from functools import partial, wraps\nfrom inspect import signature\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom re import sub\nfrom time import gmtime, strftime\nfrom typing import Iterable, List, Optional, Set, Union\nfrom urllib.parse import unquote\nfrom sanic_routing.route import Route\nfrom sanic.compat import stat_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS\nfrom sanic.exceptions import (\n ContentRangeError,\n FileNotFound,\n HeaderNotFound,\n InvalidUsage,\n)\nfrom sanic.handlers import ContentRangeHandler\nfrom sanic.log import error_logger\nfrom sanic.models.futures import FutureRoute, FutureStatic\nfrom sanic.response import HTTPResponse, file, file_stream\nfrom sanic.views import CompositionView\n\n\n\nclass RouteMixin:\n\n def __init__(self, *args, **kwargs) -> None:\n self._future_routes: Set[FutureRoute] = set()\n self._future_statics: Set[FutureStatic] = set()\n self.name = \"\"\n self.strict_slashes: Optional[bool] = False\n\n def static(\n self,\n uri,\n file_or_directory: Union[str, bytes, PurePath],\n pattern=r\"/?.+\",\n use_modified_since=True,\n use_content_range=False,\n stream_large_files=False,\n name=\"static\",\n host=None,\n strict_slashes=None,\n content_type=None,\n apply=True,\n ):\n \"\"\"\n Register a root to serve files from. The input can either be a\n file or a directory. This method will enable an easy and simple way\n to setup the :class:`Route` necessary to serve the static files.\n\n :param uri: URL path to be used for serving static content\n :param file_or_directory: Path for the Static file/directory with\n static files\n :param pattern: Regex Pattern identifying the valid static files\n :param use_modified_since: If true, send file modified time, and return\n not modified if the browser's matches the server's\n :param use_content_range: If true, process header for range requests\n and sends the file part that is requested\n :param stream_large_files: If true, use the\n :func:`StreamingHTTPResponse.file_stream` handler rather\n than the :func:`HTTPResponse.file` handler to send the file.\n If this is an integer, this represents the threshold size to\n switch to :func:`StreamingHTTPResponse.file_stream`\n :param name: user defined name used for url_for\n :param host: Host IP or FQDN for the service to use\n :param strict_slashes: Instruct :class:`Sanic` to check if the request\n URLs need to terminate with a */*\n :param content_type: user defined content type for header\n :return: routes registered on the router\n :rtype: List[sanic.router.Route]\n \"\"\"\n\n name = self._generate_name(name)\n\n if strict_slashes is None and self.strict_slashes is not None:\n strict_slashes = self.strict_slashes\n\n if not isinstance(file_or_directory, (str, bytes, PurePath)):\n raise ValueError(\n f\"Static route must be a valid path, not {file_or_directory}\"\n )\n\n static = FutureStatic(\n uri,\n file_or_directory,\n pattern,\n use_modified_since,\n use_content_range,\n stream_large_files,\n name,\n host,\n strict_slashes,\n content_type,\n )\n self._future_statics.add(static)\n\n if apply:\n self._apply_static(static)", "has_branch": true, "total_branches": 2} {"prompt_id": 505, "project": "sanic", "module": "sanic.response", "class": "", "method": "json", "focal_method_txt": "def json(\n body: Any,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"application/json\",\n dumps: Optional[Callable[..., str]] = None,\n **kwargs,\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in json format.\n\n :param body: Response data to be serialized.\n :param status: Response code.\n :param headers: Custom Headers.\n :param kwargs: Remaining arguments that are passed to the json encoder.\n \"\"\"\n if not dumps:\n dumps = BaseHTTPResponse._dumps\n return HTTPResponse(\n dumps(body, **kwargs),\n headers=headers,\n status=status,\n content_type=content_type,\n )", "focal_method_lines": [250, 268], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass BaseHTTPResponse:\n\n _dumps = json_dumps\n\n def __init__(self):\n self.asgi: bool = False\n self.body: Optional[bytes] = None\n self.content_type: Optional[str] = None\n self.stream: Http = None\n self.status: int = None\n self.headers = Header({})\n self._cookies: Optional[CookieJar] = None\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\ndef json(\n body: Any,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"application/json\",\n dumps: Optional[Callable[..., str]] = None,\n **kwargs,\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in json format.\n\n :param body: Response data to be serialized.\n :param status: Response code.\n :param headers: Custom Headers.\n :param kwargs: Remaining arguments that are passed to the json encoder.\n \"\"\"\n if not dumps:\n dumps = BaseHTTPResponse._dumps\n return HTTPResponse(\n dumps(body, **kwargs),\n headers=headers,\n status=status,\n content_type=content_type,\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 506, "project": "sanic", "module": "sanic.response", "class": "", "method": "text", "focal_method_txt": "def text(\n body: str,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in text format.\n\n :param body: Response data to be encoded.\n :param status: Response code.\n :param headers: Custom Headers.\n :param content_type: the content type (string) of the response\n \"\"\"\n if not isinstance(body, str):\n raise TypeError(\n f\"Bad body type. Expected str, got {type(body).__name__})\"\n )\n\n return HTTPResponse(\n body, status=status, headers=headers, content_type=content_type\n )", "focal_method_lines": [276, 295], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\ndef text(\n body: str,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in text format.\n\n :param body: Response data to be encoded.\n :param status: Response code.\n :param headers: Custom Headers.\n :param content_type: the content type (string) of the response\n \"\"\"\n if not isinstance(body, str):\n raise TypeError(\n f\"Bad body type. Expected str, got {type(body).__name__})\"\n )\n\n return HTTPResponse(\n body, status=status, headers=headers, content_type=content_type\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 507, "project": "sanic", "module": "sanic.response", "class": "", "method": "html", "focal_method_txt": "def html(\n body: Union[str, bytes, HTMLProtocol],\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in html format.\n\n :param body: str or bytes-ish, or an object with __html__ or _repr_html_.\n :param status: Response code.\n :param headers: Custom Headers.\n \"\"\"\n if not isinstance(body, (str, bytes)):\n if hasattr(body, \"__html__\"):\n body = body.__html__()\n elif hasattr(body, \"_repr_html_\"):\n body = body._repr_html_()\n\n return HTTPResponse( # type: ignore\n body,\n status=status,\n headers=headers,\n content_type=\"text/html; charset=utf-8\",\n )", "focal_method_lines": [322, 340], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\ndef html(\n body: Union[str, bytes, HTMLProtocol],\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n) -> HTTPResponse:\n \"\"\"\n Returns response object with body in html format.\n\n :param body: str or bytes-ish, or an object with __html__ or _repr_html_.\n :param status: Response code.\n :param headers: Custom Headers.\n \"\"\"\n if not isinstance(body, (str, bytes)):\n if hasattr(body, \"__html__\"):\n body = body.__html__()\n elif hasattr(body, \"_repr_html_\"):\n body = body._repr_html_()\n\n return HTTPResponse( # type: ignore\n body,\n status=status,\n headers=headers,\n content_type=\"text/html; charset=utf-8\",\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 508, "project": "sanic", "module": "sanic.response", "class": "", "method": "file", "focal_method_txt": "async def file(\n location: Union[str, PurePath],\n status: int = 200,\n mime_type: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n filename: Optional[str] = None,\n _range: Optional[Range] = None,\n) -> HTTPResponse:\n \"\"\"Return a response object with file data.\n\n :param location: Location of file on system.\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param filename: Override filename.\n :param _range:\n \"\"\"\n headers = headers or {}\n if filename:\n headers.setdefault(\n \"Content-Disposition\", f'attachment; filename=\"{filename}\"'\n )\n filename = filename or path.split(location)[-1]\n\n async with await open_async(location, mode=\"rb\") as f:\n if _range:\n await f.seek(_range.start)\n out_stream = await f.read(_range.size)\n headers[\n \"Content-Range\"\n ] = f\"bytes {_range.start}-{_range.end}/{_range.total}\"\n status = 206\n else:\n out_stream = await f.read()\n\n mime_type = mime_type or guess_type(filename)[0] or \"text/plain\"\n return HTTPResponse(\n body=out_stream,\n status=status,\n headers=headers,\n content_type=mime_type,\n )", "focal_method_lines": [348, 383], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\nasync def file(\n location: Union[str, PurePath],\n status: int = 200,\n mime_type: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n filename: Optional[str] = None,\n _range: Optional[Range] = None,\n) -> HTTPResponse:\n \"\"\"Return a response object with file data.\n\n :param location: Location of file on system.\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param filename: Override filename.\n :param _range:\n \"\"\"\n headers = headers or {}\n if filename:\n headers.setdefault(\n \"Content-Disposition\", f'attachment; filename=\"{filename}\"'\n )\n filename = filename or path.split(location)[-1]\n\n async with await open_async(location, mode=\"rb\") as f:\n if _range:\n await f.seek(_range.start)\n out_stream = await f.read(_range.size)\n headers[\n \"Content-Range\"\n ] = f\"bytes {_range.start}-{_range.end}/{_range.total}\"\n status = 206\n else:\n out_stream = await f.read()\n\n mime_type = mime_type or guess_type(filename)[0] or \"text/plain\"\n return HTTPResponse(\n body=out_stream,\n status=status,\n headers=headers,\n content_type=mime_type,\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 509, "project": "sanic", "module": "sanic.response", "class": "", "method": "file_stream", "focal_method_txt": "async def file_stream(\n location: Union[str, PurePath],\n status: int = 200,\n chunk_size: int = 4096,\n mime_type: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n filename: Optional[str] = None,\n chunked=\"deprecated\",\n _range: Optional[Range] = None,\n) -> StreamingHTTPResponse:\n \"\"\"Return a streaming response object with file data.\n\n :param location: Location of file on system.\n :param chunk_size: The size of each chunk in the stream (in bytes)\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param filename: Override filename.\n :param chunked: Deprecated\n :param _range:\n \"\"\"\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n headers = headers or {}\n if filename:\n headers.setdefault(\n \"Content-Disposition\", f'attachment; filename=\"{filename}\"'\n )\n filename = filename or path.split(location)[-1]\n mime_type = mime_type or guess_type(filename)[0] or \"text/plain\"\n if _range:\n start = _range.start\n end = _range.end\n total = _range.total\n\n headers[\"Content-Range\"] = f\"bytes {start}-{end}/{total}\"\n status = 206\n\n async def _streaming_fn(response):\n async with await open_async(location, mode=\"rb\") as f:\n if _range:\n await f.seek(_range.start)\n to_send = _range.size\n while to_send > 0:\n content = await f.read(min((_range.size, chunk_size)))\n if len(content) < 1:\n break\n to_send -= len(content)\n await response.write(content)\n else:\n while True:\n content = await f.read(chunk_size)\n if len(content) < 1:\n break\n await response.write(content)\n\n return StreamingHTTPResponse(\n streaming_fn=_streaming_fn,\n status=status,\n headers=headers,\n content_type=mime_type,\n )", "focal_method_lines": [391, 450], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass StreamingHTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\n \"streaming_fn\",\n \"status\",\n \"content_type\",\n \"headers\",\n \"_cookies\",\n )\n\n def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\nasync def file_stream(\n location: Union[str, PurePath],\n status: int = 200,\n chunk_size: int = 4096,\n mime_type: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n filename: Optional[str] = None,\n chunked=\"deprecated\",\n _range: Optional[Range] = None,\n) -> StreamingHTTPResponse:\n \"\"\"Return a streaming response object with file data.\n\n :param location: Location of file on system.\n :param chunk_size: The size of each chunk in the stream (in bytes)\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param filename: Override filename.\n :param chunked: Deprecated\n :param _range:\n \"\"\"\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n headers = headers or {}\n if filename:\n headers.setdefault(\n \"Content-Disposition\", f'attachment; filename=\"{filename}\"'\n )\n filename = filename or path.split(location)[-1]\n mime_type = mime_type or guess_type(filename)[0] or \"text/plain\"\n if _range:\n start = _range.start\n end = _range.end\n total = _range.total\n\n headers[\"Content-Range\"] = f\"bytes {start}-{end}/{total}\"\n status = 206\n\n async def _streaming_fn(response):\n async with await open_async(location, mode=\"rb\") as f:\n if _range:\n await f.seek(_range.start)\n to_send = _range.size\n while to_send > 0:\n content = await f.read(min((_range.size, chunk_size)))\n if len(content) < 1:\n break\n to_send -= len(content)\n await response.write(content)\n else:\n while True:\n content = await f.read(chunk_size)\n if len(content) < 1:\n break\n await response.write(content)\n\n return StreamingHTTPResponse(\n streaming_fn=_streaming_fn,\n status=status,\n headers=headers,\n content_type=mime_type,\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 510, "project": "sanic", "module": "sanic.response", "class": "", "method": "stream", "focal_method_txt": "def stream(\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n):\n \"\"\"Accepts an coroutine `streaming_fn` which can be used to\n write chunks to a streaming response. Returns a `StreamingHTTPResponse`.\n\n Example usage::\n\n @app.route(\"/\")\n async def index(request):\n async def streaming_fn(response):\n await response.write('foo')\n await response.write('bar')\n\n return stream(streaming_fn, content_type='text/plain')\n\n :param streaming_fn: A coroutine accepts a response and\n writes content to that response.\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param chunked: Deprecated\n \"\"\"\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n return StreamingHTTPResponse(\n streaming_fn,\n headers=headers,\n content_type=content_type,\n status=status,\n )", "focal_method_lines": [458, 490], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass StreamingHTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\n \"streaming_fn\",\n \"status\",\n \"content_type\",\n \"headers\",\n \"_cookies\",\n )\n\n def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\nclass HTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\"body\", \"status\", \"content_type\", \"headers\", \"_cookies\")\n\n def __init__(\n self,\n body: Optional[AnyStr] = None,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: Optional[str] = None,\n ):\n super().__init__()\n\n self.content_type: Optional[str] = content_type\n self.body = self._encode_body(body)\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\ndef stream(\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Dict[str, str]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n):\n \"\"\"Accepts an coroutine `streaming_fn` which can be used to\n write chunks to a streaming response. Returns a `StreamingHTTPResponse`.\n\n Example usage::\n\n @app.route(\"/\")\n async def index(request):\n async def streaming_fn(response):\n await response.write('foo')\n await response.write('bar')\n\n return stream(streaming_fn, content_type='text/plain')\n\n :param streaming_fn: A coroutine accepts a response and\n writes content to that response.\n :param mime_type: Specific mime_type.\n :param headers: Custom Headers.\n :param chunked: Deprecated\n \"\"\"\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n return StreamingHTTPResponse(\n streaming_fn,\n headers=headers,\n content_type=content_type,\n status=status,\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 511, "project": "sanic", "module": "sanic.response", "class": "BaseHTTPResponse", "method": "send", "focal_method_txt": " async def send(\n self,\n data: Optional[Union[AnyStr]] = None,\n end_stream: Optional[bool] = None,\n ) -> None:\n \"\"\"\n Send any pending response headers and the given data as body.\n\n :param data: str or bytes to be written\n :param end_stream: whether to close the stream after this block\n \"\"\"\n if data is None and end_stream is None:\n end_stream = True\n if end_stream and not data and self.stream.send is None:\n return\n data = (\n data.encode() # type: ignore\n if hasattr(data, \"encode\")\n else data or b\"\"\n )\n await self.stream.send(data, end_stream=end_stream)", "focal_method_lines": [101, 121], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass BaseHTTPResponse:\n\n _dumps = json_dumps\n\n def __init__(self):\n self.asgi: bool = False\n self.body: Optional[bytes] = None\n self.content_type: Optional[str] = None\n self.stream: Http = None\n self.status: int = None\n self.headers = Header({})\n self._cookies: Optional[CookieJar] = None\n\n async def send(\n self,\n data: Optional[Union[AnyStr]] = None,\n end_stream: Optional[bool] = None,\n ) -> None:\n \"\"\"\n Send any pending response headers and the given data as body.\n\n :param data: str or bytes to be written\n :param end_stream: whether to close the stream after this block\n \"\"\"\n if data is None and end_stream is None:\n end_stream = True\n if end_stream and not data and self.stream.send is None:\n return\n data = (\n data.encode() # type: ignore\n if hasattr(data, \"encode\")\n else data or b\"\"\n )\n await self.stream.send(data, end_stream=end_stream)", "has_branch": true, "total_branches": 2} {"prompt_id": 512, "project": "sanic", "module": "sanic.response", "class": "StreamingHTTPResponse", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None", "focal_method_lines": [170, 190], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass StreamingHTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\n \"streaming_fn\",\n \"status\",\n \"content_type\",\n \"headers\",\n \"_cookies\",\n )\n\n def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None", "has_branch": true, "total_branches": 2} {"prompt_id": 513, "project": "sanic", "module": "sanic.response", "class": "StreamingHTTPResponse", "method": "write", "focal_method_txt": " async def write(self, data):\n \"\"\"Writes a chunk of data to the streaming response.\n\n :param data: str or bytes-ish data to be written.\n \"\"\"\n await super().send(self._encode_body(data))", "focal_method_lines": [192, 197], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass StreamingHTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\n \"streaming_fn\",\n \"status\",\n \"content_type\",\n \"headers\",\n \"_cookies\",\n )\n\n def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\n async def write(self, data):\n \"\"\"Writes a chunk of data to the streaming response.\n\n :param data: str or bytes-ish data to be written.\n \"\"\"\n await super().send(self._encode_body(data))", "has_branch": false, "total_branches": 0} {"prompt_id": 514, "project": "sanic", "module": "sanic.response", "class": "StreamingHTTPResponse", "method": "send", "focal_method_txt": " async def send(self, *args, **kwargs):\n if self.streaming_fn is not None:\n await self.streaming_fn(self)\n self.streaming_fn = None\n await super().send(*args, **kwargs)", "focal_method_lines": [199, 203], "in_stack": false, "globals": ["StreamingFunction"], "type_context": "from functools import partial\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Coroutine,\n Dict,\n Iterator,\n Optional,\n Tuple,\n Union,\n)\nfrom urllib.parse import quote_plus\nfrom warnings import warn\nfrom sanic.compat import Header, open_async\nfrom sanic.constants import DEFAULT_HTTP_CONTENT_TYPE\nfrom sanic.cookies import CookieJar\nfrom sanic.helpers import has_message_body, remove_entity_headers\nfrom sanic.http import Http\nfrom sanic.models.protocol_types import HTMLProtocol, Range\n\nStreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]\n\nclass StreamingHTTPResponse(BaseHTTPResponse):\n\n __slots__ = (\n \"streaming_fn\",\n \"status\",\n \"content_type\",\n \"headers\",\n \"_cookies\",\n )\n\n def __init__(\n self,\n streaming_fn: StreamingFunction,\n status: int = 200,\n headers: Optional[Union[Header, Dict[str, str]]] = None,\n content_type: str = \"text/plain; charset=utf-8\",\n chunked=\"deprecated\",\n ):\n if chunked != \"deprecated\":\n warn(\n \"The chunked argument has been deprecated and will be \"\n \"removed in v21.6\"\n )\n\n super().__init__()\n\n self.content_type = content_type\n self.streaming_fn = streaming_fn\n self.status = status\n self.headers = Header(headers or {})\n self._cookies = None\n\n async def send(self, *args, **kwargs):\n if self.streaming_fn is not None:\n await self.streaming_fn(self)\n self.streaming_fn = None\n await super().send(*args, **kwargs)", "has_branch": true, "total_branches": 2} {"prompt_id": 515, "project": "sanic", "module": "sanic.router", "class": "Router", "method": "add", "focal_method_txt": " def add( # type: ignore\n self,\n uri: str,\n methods: Iterable[str],\n handler: RouteHandler,\n host: Optional[Union[str, Iterable[str]]] = None,\n strict_slashes: bool = False,\n stream: bool = False,\n ignore_body: bool = False,\n version: Union[str, float, int] = None,\n name: Optional[str] = None,\n unquote: bool = False,\n static: bool = False,\n ) -> Union[Route, List[Route]]:\n \"\"\"\n Add a handler to the router\n\n :param uri: the path of the route\n :type uri: str\n :param methods: the types of HTTP methods that should be attached,\n example: ``[\"GET\", \"POST\", \"OPTIONS\"]``\n :type methods: Iterable[str]\n :param handler: the sync or async function to be executed\n :type handler: RouteHandler\n :param host: host that the route should be on, defaults to None\n :type host: Optional[str], optional\n :param strict_slashes: whether to apply strict slashes, defaults\n to False\n :type strict_slashes: bool, optional\n :param stream: whether to stream the response, defaults to False\n :type stream: bool, optional\n :param ignore_body: whether the incoming request body should be read,\n defaults to False\n :type ignore_body: bool, optional\n :param version: a version modifier for the uri, defaults to None\n :type version: Union[str, float, int], optional\n :param name: an identifying name of the route, defaults to None\n :type name: Optional[str], optional\n :return: the route object\n :rtype: Route\n \"\"\"\n if version is not None:\n version = str(version).strip(\"/\").lstrip(\"v\")\n uri = \"/\".join([f\"/v{version}\", uri.lstrip(\"/\")])\n\n params = dict(\n path=uri,\n handler=handler,\n methods=methods,\n name=name,\n strict=strict_slashes,\n unquote=unquote,\n )\n\n if isinstance(host, str):\n hosts = [host]\n else:\n hosts = host or [None] # type: ignore\n\n routes = []\n\n for host in hosts:\n if host:\n params.update({\"requirements\": {\"host\": host}})\n\n route = super().add(**params) # type: ignore\n route.ctx.ignore_body = ignore_body\n route.ctx.stream = stream\n route.ctx.hosts = hosts\n route.ctx.static = static\n\n routes.append(route)\n\n if len(routes) == 1:\n return routes[0]\n return routes", "focal_method_lines": [62, 137], "in_stack": false, "globals": ["ROUTER_CACHE_SIZE", "ALLOWED_LABELS"], "type_context": "from functools import lru_cache\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom sanic_routing import BaseRouter\nfrom sanic_routing.exceptions import NoMethod\nfrom sanic_routing.exceptions import (\n NotFound as RoutingNotFound, # type: ignore\n)\nfrom sanic_routing.route import Route\nfrom sanic.constants import HTTP_METHODS\nfrom sanic.exceptions import MethodNotSupported, NotFound, SanicException\nfrom sanic.models.handler_types import RouteHandler\n\nROUTER_CACHE_SIZE = 1024\nALLOWED_LABELS = (\"__file_uri__\",)\n\nclass Router(BaseRouter):\n\n DEFAULT_METHOD = \"GET\"\n\n ALLOWED_METHODS = HTTP_METHODS\n\n def add( # type: ignore\n self,\n uri: str,\n methods: Iterable[str],\n handler: RouteHandler,\n host: Optional[Union[str, Iterable[str]]] = None,\n strict_slashes: bool = False,\n stream: bool = False,\n ignore_body: bool = False,\n version: Union[str, float, int] = None,\n name: Optional[str] = None,\n unquote: bool = False,\n static: bool = False,\n ) -> Union[Route, List[Route]]:\n \"\"\"\n Add a handler to the router\n\n :param uri: the path of the route\n :type uri: str\n :param methods: the types of HTTP methods that should be attached,\n example: ``[\"GET\", \"POST\", \"OPTIONS\"]``\n :type methods: Iterable[str]\n :param handler: the sync or async function to be executed\n :type handler: RouteHandler\n :param host: host that the route should be on, defaults to None\n :type host: Optional[str], optional\n :param strict_slashes: whether to apply strict slashes, defaults\n to False\n :type strict_slashes: bool, optional\n :param stream: whether to stream the response, defaults to False\n :type stream: bool, optional\n :param ignore_body: whether the incoming request body should be read,\n defaults to False\n :type ignore_body: bool, optional\n :param version: a version modifier for the uri, defaults to None\n :type version: Union[str, float, int], optional\n :param name: an identifying name of the route, defaults to None\n :type name: Optional[str], optional\n :return: the route object\n :rtype: Route\n \"\"\"\n if version is not None:\n version = str(version).strip(\"/\").lstrip(\"v\")\n uri = \"/\".join([f\"/v{version}\", uri.lstrip(\"/\")])\n\n params = dict(\n path=uri,\n handler=handler,\n methods=methods,\n name=name,\n strict=strict_slashes,\n unquote=unquote,\n )\n\n if isinstance(host, str):\n hosts = [host]\n else:\n hosts = host or [None] # type: ignore\n\n routes = []\n\n for host in hosts:\n if host:\n params.update({\"requirements\": {\"host\": host}})\n\n route = super().add(**params) # type: ignore\n route.ctx.ignore_body = ignore_body\n route.ctx.stream = stream\n route.ctx.hosts = hosts\n route.ctx.static = static\n\n routes.append(route)\n\n if len(routes) == 1:\n return routes[0]\n return routes", "has_branch": true, "total_branches": 2} {"prompt_id": 516, "project": "sanic", "module": "sanic.router", "class": "Router", "method": "finalize", "focal_method_txt": " def finalize(self, *args, **kwargs):\n super().finalize(*args, **kwargs)\n\n for route in self.dynamic_routes.values():\n if any(\n label.startswith(\"__\") and label not in ALLOWED_LABELS\n for label in route.labels\n ):\n raise SanicException(\n f\"Invalid route: {route}. Parameter names cannot use '__'.\"\n )", "focal_method_lines": [177, 185], "in_stack": false, "globals": ["ROUTER_CACHE_SIZE", "ALLOWED_LABELS"], "type_context": "from functools import lru_cache\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Union\nfrom sanic_routing import BaseRouter\nfrom sanic_routing.exceptions import NoMethod\nfrom sanic_routing.exceptions import (\n NotFound as RoutingNotFound, # type: ignore\n)\nfrom sanic_routing.route import Route\nfrom sanic.constants import HTTP_METHODS\nfrom sanic.exceptions import MethodNotSupported, NotFound, SanicException\nfrom sanic.models.handler_types import RouteHandler\n\nROUTER_CACHE_SIZE = 1024\nALLOWED_LABELS = (\"__file_uri__\",)\n\nclass Router(BaseRouter):\n\n DEFAULT_METHOD = \"GET\"\n\n ALLOWED_METHODS = HTTP_METHODS\n\n def finalize(self, *args, **kwargs):\n super().finalize(*args, **kwargs)\n\n for route in self.dynamic_routes.values():\n if any(\n label.startswith(\"__\") and label not in ALLOWED_LABELS\n for label in route.labels\n ):\n raise SanicException(\n f\"Invalid route: {route}. Parameter names cannot use '__'.\"\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 517, "project": "sanic", "module": "sanic.utils", "class": "", "method": "str_to_bool", "focal_method_txt": "def str_to_bool(val: str) -> bool:\n \"\"\"Takes string and tries to turn it into bool as human would do.\n\n If val is in case insensitive (\n \"y\", \"yes\", \"yep\", \"yup\", \"t\",\n \"true\", \"on\", \"enable\", \"enabled\", \"1\"\n ) returns True.\n If val is in case insensitive (\n \"n\", \"no\", \"f\", \"false\", \"off\", \"disable\", \"disabled\", \"0\"\n ) returns False.\n Else Raise ValueError.\"\"\"\n\n val = val.lower()\n if val in {\n \"y\",\n \"yes\",\n \"yep\",\n \"yup\",\n \"t\",\n \"true\",\n \"on\",\n \"enable\",\n \"enabled\",\n \"1\",\n }:\n return True\n elif val in {\"n\", \"no\", \"f\", \"false\", \"off\", \"disable\", \"disabled\", \"0\"}:\n return False\n else:\n raise ValueError(f\"Invalid truth value {val}\")", "focal_method_lines": [12, 41], "in_stack": false, "globals": [], "type_context": "import types\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom os import environ as os_environ\nfrom pathlib import Path\nfrom re import findall as re_findall\nfrom typing import Union\nfrom sanic.exceptions import LoadFileException, PyFileError\nfrom sanic.helpers import import_string\n\n\n\ndef str_to_bool(val: str) -> bool:\n \"\"\"Takes string and tries to turn it into bool as human would do.\n\n If val is in case insensitive (\n \"y\", \"yes\", \"yep\", \"yup\", \"t\",\n \"true\", \"on\", \"enable\", \"enabled\", \"1\"\n ) returns True.\n If val is in case insensitive (\n \"n\", \"no\", \"f\", \"false\", \"off\", \"disable\", \"disabled\", \"0\"\n ) returns False.\n Else Raise ValueError.\"\"\"\n\n val = val.lower()\n if val in {\n \"y\",\n \"yes\",\n \"yep\",\n \"yup\",\n \"t\",\n \"true\",\n \"on\",\n \"enable\",\n \"enabled\",\n \"1\",\n }:\n return True\n elif val in {\"n\", \"no\", \"f\", \"false\", \"off\", \"disable\", \"disabled\", \"0\"}:\n return False\n else:\n raise ValueError(f\"Invalid truth value {val}\")", "has_branch": true, "total_branches": 2} {"prompt_id": 518, "project": "sanic", "module": "sanic.utils", "class": "", "method": "load_module_from_file_location", "focal_method_txt": "def load_module_from_file_location(\n location: Union[bytes, str, Path], encoding: str = \"utf8\", *args, **kwargs\n): # noqa\n \"\"\"Returns loaded module provided as a file path.\n\n :param args:\n Coresponds to importlib.util.spec_from_file_location location\n parameters,but with this differences:\n - It has to be of a string or bytes type.\n - You can also use here environment variables\n in format ${some_env_var}.\n Mark that $some_env_var will not be resolved as environment variable.\n :encoding:\n If location parameter is of a bytes type, then use this encoding\n to decode it into string.\n :param args:\n Coresponds to the rest of importlib.util.spec_from_file_location\n parameters.\n :param kwargs:\n Coresponds to the rest of importlib.util.spec_from_file_location\n parameters.\n\n For example You can:\n\n some_module = load_module_from_file_location(\n \"some_module_name\",\n \"/some/path/${some_env_var}\"\n )\n \"\"\"\n if isinstance(location, bytes):\n location = location.decode(encoding)\n\n if isinstance(location, Path) or \"/\" in location or \"$\" in location:\n\n if not isinstance(location, Path):\n # A) Check if location contains any environment variables\n # in format ${some_env_var}.\n env_vars_in_location = set(re_findall(r\"\\${(.+?)}\", location))\n\n # B) Check these variables exists in environment.\n not_defined_env_vars = env_vars_in_location.difference(\n os_environ.keys()\n )\n if not_defined_env_vars:\n raise LoadFileException(\n \"The following environment variables are not set: \"\n f\"{', '.join(not_defined_env_vars)}\"\n )\n\n # C) Substitute them in location.\n for env_var in env_vars_in_location:\n location = location.replace(\n \"${\" + env_var + \"}\", os_environ[env_var]\n )\n\n location = str(location)\n if \".py\" in location:\n name = location.split(\"/\")[-1].split(\".\")[\n 0\n ] # get just the file name without path and .py extension\n _mod_spec = spec_from_file_location(\n name, location, *args, **kwargs\n )\n module = module_from_spec(_mod_spec)\n _mod_spec.loader.exec_module(module) # type: ignore\n\n else:\n module = types.ModuleType(\"config\")\n module.__file__ = str(location)\n try:\n with open(location) as config_file:\n exec( # nosec\n compile(config_file.read(), location, \"exec\"),\n module.__dict__,\n )\n except IOError as e:\n e.strerror = \"Unable to load configuration file (e.strerror)\"\n raise\n except Exception as e:\n raise PyFileError(location) from e\n\n return module\n else:\n try:\n return import_string(location)\n except ValueError:\n raise IOError(\"Unable to load configuration %s\" % str(location))", "focal_method_lines": [44, 130], "in_stack": false, "globals": [], "type_context": "import types\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom os import environ as os_environ\nfrom pathlib import Path\nfrom re import findall as re_findall\nfrom typing import Union\nfrom sanic.exceptions import LoadFileException, PyFileError\nfrom sanic.helpers import import_string\n\n\n\ndef load_module_from_file_location(\n location: Union[bytes, str, Path], encoding: str = \"utf8\", *args, **kwargs\n): # noqa\n \"\"\"Returns loaded module provided as a file path.\n\n :param args:\n Coresponds to importlib.util.spec_from_file_location location\n parameters,but with this differences:\n - It has to be of a string or bytes type.\n - You can also use here environment variables\n in format ${some_env_var}.\n Mark that $some_env_var will not be resolved as environment variable.\n :encoding:\n If location parameter is of a bytes type, then use this encoding\n to decode it into string.\n :param args:\n Coresponds to the rest of importlib.util.spec_from_file_location\n parameters.\n :param kwargs:\n Coresponds to the rest of importlib.util.spec_from_file_location\n parameters.\n\n For example You can:\n\n some_module = load_module_from_file_location(\n \"some_module_name\",\n \"/some/path/${some_env_var}\"\n )\n \"\"\"\n if isinstance(location, bytes):\n location = location.decode(encoding)\n\n if isinstance(location, Path) or \"/\" in location or \"$\" in location:\n\n if not isinstance(location, Path):\n # A) Check if location contains any environment variables\n # in format ${some_env_var}.\n env_vars_in_location = set(re_findall(r\"\\${(.+?)}\", location))\n\n # B) Check these variables exists in environment.\n not_defined_env_vars = env_vars_in_location.difference(\n os_environ.keys()\n )\n if not_defined_env_vars:\n raise LoadFileException(\n \"The following environment variables are not set: \"\n f\"{', '.join(not_defined_env_vars)}\"\n )\n\n # C) Substitute them in location.\n for env_var in env_vars_in_location:\n location = location.replace(\n \"${\" + env_var + \"}\", os_environ[env_var]\n )\n\n location = str(location)\n if \".py\" in location:\n name = location.split(\"/\")[-1].split(\".\")[\n 0\n ] # get just the file name without path and .py extension\n _mod_spec = spec_from_file_location(\n name, location, *args, **kwargs\n )\n module = module_from_spec(_mod_spec)\n _mod_spec.loader.exec_module(module) # type: ignore\n\n else:\n module = types.ModuleType(\"config\")\n module.__file__ = str(location)\n try:\n with open(location) as config_file:\n exec( # nosec\n compile(config_file.read(), location, \"exec\"),\n module.__dict__,\n )\n except IOError as e:\n e.strerror = \"Unable to load configuration file (e.strerror)\"\n raise\n except Exception as e:\n raise PyFileError(location) from e\n\n return module\n else:\n try:\n return import_string(location)\n except ValueError:\n raise IOError(\"Unable to load configuration %s\" % str(location))", "has_branch": false, "total_branches": 0} {"prompt_id": 519, "project": "semantic_release", "module": "semantic_release.ci_checks", "class": "", "method": "checker", "focal_method_txt": "def checker(func: Callable) -> Callable:\n \"\"\"\n A decorator that will convert AssertionErrors into\n CiVerificationError.\n\n :param func: A function that will raise AssertionError\n :return: The given function wrapped to raise a CiVerificationError on AssertionError\n \"\"\"\n\n def func_wrapper(*args, **kwargs):\n try:\n func(*args, **kwargs)\n return True\n except AssertionError:\n raise CiVerificationError(\n \"The verification check for the environment did not pass.\"\n )\n\n return func_wrapper", "focal_method_lines": [8, 26], "in_stack": false, "globals": [], "type_context": "import os\nfrom typing import Callable\nfrom semantic_release.errors import CiVerificationError\n\n\n\ndef checker(func: Callable) -> Callable:\n \"\"\"\n A decorator that will convert AssertionErrors into\n CiVerificationError.\n\n :param func: A function that will raise AssertionError\n :return: The given function wrapped to raise a CiVerificationError on AssertionError\n \"\"\"\n\n def func_wrapper(*args, **kwargs):\n try:\n func(*args, **kwargs)\n return True\n except AssertionError:\n raise CiVerificationError(\n \"The verification check for the environment did not pass.\"\n )\n\n return func_wrapper", "has_branch": false, "total_branches": 0} {"prompt_id": 520, "project": "semantic_release", "module": "semantic_release.ci_checks", "class": "", "method": "check", "focal_method_txt": "def check(branch: str = \"master\"):\n \"\"\"\n Detects the current CI environment, if any, and performs necessary\n environment checks.\n\n :param branch: The branch that should be the current branch.\n \"\"\"\n if os.environ.get(\"TRAVIS\") == \"true\":\n travis(branch)\n elif os.environ.get(\"SEMAPHORE\") == \"true\":\n semaphore(branch)\n elif os.environ.get(\"FRIGG\") == \"true\":\n frigg(branch)\n elif os.environ.get(\"CIRCLECI\") == \"true\":\n circle(branch)\n elif os.environ.get(\"GITLAB_CI\") == \"true\":\n gitlab(branch)\n elif os.environ.get(\"JENKINS_URL\") is not None:\n jenkins(branch)\n elif \"BITBUCKET_BUILD_NUMBER\" in os.environ:\n bitbucket(branch)", "focal_method_lines": [117, 137], "in_stack": false, "globals": [], "type_context": "import os\nfrom typing import Callable\nfrom semantic_release.errors import CiVerificationError\n\n\n\ndef check(branch: str = \"master\"):\n \"\"\"\n Detects the current CI environment, if any, and performs necessary\n environment checks.\n\n :param branch: The branch that should be the current branch.\n \"\"\"\n if os.environ.get(\"TRAVIS\") == \"true\":\n travis(branch)\n elif os.environ.get(\"SEMAPHORE\") == \"true\":\n semaphore(branch)\n elif os.environ.get(\"FRIGG\") == \"true\":\n frigg(branch)\n elif os.environ.get(\"CIRCLECI\") == \"true\":\n circle(branch)\n elif os.environ.get(\"GITLAB_CI\") == \"true\":\n gitlab(branch)\n elif os.environ.get(\"JENKINS_URL\") is not None:\n jenkins(branch)\n elif \"BITBUCKET_BUILD_NUMBER\" in os.environ:\n bitbucket(branch)", "has_branch": true, "total_branches": 2} {"prompt_id": 521, "project": "semantic_release", "module": "semantic_release.dist", "class": "", "method": "should_build", "focal_method_txt": "def should_build():\n upload_pypi = config.get(\"upload_to_pypi\")\n upload_release = config.get(\"upload_to_release\")\n build_command = config.get(\"build_command\")\n build_command = build_command if build_command != \"false\" else False\n return bool(build_command and (upload_pypi or upload_release))", "focal_method_lines": [11, 16], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nfrom invoke import run\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\ndef should_build():\n upload_pypi = config.get(\"upload_to_pypi\")\n upload_release = config.get(\"upload_to_release\")\n build_command = config.get(\"build_command\")\n build_command = build_command if build_command != \"false\" else False\n return bool(build_command and (upload_pypi or upload_release))", "has_branch": false, "total_branches": 0} {"prompt_id": 522, "project": "semantic_release", "module": "semantic_release.dist", "class": "", "method": "should_remove_dist", "focal_method_txt": "def should_remove_dist():\n remove_dist = config.get(\"remove_dist\")\n return bool(remove_dist and should_build())", "focal_method_lines": [19, 21], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nfrom invoke import run\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\ndef should_remove_dist():\n remove_dist = config.get(\"remove_dist\")\n return bool(remove_dist and should_build())", "has_branch": false, "total_branches": 0} {"prompt_id": 523, "project": "semantic_release", "module": "semantic_release.helpers", "class": "", "method": "build_requests_session", "focal_method_txt": "def build_requests_session(\n raise_for_status=True, retry: Union[bool, int, Retry] = True\n) -> Session:\n \"\"\"\n Create a requests session.\n :param raise_for_status: If True, a hook to invoke raise_for_status be installed\n :param retry: If true, it will use default Retry configuration. if an integer, it will use default Retry\n configuration with given integer as total retry count. if Retry instance, it will use this instance.\n :return: configured requests Session\n \"\"\"\n session = Session()\n if raise_for_status:\n session.hooks = {\"response\": [lambda r, *args, **kwargs: r.raise_for_status()]}\n if retry:\n if isinstance(retry, bool):\n retry = Retry()\n elif isinstance(retry, int):\n retry = Retry(retry)\n elif not isinstance(retry, Retry):\n raise ValueError(\"retry should be a bool, int or Retry instance.\")\n adapter = HTTPAdapter(max_retries=retry)\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session", "focal_method_lines": [15, 38], "in_stack": false, "globals": [], "type_context": "import functools\nfrom typing import Union\nfrom requests import Session\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\n\n\ndef build_requests_session(\n raise_for_status=True, retry: Union[bool, int, Retry] = True\n) -> Session:\n \"\"\"\n Create a requests session.\n :param raise_for_status: If True, a hook to invoke raise_for_status be installed\n :param retry: If true, it will use default Retry configuration. if an integer, it will use default Retry\n configuration with given integer as total retry count. if Retry instance, it will use this instance.\n :return: configured requests Session\n \"\"\"\n session = Session()\n if raise_for_status:\n session.hooks = {\"response\": [lambda r, *args, **kwargs: r.raise_for_status()]}\n if retry:\n if isinstance(retry, bool):\n retry = Retry()\n elif isinstance(retry, int):\n retry = Retry(retry)\n elif not isinstance(retry, Retry):\n raise ValueError(\"retry should be a bool, int or Retry instance.\")\n adapter = HTTPAdapter(max_retries=retry)\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session", "has_branch": true, "total_branches": 2} {"prompt_id": 524, "project": "semantic_release", "module": "semantic_release.helpers", "class": "LoggedFunction", "method": "__call__", "focal_method_txt": " def __call__(self, func):\n @functools.wraps(func)\n def logged_func(*args, **kwargs):\n # Log function name and arguments\n self.logger.debug(\n \"{function}({args}{kwargs})\".format(\n function=func.__name__,\n args=\", \".join([format_arg(x) for x in args]),\n kwargs=\"\".join(\n [f\", {k}={format_arg(v)}\" for k, v in kwargs.items()]\n ),\n )\n )\n\n # Call function\n result = func(*args, **kwargs)\n\n # Log result\n if result is not None:\n self.logger.debug(f\"{func.__name__} -> {result}\")\n return result\n\n return logged_func", "focal_method_lines": [54, 76], "in_stack": false, "globals": [], "type_context": "import functools\nfrom typing import Union\nfrom requests import Session\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\n\n\nclass LoggedFunction:\n\n def __init__(self, logger):\n self.logger = logger\n\n def __call__(self, func):\n @functools.wraps(func)\n def logged_func(*args, **kwargs):\n # Log function name and arguments\n self.logger.debug(\n \"{function}({args}{kwargs})\".format(\n function=func.__name__,\n args=\", \".join([format_arg(x) for x in args]),\n kwargs=\"\".join(\n [f\", {k}={format_arg(v)}\" for k, v in kwargs.items()]\n ),\n )\n )\n\n # Call function\n result = func(*args, **kwargs)\n\n # Log result\n if result is not None:\n self.logger.debug(f\"{func.__name__} -> {result}\")\n return result\n\n return logged_func", "has_branch": true, "total_branches": 2} {"prompt_id": 525, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "TokenAuth", "method": "__call__", "focal_method_txt": " def __call__(self, r):\n r.headers[\"Authorization\"] = f\"token {self.token}\"\n return r", "focal_method_lines": [84, 86], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass TokenAuth(AuthBase):\n\n def __init__(self, token):\n self.token = token\n\n def __call__(self, r):\n r.headers[\"Authorization\"] = f\"token {self.token}\"\n return r", "has_branch": false, "total_branches": 0} {"prompt_id": 526, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Github", "method": "domain", "focal_method_txt": " @staticmethod\n def domain() -> str:\n \"\"\"Github domain property\n\n :return: The Github domain\n \"\"\"\n hvcs_domain = config.get(\"hvcs_domain\")\n domain = hvcs_domain if hvcs_domain else Github.DEFAULT_DOMAIN\n return domain", "focal_method_lines": [96, 103], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass Github(Base):\n\n DEFAULT_DOMAIN = \"github.com\"\n\n @staticmethod\n def domain() -> str:\n \"\"\"Github domain property\n\n :return: The Github domain\n \"\"\"\n hvcs_domain = config.get(\"hvcs_domain\")\n domain = hvcs_domain if hvcs_domain else Github.DEFAULT_DOMAIN\n return domain", "has_branch": false, "total_branches": 0} {"prompt_id": 527, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Github", "method": "api_url", "focal_method_txt": " @staticmethod\n def api_url() -> str:\n \"\"\"Github api_url property\n\n :return: The Github API URL\n \"\"\"\n # not necessarily prefixed with api in the case of a custom domain, so\n # can't just default DEFAULT_DOMAIN to github.com\n hvcs_domain = config.get(\"hvcs_domain\")\n hostname = hvcs_domain if hvcs_domain else \"api.\" + Github.DEFAULT_DOMAIN\n return f\"https://{hostname}\"", "focal_method_lines": [106, 115], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass Github(Base):\n\n DEFAULT_DOMAIN = \"github.com\"\n\n @staticmethod\n def api_url() -> str:\n \"\"\"Github api_url property\n\n :return: The Github API URL\n \"\"\"\n # not necessarily prefixed with api in the case of a custom domain, so\n # can't just default DEFAULT_DOMAIN to github.com\n hvcs_domain = config.get(\"hvcs_domain\")\n hostname = hvcs_domain if hvcs_domain else \"api.\" + Github.DEFAULT_DOMAIN\n return f\"https://{hostname}\"", "has_branch": false, "total_branches": 0} {"prompt_id": 528, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Github", "method": "auth", "focal_method_txt": " @staticmethod\n def auth() -> Optional[TokenAuth]:\n \"\"\"Github token property\n\n :return: The Github token environment variable (GH_TOKEN) value\n \"\"\"\n token = Github.token()\n if not token:\n return None\n return TokenAuth(token)", "focal_method_lines": [126, 134], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass TokenAuth(AuthBase):\n\n def __init__(self, token):\n self.token = token\n\nclass Github(Base):\n\n DEFAULT_DOMAIN = \"github.com\"\n\n @staticmethod\n def auth() -> Optional[TokenAuth]:\n \"\"\"Github token property\n\n :return: The Github token environment variable (GH_TOKEN) value\n \"\"\"\n token = Github.token()\n if not token:\n return None\n return TokenAuth(token)", "has_branch": true, "total_branches": 2} {"prompt_id": 529, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Github", "method": "check_build_status", "focal_method_txt": " @staticmethod\n @LoggedFunction(logger)\n def check_build_status(owner: str, repo: str, ref: str) -> bool:\n \"\"\"Check build status\n\n https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference\n\n :param owner: The owner namespace of the repository\n :param repo: The repository name\n :param ref: The sha1 hash of the commit ref\n\n :return: Was the build status success?\n \"\"\"\n url = \"{domain}/repos/{owner}/{repo}/commits/{ref}/status\"\n try:\n response = Github.session().get(\n url.format(domain=Github.api_url(), owner=owner, repo=repo, ref=ref)\n )\n return response.json().get(\"state\") == \"success\"\n except HTTPError as e:\n logger.warning(f\"Build status check on Github has failed: {e}\")\n return False", "focal_method_lines": [146, 165], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass Github(Base):\n\n DEFAULT_DOMAIN = \"github.com\"\n\n @staticmethod\n @LoggedFunction(logger)\n def check_build_status(owner: str, repo: str, ref: str) -> bool:\n \"\"\"Check build status\n\n https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference\n\n :param owner: The owner namespace of the repository\n :param repo: The repository name\n :param ref: The sha1 hash of the commit ref\n\n :return: Was the build status success?\n \"\"\"\n url = \"{domain}/repos/{owner}/{repo}/commits/{ref}/status\"\n try:\n response = Github.session().get(\n url.format(domain=Github.api_url(), owner=owner, repo=repo, ref=ref)\n )\n return response.json().get(\"state\") == \"success\"\n except HTTPError as e:\n logger.warning(f\"Build status check on Github has failed: {e}\")\n return False", "has_branch": false, "total_branches": 0} {"prompt_id": 530, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Gitlab", "method": "domain", "focal_method_txt": " @staticmethod\n def domain() -> str:\n \"\"\"Gitlab domain property\n\n :return: The Gitlab instance domain\n \"\"\"\n domain = config.get(\"hvcs_domain\", os.environ.get(\"CI_SERVER_HOST\"))\n return domain if domain else \"gitlab.com\"", "focal_method_lines": [348, 354], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass Gitlab(Base):\n\n @staticmethod\n def domain() -> str:\n \"\"\"Gitlab domain property\n\n :return: The Gitlab instance domain\n \"\"\"\n domain = config.get(\"hvcs_domain\", os.environ.get(\"CI_SERVER_HOST\"))\n return domain if domain else \"gitlab.com\"", "has_branch": false, "total_branches": 0} {"prompt_id": 531, "project": "semantic_release", "module": "semantic_release.hvcs", "class": "Gitlab", "method": "check_build_status", "focal_method_txt": " @staticmethod\n @LoggedFunction(logger)\n def check_build_status(owner: str, repo: str, ref: str) -> bool:\n \"\"\"Check last build status\n\n :param owner: The owner namespace of the repository. It includes all groups and subgroups.\n :param repo: The repository name\n :param ref: The sha1 hash of the commit ref\n\n :return: the status of the pipeline (False if a job failed)\n \"\"\"\n gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token())\n gl.auth()\n jobs = gl.projects.get(owner + \"/\" + repo).commits.get(ref).statuses.list()\n for job in jobs:\n if job[\"status\"] not in [\"success\", \"skipped\"]:\n if job[\"status\"] == \"pending\":\n logger.debug(\n f\"check_build_status: job {job['name']} is still in pending status\"\n )\n return False\n elif job[\"status\"] == \"failed\" and not job[\"allow_failure\"]:\n logger.debug(f\"check_build_status: job {job['name']} failed\")\n return False\n return True", "focal_method_lines": [374, 396], "in_stack": false, "globals": ["logger"], "type_context": "import logging\nimport mimetypes\nimport os\nfrom typing import Optional, Union\nimport gitlab\nfrom requests import HTTPError, Session\nfrom requests.auth import AuthBase\nfrom urllib3 import Retry\nfrom .errors import ImproperConfigurationError\nfrom .helpers import LoggedFunction, build_requests_session\nfrom .settings import config\n\nlogger = logging.getLogger(__name__)\n\nclass Gitlab(Base):\n\n @staticmethod\n @LoggedFunction(logger)\n def check_build_status(owner: str, repo: str, ref: str) -> bool:\n \"\"\"Check last build status\n\n :param owner: The owner namespace of the repository. It includes all groups and subgroups.\n :param repo: The repository name\n :param ref: The sha1 hash of the commit ref\n\n :return: the status of the pipeline (False if a job failed)\n \"\"\"\n gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token())\n gl.auth()\n jobs = gl.projects.get(owner + \"/\" + repo).commits.get(ref).statuses.list()\n for job in jobs:\n if job[\"status\"] not in [\"success\", \"skipped\"]:\n if job[\"status\"] == \"pending\":\n logger.debug(\n f\"check_build_status: job {job['name']} is still in pending status\"\n )\n return False\n elif job[\"status\"] == \"failed\" and not job[\"allow_failure\"]:\n logger.debug(f\"check_build_status: job {job['name']} failed\")\n return False\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 532, "project": "semantic_release", "module": "semantic_release.settings", "class": "", "method": "current_commit_parser", "focal_method_txt": "def current_commit_parser() -> Callable:\n \"\"\"Get the currently-configured commit parser\n\n :raises ImproperConfigurationError: if ImportError or AttributeError is raised\n :returns: Commit parser\n \"\"\"\n\n try:\n # All except the last part is the import path\n parts = config.get(\"commit_parser\").split(\".\")\n module = \".\".join(parts[:-1])\n # The final part is the name of the parse function\n return getattr(importlib.import_module(module), parts[-1])\n except (ImportError, AttributeError) as error:\n raise ImproperConfigurationError(f'Unable to import parser \"{error}\"')", "focal_method_lines": [79, 93], "in_stack": false, "globals": ["logger", "config"], "type_context": "import configparser\nimport importlib\nimport logging\nimport os\nfrom collections import UserDict\nfrom functools import wraps\nfrom os import getcwd\nfrom typing import Callable, List\nimport tomlkit\nfrom tomlkit.exceptions import TOMLKitError\nfrom .errors import ImproperConfigurationError\n\nlogger = logging.getLogger(__name__)\nconfig = _config()\n\ndef current_commit_parser() -> Callable:\n \"\"\"Get the currently-configured commit parser\n\n :raises ImproperConfigurationError: if ImportError or AttributeError is raised\n :returns: Commit parser\n \"\"\"\n\n try:\n # All except the last part is the import path\n parts = config.get(\"commit_parser\").split(\".\")\n module = \".\".join(parts[:-1])\n # The final part is the name of the parse function\n return getattr(importlib.import_module(module), parts[-1])\n except (ImportError, AttributeError) as error:\n raise ImproperConfigurationError(f'Unable to import parser \"{error}\"')", "has_branch": false, "total_branches": 0} {"prompt_id": 533, "project": "semantic_release", "module": "semantic_release.settings", "class": "", "method": "current_changelog_components", "focal_method_txt": "def current_changelog_components() -> List[Callable]:\n \"\"\"Get the currently-configured changelog components\n\n :raises ImproperConfigurationError: if ImportError or AttributeError is raised\n :returns: List of component functions\n \"\"\"\n component_paths = config.get(\"changelog_components\").split(\",\")\n components = list()\n\n for path in component_paths:\n try:\n # All except the last part is the import path\n parts = path.split(\".\")\n module = \".\".join(parts[:-1])\n # The final part is the name of the component function\n components.append(getattr(importlib.import_module(module), parts[-1]))\n except (ImportError, AttributeError) as error:\n raise ImproperConfigurationError(\n f'Unable to import changelog component \"{path}\"'\n )\n\n return components", "focal_method_lines": [96, 117], "in_stack": false, "globals": ["logger", "config"], "type_context": "import configparser\nimport importlib\nimport logging\nimport os\nfrom collections import UserDict\nfrom functools import wraps\nfrom os import getcwd\nfrom typing import Callable, List\nimport tomlkit\nfrom tomlkit.exceptions import TOMLKitError\nfrom .errors import ImproperConfigurationError\n\nlogger = logging.getLogger(__name__)\nconfig = _config()\n\ndef current_changelog_components() -> List[Callable]:\n \"\"\"Get the currently-configured changelog components\n\n :raises ImproperConfigurationError: if ImportError or AttributeError is raised\n :returns: List of component functions\n \"\"\"\n component_paths = config.get(\"changelog_components\").split(\",\")\n components = list()\n\n for path in component_paths:\n try:\n # All except the last part is the import path\n parts = path.split(\".\")\n module = \".\".join(parts[:-1])\n # The final part is the name of the component function\n components.append(getattr(importlib.import_module(module), parts[-1]))\n except (ImportError, AttributeError) as error:\n raise ImproperConfigurationError(\n f'Unable to import changelog component \"{path}\"'\n )\n\n return components", "has_branch": true, "total_branches": 2} {"prompt_id": 534, "project": "semantic_release", "module": "semantic_release.settings", "class": "", "method": "overload_configuration", "focal_method_txt": "def overload_configuration(func):\n \"\"\"This decorator gets the content of the \"define\" array and edits \"config\"\n according to the pairs of key/value.\n \"\"\"\n\n @wraps(func)\n def wrap(*args, **kwargs):\n if \"define\" in kwargs:\n for defined_param in kwargs[\"define\"]:\n pair = defined_param.split(\"=\", maxsplit=1)\n if len(pair) == 2:\n config[str(pair[0])] = pair[1]\n return func(*args, **kwargs)\n\n return wrap", "focal_method_lines": [120, 134], "in_stack": false, "globals": ["logger", "config"], "type_context": "import configparser\nimport importlib\nimport logging\nimport os\nfrom collections import UserDict\nfrom functools import wraps\nfrom os import getcwd\nfrom typing import Callable, List\nimport tomlkit\nfrom tomlkit.exceptions import TOMLKitError\nfrom .errors import ImproperConfigurationError\n\nlogger = logging.getLogger(__name__)\nconfig = _config()\n\ndef overload_configuration(func):\n \"\"\"This decorator gets the content of the \"define\" array and edits \"config\"\n according to the pairs of key/value.\n \"\"\"\n\n @wraps(func)\n def wrap(*args, **kwargs):\n if \"define\" in kwargs:\n for defined_param in kwargs[\"define\"]:\n pair = defined_param.split(\"=\", maxsplit=1)\n if len(pair) == 2:\n config[str(pair[0])] = pair[1]\n return func(*args, **kwargs)\n\n return wrap", "has_branch": true, "total_branches": 2} {"prompt_id": 535, "project": "string_utils", "module": "string_utils.generation", "class": "", "method": "roman_range", "focal_method_txt": "def roman_range(stop: int, start: int = 1, step: int = 1) -> Generator:\n \"\"\"\n Similarly to native Python's `range()`, returns a Generator object which generates a new roman number\n on each iteration instead of an integer.\n\n *Example:*\n\n >>> for n in roman_range(7): print(n)\n >>> # prints: I, II, III, IV, V, VI, VII\n >>> for n in roman_range(start=7, stop=1, step=-1): print(n)\n >>> # prints: VII, VI, V, IV, III, II, I\n\n :param stop: Number at which the generation must stop (must be <= 3999).\n :param start: Number at which the generation must start (must be >= 1).\n :param step: Increment of each generation step (default to 1).\n :return: Generator of roman numbers.\n \"\"\"\n\n def validate(arg_value, arg_name, allow_negative=False):\n msg = '\"{}\" must be an integer in the range 1-3999'.format(arg_name)\n\n if not isinstance(arg_value, int):\n raise ValueError(msg)\n\n if allow_negative:\n arg_value = abs(arg_value)\n\n if arg_value < 1 or arg_value > 3999:\n raise ValueError(msg)\n\n def generate():\n current = start\n\n # generate values for each step\n while current != stop:\n yield roman_encode(current)\n current += step\n\n # last value to return\n yield roman_encode(current)\n\n # checks each single argument value\n validate(stop, 'stop')\n validate(start, 'start')\n validate(step, 'step', allow_negative=True)\n\n # checks if the provided configuration leads to a feasible iteration with respect to boundaries or not\n forward_exceed = step > 0 and (start > stop or start + step > stop)\n backward_exceed = step < 0 and (start < stop or start + step < stop)\n if forward_exceed or backward_exceed:\n raise OverflowError('Invalid start/stop/step configuration')\n\n return generate()", "focal_method_lines": [87, 139], "in_stack": false, "globals": ["__all__"], "type_context": "import binascii\nimport os\nimport random\nimport string\nfrom typing import Generator\nfrom uuid import uuid4\nfrom .manipulation import roman_encode\n\n__all__ = [\n 'uuid',\n 'random_string',\n 'secure_random_hex',\n 'roman_range',\n]\n\ndef roman_range(stop: int, start: int = 1, step: int = 1) -> Generator:\n \"\"\"\n Similarly to native Python's `range()`, returns a Generator object which generates a new roman number\n on each iteration instead of an integer.\n\n *Example:*\n\n >>> for n in roman_range(7): print(n)\n >>> # prints: I, II, III, IV, V, VI, VII\n >>> for n in roman_range(start=7, stop=1, step=-1): print(n)\n >>> # prints: VII, VI, V, IV, III, II, I\n\n :param stop: Number at which the generation must stop (must be <= 3999).\n :param start: Number at which the generation must start (must be >= 1).\n :param step: Increment of each generation step (default to 1).\n :return: Generator of roman numbers.\n \"\"\"\n\n def validate(arg_value, arg_name, allow_negative=False):\n msg = '\"{}\" must be an integer in the range 1-3999'.format(arg_name)\n\n if not isinstance(arg_value, int):\n raise ValueError(msg)\n\n if allow_negative:\n arg_value = abs(arg_value)\n\n if arg_value < 1 or arg_value > 3999:\n raise ValueError(msg)\n\n def generate():\n current = start\n\n # generate values for each step\n while current != stop:\n yield roman_encode(current)\n current += step\n\n # last value to return\n yield roman_encode(current)\n\n # checks each single argument value\n validate(stop, 'stop')\n validate(start, 'start')\n validate(step, 'step', allow_negative=True)\n\n # checks if the provided configuration leads to a feasible iteration with respect to boundaries or not\n forward_exceed = step > 0 and (start > stop or start + step > stop)\n backward_exceed = step < 0 and (start < stop or start + step < stop)\n if forward_exceed or backward_exceed:\n raise OverflowError('Invalid start/stop/step configuration')\n\n return generate()", "has_branch": true, "total_branches": 2} {"prompt_id": 536, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "reverse", "focal_method_txt": "def reverse(input_string: str) -> str:\n \"\"\"\n Returns the string with its chars reversed.\n\n *Example:*\n\n >>> reverse('hello') # returns 'olleh'\n\n :param input_string: String to revert.\n :type input_string: str\n :return: Reversed string.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n return input_string[::-1]", "focal_method_lines": [281, 296], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef reverse(input_string: str) -> str:\n \"\"\"\n Returns the string with its chars reversed.\n\n *Example:*\n\n >>> reverse('hello') # returns 'olleh'\n\n :param input_string: String to revert.\n :type input_string: str\n :return: Reversed string.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n return input_string[::-1]", "has_branch": true, "total_branches": 2} {"prompt_id": 537, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "camel_case_to_snake", "focal_method_txt": "def camel_case_to_snake(input_string, separator='_'):\n \"\"\"\n Convert a camel case string into a snake case one.\n (The original string is returned if is not a valid camel case string)\n\n *Example:*\n\n >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test'\n\n :param input_string: String to convert.\n :type input_string: str\n :param separator: Sign to use as separator.\n :type separator: str\n :return: Converted string.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n if not is_camel_case(input_string):\n return input_string\n\n return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower()", "focal_method_lines": [299, 320], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef camel_case_to_snake(input_string, separator='_'):\n \"\"\"\n Convert a camel case string into a snake case one.\n (The original string is returned if is not a valid camel case string)\n\n *Example:*\n\n >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test'\n\n :param input_string: String to convert.\n :type input_string: str\n :param separator: Sign to use as separator.\n :type separator: str\n :return: Converted string.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n if not is_camel_case(input_string):\n return input_string\n\n return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower()", "has_branch": true, "total_branches": 2} {"prompt_id": 538, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "snake_case_to_camel", "focal_method_txt": "def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str:\n \"\"\"\n Convert a snake case string into a camel case one.\n (The original string is returned if is not a valid snake case string)\n\n *Example:*\n\n >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen'\n\n :param input_string: String to convert.\n :type input_string: str\n :param upper_case_first: True to turn the first letter into uppercase (default).\n :type upper_case_first: bool\n :param separator: Sign to use as separator (default to \"_\").\n :type separator: str\n :return: Converted string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n if not is_snake_case(input_string, separator):\n return input_string\n\n tokens = [s.title() for s in input_string.split(separator) if is_full_string(s)]\n\n if not upper_case_first:\n tokens[0] = tokens[0].lower()\n\n out = ''.join(tokens)\n\n return out", "focal_method_lines": [323, 353], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str:\n \"\"\"\n Convert a snake case string into a camel case one.\n (The original string is returned if is not a valid snake case string)\n\n *Example:*\n\n >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen'\n\n :param input_string: String to convert.\n :type input_string: str\n :param upper_case_first: True to turn the first letter into uppercase (default).\n :type upper_case_first: bool\n :param separator: Sign to use as separator (default to \"_\").\n :type separator: str\n :return: Converted string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n if not is_snake_case(input_string, separator):\n return input_string\n\n tokens = [s.title() for s in input_string.split(separator) if is_full_string(s)]\n\n if not upper_case_first:\n tokens[0] = tokens[0].lower()\n\n out = ''.join(tokens)\n\n return out", "has_branch": true, "total_branches": 2} {"prompt_id": 539, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "shuffle", "focal_method_txt": "def shuffle(input_string: str) -> str:\n \"\"\"\n Return a new string containing same chars of the given one but in a randomized order.\n\n *Example:*\n\n >>> shuffle('hello world') # possible output: 'l wodheorll'\n\n :param input_string: String to shuffle\n :type input_string: str\n :return: Shuffled string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # turn the string into a list of chars\n chars = list(input_string)\n\n # shuffle the list\n random.shuffle(chars)\n\n # convert the shuffled list back to string\n return ''.join(chars)", "focal_method_lines": [356, 378], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef shuffle(input_string: str) -> str:\n \"\"\"\n Return a new string containing same chars of the given one but in a randomized order.\n\n *Example:*\n\n >>> shuffle('hello world') # possible output: 'l wodheorll'\n\n :param input_string: String to shuffle\n :type input_string: str\n :return: Shuffled string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # turn the string into a list of chars\n chars = list(input_string)\n\n # shuffle the list\n random.shuffle(chars)\n\n # convert the shuffled list back to string\n return ''.join(chars)", "has_branch": true, "total_branches": 2} {"prompt_id": 540, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "strip_html", "focal_method_txt": "def strip_html(input_string: str, keep_tag_content: bool = False) -> str:\n \"\"\"\n Remove html code contained into the given string.\n\n *Examples:*\n\n >>> strip_html('test: click here') # returns 'test: '\n >>> strip_html('test: click here', keep_tag_content=True) # returns 'test: click here'\n\n :param input_string: String to manipulate.\n :type input_string: str\n :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n :type keep_tag_content: bool\n :return: String with html removed.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n\n return r.sub('', input_string)", "focal_method_lines": [381, 401], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef strip_html(input_string: str, keep_tag_content: bool = False) -> str:\n \"\"\"\n Remove html code contained into the given string.\n\n *Examples:*\n\n >>> strip_html('test: click here') # returns 'test: '\n >>> strip_html('test: click here', keep_tag_content=True) # returns 'test: click here'\n\n :param input_string: String to manipulate.\n :type input_string: str\n :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n :type keep_tag_content: bool\n :return: String with html removed.\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n\n return r.sub('', input_string)", "has_branch": true, "total_branches": 2} {"prompt_id": 541, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "prettify", "focal_method_txt": "def prettify(input_string: str) -> str:\n \"\"\"\n Reformat a string by applying the following basic grammar and formatting rules:\n\n - String cannot start or end with spaces\n - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase\n - String cannot have multiple sequential spaces, empty lines or punctuation (except for \"?\", \"!\" and \".\")\n - Arithmetic operators (+, -, /, \\\\*, =) must have one, and only one space before and after themselves\n - One, and only one space should follow a dot, a comma, an exclamation or a question mark\n - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \\\n after quotes (foo\" bar\"baz -> foo \"bar\" baz)\n - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \\\n after brackets (\"foo(bar )baz\" -> \"foo (bar) baz\")\n - Percentage sign (\"%\") cannot be preceded by a space if there is a number before (\"100 %\" -> \"100%\")\n - Saxon genitive is correct (\"Dave' s dog\" -> \"Dave's dog\")\n\n *Examples:*\n\n >>> prettify(' unprettified string ,, like this one,will be\"prettified\" .it\\\\' s awesome! ')\n >>> # -> 'Unprettified string, like this one, will be \"prettified\". It\\'s awesome!'\n\n :param input_string: String to manipulate\n :return: Prettified string.\n \"\"\"\n formatted = __StringFormatter(input_string).format()\n return formatted", "focal_method_lines": [404, 429], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\nclass __StringFormatter:\n\n def __init__(self, input_string):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string\n\ndef prettify(input_string: str) -> str:\n \"\"\"\n Reformat a string by applying the following basic grammar and formatting rules:\n\n - String cannot start or end with spaces\n - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase\n - String cannot have multiple sequential spaces, empty lines or punctuation (except for \"?\", \"!\" and \".\")\n - Arithmetic operators (+, -, /, \\\\*, =) must have one, and only one space before and after themselves\n - One, and only one space should follow a dot, a comma, an exclamation or a question mark\n - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \\\n after quotes (foo\" bar\"baz -> foo \"bar\" baz)\n - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \\\n after brackets (\"foo(bar )baz\" -> \"foo (bar) baz\")\n - Percentage sign (\"%\") cannot be preceded by a space if there is a number before (\"100 %\" -> \"100%\")\n - Saxon genitive is correct (\"Dave' s dog\" -> \"Dave's dog\")\n\n *Examples:*\n\n >>> prettify(' unprettified string ,, like this one,will be\"prettified\" .it\\\\' s awesome! ')\n >>> # -> 'Unprettified string, like this one, will be \"prettified\". It\\'s awesome!'\n\n :param input_string: String to manipulate\n :return: Prettified string.\n \"\"\"\n formatted = __StringFormatter(input_string).format()\n return formatted", "has_branch": false, "total_branches": 0} {"prompt_id": 542, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "asciify", "focal_method_txt": "def asciify(input_string: str) -> str:\n \"\"\"\n Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation\n (eg: ó -> o, Ë -> E, ç -> c...).\n\n **Bear in mind**: Some chars may be lost if impossible to translate.\n\n *Example:*\n\n >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE'\n\n :param input_string: String to convert\n :return: Ascii utf-8 string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # \"NFKD\" is the algorithm which is able to successfully translate the most of non-ascii chars\n normalized = unicodedata.normalize('NFKD', input_string)\n\n # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out)\n ascii_bytes = normalized.encode('ascii', 'ignore')\n\n # turns encoded bytes into an utf-8 string\n ascii_string = ascii_bytes.decode('utf-8')\n\n return ascii_string", "focal_method_lines": [432, 458], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef asciify(input_string: str) -> str:\n \"\"\"\n Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation\n (eg: ó -> o, Ë -> E, ç -> c...).\n\n **Bear in mind**: Some chars may be lost if impossible to translate.\n\n *Example:*\n\n >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE'\n\n :param input_string: String to convert\n :return: Ascii utf-8 string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # \"NFKD\" is the algorithm which is able to successfully translate the most of non-ascii chars\n normalized = unicodedata.normalize('NFKD', input_string)\n\n # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out)\n ascii_bytes = normalized.encode('ascii', 'ignore')\n\n # turns encoded bytes into an utf-8 string\n ascii_string = ascii_bytes.decode('utf-8')\n\n return ascii_string", "has_branch": true, "total_branches": 2} {"prompt_id": 543, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "slugify", "focal_method_txt": "def slugify(input_string: str, separator: str = '-') -> str:\n \"\"\"\n Converts a string into a \"slug\" using provided separator.\n The returned string has the following properties:\n\n - it has no spaces\n - all letters are in lower case\n - all punctuation signs and non alphanumeric chars are removed\n - words are divided using provided separator\n - all chars are encoded as ascii (by using `asciify()`)\n - is safe for URL\n\n *Examples:*\n\n >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs'\n >>> slugify('Mönstér Mägnët') # returns 'monster-magnet'\n\n :param input_string: String to convert.\n :type input_string: str\n :param separator: Sign used to join string tokens (default to \"-\").\n :type separator: str\n :return: Slug string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # replace any character that is NOT letter or number with spaces\n out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip()\n\n # replace spaces with join sign\n out = SPACES_RE.sub(separator, out)\n\n # normalize joins (remove duplicates)\n out = re.sub(re.escape(separator) + r'+', separator, out)\n\n return asciify(out)", "focal_method_lines": [461, 496], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef slugify(input_string: str, separator: str = '-') -> str:\n \"\"\"\n Converts a string into a \"slug\" using provided separator.\n The returned string has the following properties:\n\n - it has no spaces\n - all letters are in lower case\n - all punctuation signs and non alphanumeric chars are removed\n - words are divided using provided separator\n - all chars are encoded as ascii (by using `asciify()`)\n - is safe for URL\n\n *Examples:*\n\n >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs'\n >>> slugify('Mönstér Mägnët') # returns 'monster-magnet'\n\n :param input_string: String to convert.\n :type input_string: str\n :param separator: Sign used to join string tokens (default to \"-\").\n :type separator: str\n :return: Slug string\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n # replace any character that is NOT letter or number with spaces\n out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip()\n\n # replace spaces with join sign\n out = SPACES_RE.sub(separator, out)\n\n # normalize joins (remove duplicates)\n out = re.sub(re.escape(separator) + r'+', separator, out)\n\n return asciify(out)", "has_branch": true, "total_branches": 2} {"prompt_id": 544, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "booleanize", "focal_method_txt": "def booleanize(input_string: str) -> bool:\n \"\"\"\n Turns a string into a boolean based on its content (CASE INSENSITIVE).\n\n A positive boolean (True) is returned if the string value is one of the following:\n\n - \"true\"\n - \"1\"\n - \"yes\"\n - \"y\"\n\n Otherwise False is returned.\n\n *Examples:*\n\n >>> booleanize('true') # returns True\n >>> booleanize('YES') # returns True\n >>> booleanize('nope') # returns False\n\n :param input_string: String to convert\n :type input_string: str\n :return: True if the string contains a boolean-like positive value, false otherwise\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n return input_string.lower() in ('true', '1', 'yes', 'y')", "focal_method_lines": [499, 525], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef booleanize(input_string: str) -> bool:\n \"\"\"\n Turns a string into a boolean based on its content (CASE INSENSITIVE).\n\n A positive boolean (True) is returned if the string value is one of the following:\n\n - \"true\"\n - \"1\"\n - \"yes\"\n - \"y\"\n\n Otherwise False is returned.\n\n *Examples:*\n\n >>> booleanize('true') # returns True\n >>> booleanize('YES') # returns True\n >>> booleanize('nope') # returns False\n\n :param input_string: String to convert\n :type input_string: str\n :return: True if the string contains a boolean-like positive value, false otherwise\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n return input_string.lower() in ('true', '1', 'yes', 'y')", "has_branch": true, "total_branches": 2} {"prompt_id": 545, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "strip_margin", "focal_method_txt": "def strip_margin(input_string: str) -> str:\n \"\"\"\n Removes tab indentation from multi line strings (inspired by analogous Scala function).\n\n *Example:*\n\n >>> strip_margin('''\n >>> line 1\n >>> line 2\n >>> line 3\n >>> ''')\n >>> # returns:\n >>> '''\n >>> line 1\n >>> line 2\n >>> line 3\n >>> '''\n\n :param input_string: String to format\n :type input_string: str\n :return: A string without left margins\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n line_separator = '\\n'\n lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)]\n out = line_separator.join(lines)\n\n return out", "focal_method_lines": [528, 557], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef strip_margin(input_string: str) -> str:\n \"\"\"\n Removes tab indentation from multi line strings (inspired by analogous Scala function).\n\n *Example:*\n\n >>> strip_margin('''\n >>> line 1\n >>> line 2\n >>> line 3\n >>> ''')\n >>> # returns:\n >>> '''\n >>> line 1\n >>> line 2\n >>> line 3\n >>> '''\n\n :param input_string: String to format\n :type input_string: str\n :return: A string without left margins\n \"\"\"\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n line_separator = '\\n'\n lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)]\n out = line_separator.join(lines)\n\n return out", "has_branch": true, "total_branches": 2} {"prompt_id": 546, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "compress", "focal_method_txt": "def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str:\n \"\"\"\n Compress the given string by returning a shorter one that can be safely used in any context (like URL) and\n restored back to its original state using `decompress()`.\n\n **Bear in mind:**\n Besides the provided `compression_level`, the compression result (how much the string is actually compressed\n by resulting into a shorter string) depends on 2 factors:\n\n 1. The amount of data (string size): short strings might not provide a significant compression result\\\n or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\\\n into the compressed string in order to be able to restore it later on)\\\n\n 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\\\n compression result is obtained when the string contains several recurring char sequences (like in the example).\n\n Behind the scenes this method makes use of the standard Python's zlib and base64 libraries.\n\n *Examples:*\n\n >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments)\n >>> # \"original\" will be a string with 169 chars:\n >>> original = ' '.join(['word n{}'.format(n) for n in range(20)])\n >>> # \"compressed\" will be a string of 88 chars\n >>> compressed = compress(original)\n\n :param input_string: String to compress (must be not empty or a ValueError will be raised).\n :type input_string: str\n :param encoding: String encoding (default to \"utf-8\").\n :type encoding: str\n :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9.\n :type compression_level: int\n :return: Compressed string.\n \"\"\"\n return __StringCompressor.compress(input_string, encoding, compression_level)", "focal_method_lines": [560, 594], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str:\n \"\"\"\n Compress the given string by returning a shorter one that can be safely used in any context (like URL) and\n restored back to its original state using `decompress()`.\n\n **Bear in mind:**\n Besides the provided `compression_level`, the compression result (how much the string is actually compressed\n by resulting into a shorter string) depends on 2 factors:\n\n 1. The amount of data (string size): short strings might not provide a significant compression result\\\n or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\\\n into the compressed string in order to be able to restore it later on)\\\n\n 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\\\n compression result is obtained when the string contains several recurring char sequences (like in the example).\n\n Behind the scenes this method makes use of the standard Python's zlib and base64 libraries.\n\n *Examples:*\n\n >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments)\n >>> # \"original\" will be a string with 169 chars:\n >>> original = ' '.join(['word n{}'.format(n) for n in range(20)])\n >>> # \"compressed\" will be a string of 88 chars\n >>> compressed = compress(original)\n\n :param input_string: String to compress (must be not empty or a ValueError will be raised).\n :type input_string: str\n :param encoding: String encoding (default to \"utf-8\").\n :type encoding: str\n :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9.\n :type compression_level: int\n :return: Compressed string.\n \"\"\"\n return __StringCompressor.compress(input_string, encoding, compression_level)", "has_branch": false, "total_branches": 0} {"prompt_id": 547, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "decompress", "focal_method_txt": "def decompress(input_string: str, encoding: str = 'utf-8') -> str:\n \"\"\"\n Restore a previously compressed string (obtained using `compress()`) back to its original state.\n\n :param input_string: String to restore.\n :type input_string: str\n :param encoding: Original string encoding.\n :type encoding: str\n :return: Decompressed string.\n \"\"\"\n return __StringCompressor.decompress(input_string, encoding)", "focal_method_lines": [597, 607], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef decompress(input_string: str, encoding: str = 'utf-8') -> str:\n \"\"\"\n Restore a previously compressed string (obtained using `compress()`) back to its original state.\n\n :param input_string: String to restore.\n :type input_string: str\n :param encoding: Original string encoding.\n :type encoding: str\n :return: Decompressed string.\n \"\"\"\n return __StringCompressor.decompress(input_string, encoding)", "has_branch": false, "total_branches": 0} {"prompt_id": 548, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "roman_encode", "focal_method_txt": "def roman_encode(input_number: Union[str, int]) -> str:\n \"\"\"\n Convert the given number/string into a roman number.\n\n The passed input must represents a positive integer in the range 1-3999 (inclusive).\n\n Why this limit? You may be wondering:\n\n 1. zero is forbidden since there is no related representation in roman numbers\n 2. the upper bound 3999 is due to the limitation in the ascii charset\\\n (the higher quantity sign displayable in ascii is \"M\" which is equal to 1000, therefore based on\\\n roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\\\n special \"boxed chars\").\n\n *Examples:*\n\n >>> roman_encode(37) # returns 'XXXVIII'\n >>> roman_encode('2020') # returns 'MMXX'\n\n :param input_number: An integer or a string to be converted.\n :type input_number: Union[str, int]\n :return: Roman number string.\n \"\"\"\n return __RomanNumbers.encode(input_number)", "focal_method_lines": [610, 633], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef roman_encode(input_number: Union[str, int]) -> str:\n \"\"\"\n Convert the given number/string into a roman number.\n\n The passed input must represents a positive integer in the range 1-3999 (inclusive).\n\n Why this limit? You may be wondering:\n\n 1. zero is forbidden since there is no related representation in roman numbers\n 2. the upper bound 3999 is due to the limitation in the ascii charset\\\n (the higher quantity sign displayable in ascii is \"M\" which is equal to 1000, therefore based on\\\n roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\\\n special \"boxed chars\").\n\n *Examples:*\n\n >>> roman_encode(37) # returns 'XXXVIII'\n >>> roman_encode('2020') # returns 'MMXX'\n\n :param input_number: An integer or a string to be converted.\n :type input_number: Union[str, int]\n :return: Roman number string.\n \"\"\"\n return __RomanNumbers.encode(input_number)", "has_branch": false, "total_branches": 0} {"prompt_id": 549, "project": "string_utils", "module": "string_utils.manipulation", "class": "", "method": "roman_decode", "focal_method_txt": "def roman_decode(input_string: str) -> int:\n \"\"\"\n Decode a roman number string into an integer if the provided string is valid.\n\n *Example:*\n\n >>> roman_decode('VII') # returns 7\n\n :param input_string: (Assumed) Roman number\n :type input_string: str\n :return: Integer value\n \"\"\"\n return __RomanNumbers.decode(input_string)", "focal_method_lines": [636, 648], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\ndef roman_decode(input_string: str) -> int:\n \"\"\"\n Decode a roman number string into an integer if the provided string is valid.\n\n *Example:*\n\n >>> roman_decode('VII') # returns 7\n\n :param input_string: (Assumed) Roman number\n :type input_string: str\n :return: Integer value\n \"\"\"\n return __RomanNumbers.decode(input_string)", "has_branch": false, "total_branches": 0} {"prompt_id": 550, "project": "string_utils", "module": "string_utils.manipulation", "class": "__StringFormatter", "method": "__init__", "focal_method_txt": " def __init__(self, input_string):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string", "focal_method_lines": [212, 216], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\nclass __StringFormatter:\n\n def __init__(self, input_string):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string", "has_branch": true, "total_branches": 2} {"prompt_id": 551, "project": "string_utils", "module": "string_utils.manipulation", "class": "__StringFormatter", "method": "format", "focal_method_txt": " def format(self) -> str:\n # map of temporary placeholders\n placeholders = {}\n out = self.input_string\n\n # looks for url or email and updates placeholders map with found values\n placeholders.update({self.__placeholder_key(): m[0] for m in URLS_RE.findall(out)})\n placeholders.update({self.__placeholder_key(): m for m in EMAILS_RE.findall(out)})\n\n # replace original value with the placeholder key\n for p in placeholders:\n out = out.replace(placeholders[p], p, 1)\n\n out = PRETTIFY_RE['UPPERCASE_FIRST_LETTER'].sub(self.__uppercase_first_char, out)\n out = PRETTIFY_RE['DUPLICATES'].sub(self.__remove_duplicates, out)\n out = PRETTIFY_RE['RIGHT_SPACE'].sub(self.__ensure_right_space_only, out)\n out = PRETTIFY_RE['LEFT_SPACE'].sub(self.__ensure_left_space_only, out)\n out = PRETTIFY_RE['SPACES_AROUND'].sub(self.__ensure_spaces_around, out)\n out = PRETTIFY_RE['SPACES_INSIDE'].sub(self.__remove_internal_spaces, out)\n out = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(self.__uppercase_first_letter_after_sign, out)\n out = PRETTIFY_RE['SAXON_GENITIVE'].sub(self.__fix_saxon_genitive, out)\n out = out.strip()\n\n # restore placeholder keys with their associated original value\n for p in placeholders:\n out = out.replace(p, placeholders[p], 1)\n\n return out", "focal_method_lines": [249, 276], "in_stack": false, "globals": ["__all__"], "type_context": "import base64\nimport random\nimport unicodedata\nimport zlib\nfrom typing import Union\nfrom uuid import uuid4\nfrom ._regex import *\nfrom .errors import InvalidInputError\nfrom .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string\n\n__all__ = [\n 'camel_case_to_snake',\n 'snake_case_to_camel',\n 'reverse',\n 'shuffle',\n 'strip_html',\n 'prettify',\n 'asciify',\n 'slugify',\n 'booleanize',\n 'strip_margin',\n 'compress',\n 'decompress',\n 'roman_encode',\n 'roman_decode',\n]\n\nclass __StringFormatter:\n\n def __init__(self, input_string):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string\n\n def format(self) -> str:\n # map of temporary placeholders\n placeholders = {}\n out = self.input_string\n\n # looks for url or email and updates placeholders map with found values\n placeholders.update({self.__placeholder_key(): m[0] for m in URLS_RE.findall(out)})\n placeholders.update({self.__placeholder_key(): m for m in EMAILS_RE.findall(out)})\n\n # replace original value with the placeholder key\n for p in placeholders:\n out = out.replace(placeholders[p], p, 1)\n\n out = PRETTIFY_RE['UPPERCASE_FIRST_LETTER'].sub(self.__uppercase_first_char, out)\n out = PRETTIFY_RE['DUPLICATES'].sub(self.__remove_duplicates, out)\n out = PRETTIFY_RE['RIGHT_SPACE'].sub(self.__ensure_right_space_only, out)\n out = PRETTIFY_RE['LEFT_SPACE'].sub(self.__ensure_left_space_only, out)\n out = PRETTIFY_RE['SPACES_AROUND'].sub(self.__ensure_spaces_around, out)\n out = PRETTIFY_RE['SPACES_INSIDE'].sub(self.__remove_internal_spaces, out)\n out = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(self.__uppercase_first_letter_after_sign, out)\n out = PRETTIFY_RE['SAXON_GENITIVE'].sub(self.__fix_saxon_genitive, out)\n out = out.strip()\n\n # restore placeholder keys with their associated original value\n for p in placeholders:\n out = out.replace(p, placeholders[p], 1)\n\n return out", "has_branch": true, "total_branches": 2} {"prompt_id": 552, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_integer", "focal_method_txt": "def is_integer(input_string: str) -> bool:\n \"\"\"\n Checks whether the given string represents an integer or not.\n\n An integer may be signed or unsigned or use a \"scientific notation\".\n\n *Examples:*\n\n >>> is_integer('42') # returns true\n >>> is_integer('42.0') # returns false\n\n :param input_string: String to check\n :type input_string: str\n :return: True if integer, false otherwise\n \"\"\"\n return is_number(input_string) and '.' not in input_string", "focal_method_lines": [140, 155], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_integer(input_string: str) -> bool:\n \"\"\"\n Checks whether the given string represents an integer or not.\n\n An integer may be signed or unsigned or use a \"scientific notation\".\n\n *Examples:*\n\n >>> is_integer('42') # returns true\n >>> is_integer('42.0') # returns false\n\n :param input_string: String to check\n :type input_string: str\n :return: True if integer, false otherwise\n \"\"\"\n return is_number(input_string) and '.' not in input_string", "has_branch": false, "total_branches": 0} {"prompt_id": 553, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_decimal", "focal_method_txt": "def is_decimal(input_string: str) -> bool:\n \"\"\"\n Checks whether the given string represents a decimal or not.\n\n A decimal may be signed or unsigned or use a \"scientific notation\".\n\n >>> is_decimal('42.0') # returns true\n >>> is_decimal('42') # returns false\n\n :param input_string: String to check\n :type input_string: str\n :return: True if integer, false otherwise\n \"\"\"\n return is_number(input_string) and '.' in input_string", "focal_method_lines": [158, 171], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_decimal(input_string: str) -> bool:\n \"\"\"\n Checks whether the given string represents a decimal or not.\n\n A decimal may be signed or unsigned or use a \"scientific notation\".\n\n >>> is_decimal('42.0') # returns true\n >>> is_decimal('42') # returns false\n\n :param input_string: String to check\n :type input_string: str\n :return: True if integer, false otherwise\n \"\"\"\n return is_number(input_string) and '.' in input_string", "has_branch": false, "total_branches": 0} {"prompt_id": 554, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_url", "focal_method_txt": "def is_url(input_string: Any, allowed_schemes: Optional[List[str]] = None) -> bool:\n \"\"\"\n Check if a string is a valid url.\n\n *Examples:*\n\n >>> is_url('http://www.mysite.com') # returns true\n >>> is_url('https://mysite.com') # returns true\n >>> is_url('.mysite.com') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).\n :type allowed_schemes: Optional[List[str]]\n :return: True if url, false otherwise\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n valid = URL_RE.match(input_string) is not None\n\n if allowed_schemes:\n return valid and any([input_string.startswith(s) for s in allowed_schemes])\n\n return valid", "focal_method_lines": [176, 200], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_url(input_string: Any, allowed_schemes: Optional[List[str]] = None) -> bool:\n \"\"\"\n Check if a string is a valid url.\n\n *Examples:*\n\n >>> is_url('http://www.mysite.com') # returns true\n >>> is_url('https://mysite.com') # returns true\n >>> is_url('.mysite.com') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).\n :type allowed_schemes: Optional[List[str]]\n :return: True if url, false otherwise\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n valid = URL_RE.match(input_string) is not None\n\n if allowed_schemes:\n return valid and any([input_string.startswith(s) for s in allowed_schemes])\n\n return valid", "has_branch": true, "total_branches": 2} {"prompt_id": 555, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_email", "focal_method_txt": "def is_email(input_string: Any) -> bool:\n \"\"\"\n Check if a string is a valid email.\n\n Reference: https://tools.ietf.org/html/rfc3696#section-3\n\n *Examples:*\n\n >>> is_email('my.email@the-provider.com') # returns true\n >>> is_email('@gmail.com') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if email, false otherwise.\n \"\"\"\n # first simple \"pre check\": it must be a non empty string with max len 320 and cannot start with a dot\n if not is_full_string(input_string) or len(input_string) > 320 or input_string.startswith('.'):\n return False\n\n try:\n # we expect 2 tokens, one before \"@\" and one after, otherwise we have an exception and the email is not valid\n head, tail = input_string.split('@')\n\n # head's size must be <= 64, tail <= 255, head must not start with a dot or contain multiple consecutive dots\n if len(head) > 64 or len(tail) > 255 or head.endswith('.') or ('..' in head):\n return False\n\n # removes escaped spaces, so that later on the test regex will accept the string\n head = head.replace('\\\\ ', '')\n if head.startswith('\"') and head.endswith('\"'):\n head = head.replace(' ', '')[1:-1]\n\n return EMAIL_RE.match(head + '@' + tail) is not None\n\n except ValueError:\n # borderline case in which we have multiple \"@\" signs but the head part is correctly escaped\n if ESCAPED_AT_SIGN.search(input_string) is not None:\n # replace \"@\" with \"a\" in the head\n return is_email(ESCAPED_AT_SIGN.sub('a', input_string))\n\n return False", "focal_method_lines": [203, 243], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_email(input_string: Any) -> bool:\n \"\"\"\n Check if a string is a valid email.\n\n Reference: https://tools.ietf.org/html/rfc3696#section-3\n\n *Examples:*\n\n >>> is_email('my.email@the-provider.com') # returns true\n >>> is_email('@gmail.com') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if email, false otherwise.\n \"\"\"\n # first simple \"pre check\": it must be a non empty string with max len 320 and cannot start with a dot\n if not is_full_string(input_string) or len(input_string) > 320 or input_string.startswith('.'):\n return False\n\n try:\n # we expect 2 tokens, one before \"@\" and one after, otherwise we have an exception and the email is not valid\n head, tail = input_string.split('@')\n\n # head's size must be <= 64, tail <= 255, head must not start with a dot or contain multiple consecutive dots\n if len(head) > 64 or len(tail) > 255 or head.endswith('.') or ('..' in head):\n return False\n\n # removes escaped spaces, so that later on the test regex will accept the string\n head = head.replace('\\\\ ', '')\n if head.startswith('\"') and head.endswith('\"'):\n head = head.replace(' ', '')[1:-1]\n\n return EMAIL_RE.match(head + '@' + tail) is not None\n\n except ValueError:\n # borderline case in which we have multiple \"@\" signs but the head part is correctly escaped\n if ESCAPED_AT_SIGN.search(input_string) is not None:\n # replace \"@\" with \"a\" in the head\n return is_email(ESCAPED_AT_SIGN.sub('a', input_string))\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 556, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_credit_card", "focal_method_txt": "def is_credit_card(input_string: Any, card_type: str = None) -> bool:\n \"\"\"\n Checks if a string is a valid credit card number.\n If card type is provided then it checks against that specific type only,\n otherwise any known credit card number will be accepted.\n\n Supported card types are the following:\n\n - VISA\n - MASTERCARD\n - AMERICAN_EXPRESS\n - DINERS_CLUB\n - DISCOVER\n - JCB\n\n :param input_string: String to check.\n :type input_string: str\n :param card_type: Card type. Default to None (any card).\n :type card_type: str\n\n :return: True if credit card, false otherwise.\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n if card_type:\n if card_type not in CREDIT_CARDS:\n raise KeyError(\n 'Invalid card type \"{}\". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys()))\n )\n return CREDIT_CARDS[card_type].match(input_string) is not None\n\n for c in CREDIT_CARDS:\n if CREDIT_CARDS[c].match(input_string) is not None:\n return True\n\n return False", "focal_method_lines": [246, 282], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_credit_card(input_string: Any, card_type: str = None) -> bool:\n \"\"\"\n Checks if a string is a valid credit card number.\n If card type is provided then it checks against that specific type only,\n otherwise any known credit card number will be accepted.\n\n Supported card types are the following:\n\n - VISA\n - MASTERCARD\n - AMERICAN_EXPRESS\n - DINERS_CLUB\n - DISCOVER\n - JCB\n\n :param input_string: String to check.\n :type input_string: str\n :param card_type: Card type. Default to None (any card).\n :type card_type: str\n\n :return: True if credit card, false otherwise.\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n if card_type:\n if card_type not in CREDIT_CARDS:\n raise KeyError(\n 'Invalid card type \"{}\". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys()))\n )\n return CREDIT_CARDS[card_type].match(input_string) is not None\n\n for c in CREDIT_CARDS:\n if CREDIT_CARDS[c].match(input_string) is not None:\n return True\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 557, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_json", "focal_method_txt": "def is_json(input_string: Any) -> bool:\n \"\"\"\n Check if a string is a valid json.\n\n *Examples:*\n\n >>> is_json('{\"name\": \"Peter\"}') # returns true\n >>> is_json('[1, 2, 3]') # returns true\n >>> is_json('{nope}') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if json, false otherwise\n \"\"\"\n if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None:\n try:\n return isinstance(json.loads(input_string), (dict, list))\n except (TypeError, ValueError, OverflowError):\n pass\n\n return False", "focal_method_lines": [344, 364], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_json(input_string: Any) -> bool:\n \"\"\"\n Check if a string is a valid json.\n\n *Examples:*\n\n >>> is_json('{\"name\": \"Peter\"}') # returns true\n >>> is_json('[1, 2, 3]') # returns true\n >>> is_json('{nope}') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if json, false otherwise\n \"\"\"\n if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None:\n try:\n return isinstance(json.loads(input_string), (dict, list))\n except (TypeError, ValueError, OverflowError):\n pass\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 558, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_ip_v4", "focal_method_txt": "def is_ip_v4(input_string: Any) -> bool:\n \"\"\"\n Checks if a string is a valid ip v4.\n\n *Examples:*\n\n >>> is_ip_v4('255.200.100.75') # returns true\n >>> is_ip_v4('nope') # returns false (not an ip)\n >>> is_ip_v4('255.200.100.999') # returns false (999 is out of range)\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if an ip v4, false otherwise.\n \"\"\"\n if not is_full_string(input_string) or SHALLOW_IP_V4_RE.match(input_string) is None:\n return False\n\n # checks that each entry in the ip is in the valid range (0 to 255)\n for token in input_string.split('.'):\n if not (0 <= int(token) <= 255):\n return False\n\n return True", "focal_method_lines": [392, 414], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_ip_v4(input_string: Any) -> bool:\n \"\"\"\n Checks if a string is a valid ip v4.\n\n *Examples:*\n\n >>> is_ip_v4('255.200.100.75') # returns true\n >>> is_ip_v4('nope') # returns false (not an ip)\n >>> is_ip_v4('255.200.100.999') # returns false (999 is out of range)\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if an ip v4, false otherwise.\n \"\"\"\n if not is_full_string(input_string) or SHALLOW_IP_V4_RE.match(input_string) is None:\n return False\n\n # checks that each entry in the ip is in the valid range (0 to 255)\n for token in input_string.split('.'):\n if not (0 <= int(token) <= 255):\n return False\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 559, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_ip", "focal_method_txt": "def is_ip(input_string: Any) -> bool:\n \"\"\"\n Checks if a string is a valid ip (either v4 or v6).\n\n *Examples:*\n\n >>> is_ip('255.200.100.75') # returns true\n >>> is_ip('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true\n >>> is_ip('1.2.3') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if an ip, false otherwise.\n \"\"\"\n return is_ip_v6(input_string) or is_ip_v4(input_string)", "focal_method_lines": [433, 447], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_ip(input_string: Any) -> bool:\n \"\"\"\n Checks if a string is a valid ip (either v4 or v6).\n\n *Examples:*\n\n >>> is_ip('255.200.100.75') # returns true\n >>> is_ip('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true\n >>> is_ip('1.2.3') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :return: True if an ip, false otherwise.\n \"\"\"\n return is_ip_v6(input_string) or is_ip_v4(input_string)", "has_branch": false, "total_branches": 0} {"prompt_id": 560, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_palindrome", "focal_method_txt": "def is_palindrome(input_string: Any, ignore_spaces: bool = False, ignore_case: bool = False) -> bool:\n \"\"\"\n Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n *Examples:*\n\n >>> is_palindrome('LOL') # returns true\n >>> is_palindrome('Lol') # returns false\n >>> is_palindrome('Lol', ignore_case=True) # returns true\n >>> is_palindrome('ROTFL') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :param ignore_spaces: False if white spaces matter (default), true otherwise.\n :type ignore_spaces: bool\n :param ignore_case: False if char case matters (default), true otherwise.\n :type ignore_case: bool\n :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\\\n False otherwise\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n if ignore_spaces:\n input_string = SPACES_RE.sub('', input_string)\n\n string_len = len(input_string)\n\n # Traverse the string one char at step, and for each step compares the\n # \"head_char\" (the one on the left of the string) to the \"tail_char\" (the one on the right).\n # In this way we avoid to manipulate the whole string in advance if not necessary and provide a faster\n # algorithm which can scale very well for long strings.\n for index in range(string_len):\n head_char = input_string[index]\n tail_char = input_string[string_len - index - 1]\n\n if ignore_case:\n head_char = head_char.lower()\n tail_char = tail_char.lower()\n\n if head_char != tail_char:\n return False\n\n return True", "focal_method_lines": [450, 493], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\ndef is_palindrome(input_string: Any, ignore_spaces: bool = False, ignore_case: bool = False) -> bool:\n \"\"\"\n Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n *Examples:*\n\n >>> is_palindrome('LOL') # returns true\n >>> is_palindrome('Lol') # returns false\n >>> is_palindrome('Lol', ignore_case=True) # returns true\n >>> is_palindrome('ROTFL') # returns false\n\n :param input_string: String to check.\n :type input_string: str\n :param ignore_spaces: False if white spaces matter (default), true otherwise.\n :type ignore_spaces: bool\n :param ignore_case: False if char case matters (default), true otherwise.\n :type ignore_case: bool\n :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\\\n False otherwise\n \"\"\"\n if not is_full_string(input_string):\n return False\n\n if ignore_spaces:\n input_string = SPACES_RE.sub('', input_string)\n\n string_len = len(input_string)\n\n # Traverse the string one char at step, and for each step compares the\n # \"head_char\" (the one on the left of the string) to the \"tail_char\" (the one on the right).\n # In this way we avoid to manipulate the whole string in advance if not necessary and provide a faster\n # algorithm which can scale very well for long strings.\n for index in range(string_len):\n head_char = input_string[index]\n tail_char = input_string[string_len - index - 1]\n\n if ignore_case:\n head_char = head_char.lower()\n tail_char = tail_char.lower()\n\n if head_char != tail_char:\n return False\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 561, "project": "string_utils", "module": "string_utils.validation", "class": "", "method": "is_isbn", "focal_method_txt": "def is_isbn(input_string: str, normalize: bool = True) -> bool:\n \"\"\"\n Checks if the given string represents a valid ISBN (International Standard Book Number).\n By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this\n function with `normalize=False` only digit-only strings will pass the validation.\n\n *Examples:*\n\n >>> is_isbn('9780312498580') # returns true\n >>> is_isbn('1506715214') # returns true\n\n :param input_string: String to check.\n :param normalize: True to ignore hyphens (\"-\") in the string (default), false otherwise.\n :return: True if valid ISBN (10 or 13), false otherwise.\n \"\"\"\n checker = __ISBNChecker(input_string, normalize)\n return checker.is_isbn_13() or checker.is_isbn_10()", "focal_method_lines": [640, 656], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\nclass __ISBNChecker:\n\n def __init__(self, input_string: str, normalize: bool = True):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string.replace('-', '') if normalize else input_string\n\ndef is_isbn(input_string: str, normalize: bool = True) -> bool:\n \"\"\"\n Checks if the given string represents a valid ISBN (International Standard Book Number).\n By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this\n function with `normalize=False` only digit-only strings will pass the validation.\n\n *Examples:*\n\n >>> is_isbn('9780312498580') # returns true\n >>> is_isbn('1506715214') # returns true\n\n :param input_string: String to check.\n :param normalize: True to ignore hyphens (\"-\") in the string (default), false otherwise.\n :return: True if valid ISBN (10 or 13), false otherwise.\n \"\"\"\n checker = __ISBNChecker(input_string, normalize)\n return checker.is_isbn_13() or checker.is_isbn_10()", "has_branch": false, "total_branches": 0} {"prompt_id": 562, "project": "string_utils", "module": "string_utils.validation", "class": "__ISBNChecker", "method": "is_isbn_13", "focal_method_txt": " def is_isbn_13(self) -> bool:\n if len(self.input_string) == 13:\n product = 0\n\n try:\n for index, digit in enumerate(self.input_string):\n weight = 1 if (index % 2 == 0) else 3\n product += int(digit) * weight\n\n return product % 10 == 0\n\n except ValueError:\n pass\n\n return False", "focal_method_lines": [48, 62], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\nclass __ISBNChecker:\n\n def __init__(self, input_string: str, normalize: bool = True):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string.replace('-', '') if normalize else input_string\n\n def is_isbn_13(self) -> bool:\n if len(self.input_string) == 13:\n product = 0\n\n try:\n for index, digit in enumerate(self.input_string):\n weight = 1 if (index % 2 == 0) else 3\n product += int(digit) * weight\n\n return product % 10 == 0\n\n except ValueError:\n pass\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 563, "project": "string_utils", "module": "string_utils.validation", "class": "__ISBNChecker", "method": "is_isbn_10", "focal_method_txt": " def is_isbn_10(self) -> bool:\n if len(self.input_string) == 10:\n product = 0\n\n try:\n for index, digit in enumerate(self.input_string):\n product += int(digit) * (index + 1)\n\n return product % 11 == 0\n\n except ValueError:\n pass\n\n return False", "focal_method_lines": [64, 77], "in_stack": false, "globals": ["__all__"], "type_context": "import json\nimport string\nfrom typing import Any, Optional, List\nfrom ._regex import *\nfrom .errors import InvalidInputError\n\n__all__ = [\n 'is_string',\n 'is_full_string',\n 'is_number',\n 'is_integer',\n 'is_decimal',\n 'is_url',\n 'is_email',\n 'is_credit_card',\n 'is_camel_case',\n 'is_snake_case',\n 'is_json',\n 'is_uuid',\n 'is_ip_v4',\n 'is_ip_v6',\n 'is_ip',\n 'is_isbn_10',\n 'is_isbn_13',\n 'is_isbn',\n 'is_palindrome',\n 'is_pangram',\n 'is_isogram',\n 'is_slug',\n 'contains_html',\n 'words_count',\n]\n\nclass __ISBNChecker:\n\n def __init__(self, input_string: str, normalize: bool = True):\n if not is_string(input_string):\n raise InvalidInputError(input_string)\n\n self.input_string = input_string.replace('-', '') if normalize else input_string\n\n def is_isbn_10(self) -> bool:\n if len(self.input_string) == 10:\n product = 0\n\n try:\n for index, digit in enumerate(self.input_string):\n product += int(digit) * (index + 1)\n\n return product % 11 == 0\n\n except ValueError:\n pass\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 564, "project": "sty", "module": "sty.lib", "class": "", "method": "mute", "focal_method_txt": "def mute(*objects: Register) -> None:\n \"\"\"\n Use this function to mute multiple register-objects at once.\n\n :param objects: Pass multiple register-objects to the function.\n \"\"\"\n err = ValueError(\n \"The mute() method can only be used with objects that inherit \"\n \"from the 'Register class'.\"\n )\n for obj in objects:\n if not isinstance(obj, Register):\n raise err\n obj.mute()", "focal_method_lines": [3, 16], "in_stack": false, "globals": [], "type_context": "from .primitive import Register\n\n\n\ndef mute(*objects: Register) -> None:\n \"\"\"\n Use this function to mute multiple register-objects at once.\n\n :param objects: Pass multiple register-objects to the function.\n \"\"\"\n err = ValueError(\n \"The mute() method can only be used with objects that inherit \"\n \"from the 'Register class'.\"\n )\n for obj in objects:\n if not isinstance(obj, Register):\n raise err\n obj.mute()", "has_branch": true, "total_branches": 2} {"prompt_id": 565, "project": "sty", "module": "sty.lib", "class": "", "method": "unmute", "focal_method_txt": "def unmute(*objects: Register) -> None:\n \"\"\"\n Use this function to unmute multiple register-objects at once.\n\n :param objects: Pass multiple register-objects to the function.\n \"\"\"\n err = ValueError(\n \"The unmute() method can only be used with objects that inherit \"\n \"from the 'Register class'.\"\n )\n for obj in objects:\n if not isinstance(obj, Register):\n raise err\n obj.unmute()", "focal_method_lines": [19, 32], "in_stack": false, "globals": [], "type_context": "from .primitive import Register\n\n\n\ndef unmute(*objects: Register) -> None:\n \"\"\"\n Use this function to unmute multiple register-objects at once.\n\n :param objects: Pass multiple register-objects to the function.\n \"\"\"\n err = ValueError(\n \"The unmute() method can only be used with objects that inherit \"\n \"from the 'Register class'.\"\n )\n for obj in objects:\n if not isinstance(obj, Register):\n raise err\n obj.unmute()", "has_branch": true, "total_branches": 2} {"prompt_id": 566, "project": "sty", "module": "sty.primitive", "class": "Style", "method": "__new__", "focal_method_txt": " def __new__(cls, *rules: StylingRule, value: str = \"\") -> \"Style\":\n new_cls = str.__new__(cls, value) # type: ignore\n setattr(new_cls, \"rules\", rules)\n return new_cls", "focal_method_lines": [33, 36], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Style(str):\n\n rules: Iterable[StylingRule]\n\n def __new__(cls, *rules: StylingRule, value: str = \"\") -> \"Style\":\n new_cls = str.__new__(cls, value) # type: ignore\n setattr(new_cls, \"rules\", rules)\n return new_cls", "has_branch": false, "total_branches": 0} {"prompt_id": 567, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "__init__", "focal_method_txt": " def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)", "focal_method_lines": [71, 75], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)", "has_branch": false, "total_branches": 0} {"prompt_id": 568, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "__setattr__", "focal_method_txt": " def __setattr__(self, name: str, value: Style):\n\n if isinstance(value, Style):\n\n if self.is_muted:\n rendered_style = Style(*value.rules, value=\"\")\n else:\n rendered, rules = _render_rules(self.renderfuncs, value.rules)\n rendered_style = Style(*rules, value=rendered)\n\n return super().__setattr__(name, rendered_style)\n else:\n # TODO: Why do we need this??? What should be set here?\n return super().__setattr__(name, value)", "focal_method_lines": [77, 90], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def __setattr__(self, name: str, value: Style):\n\n if isinstance(value, Style):\n\n if self.is_muted:\n rendered_style = Style(*value.rules, value=\"\")\n else:\n rendered, rules = _render_rules(self.renderfuncs, value.rules)\n rendered_style = Style(*rules, value=rendered)\n\n return super().__setattr__(name, rendered_style)\n else:\n # TODO: Why do we need this??? What should be set here?\n return super().__setattr__(name, value)", "has_branch": true, "total_branches": 2} {"prompt_id": 569, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "__call__", "focal_method_txt": " def __call__(self, *args: Union[int, str], **kwargs) -> str:\n \"\"\"\n This function is to handle calls such as `fg(42)`, `bg(102, 49, 42)`, `fg('red')`.\n \"\"\"\n\n # Return empty str if object is muted.\n if self.is_muted:\n return \"\"\n\n len_args = len(args)\n\n if len_args == 1:\n\n # If input is an 8bit color code, run 8bit render function.\n if isinstance(args[0], int):\n return self.eightbit_call(*args, **kwargs)\n\n # If input is a string, return attribute with the name that matches\n # input.\n else:\n return getattr(self, args[0])\n\n # If input is an 24bit color code, run 24bit render function.\n elif len_args == 3:\n return self.rgb_call(*args, **kwargs)\n\n else:\n return \"\"", "focal_method_lines": [92, 119], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def __call__(self, *args: Union[int, str], **kwargs) -> str:\n \"\"\"\n This function is to handle calls such as `fg(42)`, `bg(102, 49, 42)`, `fg('red')`.\n \"\"\"\n\n # Return empty str if object is muted.\n if self.is_muted:\n return \"\"\n\n len_args = len(args)\n\n if len_args == 1:\n\n # If input is an 8bit color code, run 8bit render function.\n if isinstance(args[0], int):\n return self.eightbit_call(*args, **kwargs)\n\n # If input is a string, return attribute with the name that matches\n # input.\n else:\n return getattr(self, args[0])\n\n # If input is an 24bit color code, run 24bit render function.\n elif len_args == 3:\n return self.rgb_call(*args, **kwargs)\n\n else:\n return \"\"", "has_branch": true, "total_branches": 2} {"prompt_id": 570, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "set_eightbit_call", "focal_method_txt": " def set_eightbit_call(self, rendertype: Type[RenderType]) -> None:\n \"\"\"\n You can call a register-object directly. A call like this ``fg(144)``\n is a Eightbit-call. With this method you can define the render-type for such calls.\n\n :param rendertype: The new rendertype that is used for Eightbit-calls.\n \"\"\"\n func: Callable = self.renderfuncs[rendertype]\n self.eightbit_call = func", "focal_method_lines": [121, 129], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def set_eightbit_call(self, rendertype: Type[RenderType]) -> None:\n \"\"\"\n You can call a register-object directly. A call like this ``fg(144)``\n is a Eightbit-call. With this method you can define the render-type for such calls.\n\n :param rendertype: The new rendertype that is used for Eightbit-calls.\n \"\"\"\n func: Callable = self.renderfuncs[rendertype]\n self.eightbit_call = func", "has_branch": false, "total_branches": 0} {"prompt_id": 571, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "set_rgb_call", "focal_method_txt": " def set_rgb_call(self, rendertype: Type[RenderType]) -> None:\n \"\"\"\n You can call a register-object directly. A call like this ``fg(10, 42, 255)``\n is a RGB-call. With this method you can define the render-type for such calls.\n\n :param rendertype: The new rendertype that is used for RGB-calls.\n \"\"\"\n func: Callable = self.renderfuncs[rendertype]\n self.rgb_call = func", "focal_method_lines": [131, 139], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def set_rgb_call(self, rendertype: Type[RenderType]) -> None:\n \"\"\"\n You can call a register-object directly. A call like this ``fg(10, 42, 255)``\n is a RGB-call. With this method you can define the render-type for such calls.\n\n :param rendertype: The new rendertype that is used for RGB-calls.\n \"\"\"\n func: Callable = self.renderfuncs[rendertype]\n self.rgb_call = func", "has_branch": false, "total_branches": 0} {"prompt_id": 572, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "set_renderfunc", "focal_method_txt": " def set_renderfunc(self, rendertype: Type[RenderType], func: Callable) -> None:\n \"\"\"\n With this method you can add or replace render-functions for a given register-object:\n\n :param rendertype: The render type for which the new renderfunc is used.\n :param func: The new render function.\n \"\"\"\n # Save new render-func in register\n self.renderfuncs.update({rendertype: func})\n\n # Update style atributes and styles with the new renderfunc.\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "focal_method_lines": [141, 155], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def set_renderfunc(self, rendertype: Type[RenderType], func: Callable) -> None:\n \"\"\"\n With this method you can add or replace render-functions for a given register-object:\n\n :param rendertype: The render type for which the new renderfunc is used.\n :param func: The new render function.\n \"\"\"\n # Save new render-func in register\n self.renderfuncs.update({rendertype: func})\n\n # Update style atributes and styles with the new renderfunc.\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "has_branch": true, "total_branches": 2} {"prompt_id": 573, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "mute", "focal_method_txt": " def mute(self) -> None:\n \"\"\"\n Sometimes it is useful to disable the formatting for a register-object. You can\n do so by invoking this method.\n \"\"\"\n self.is_muted = True\n\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "focal_method_lines": [157, 167], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def mute(self) -> None:\n \"\"\"\n Sometimes it is useful to disable the formatting for a register-object. You can\n do so by invoking this method.\n \"\"\"\n self.is_muted = True\n\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "has_branch": true, "total_branches": 2} {"prompt_id": 574, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "unmute", "focal_method_txt": " def unmute(self) -> None:\n \"\"\"\n Use this method to unmute a previously muted register object.\n \"\"\"\n self.is_muted = False\n\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "focal_method_lines": [169, 178], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def unmute(self) -> None:\n \"\"\"\n Use this method to unmute a previously muted register object.\n \"\"\"\n self.is_muted = False\n\n for attr_name in dir(self):\n val = getattr(self, attr_name)\n if isinstance(val, Style):\n setattr(self, attr_name, val)", "has_branch": true, "total_branches": 2} {"prompt_id": 575, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "as_dict", "focal_method_txt": " def as_dict(self) -> Dict[str, str]:\n \"\"\"\n Export color register as dict.\n \"\"\"\n items: Dict[str, str] = {}\n\n for name in dir(self):\n\n if not name.startswith(\"_\") and isinstance(getattr(self, name), str):\n\n items.update({name: str(getattr(self, name))})\n\n return items", "focal_method_lines": [180, 192], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def as_dict(self) -> Dict[str, str]:\n \"\"\"\n Export color register as dict.\n \"\"\"\n items: Dict[str, str] = {}\n\n for name in dir(self):\n\n if not name.startswith(\"_\") and isinstance(getattr(self, name), str):\n\n items.update({name: str(getattr(self, name))})\n\n return items", "has_branch": true, "total_branches": 2} {"prompt_id": 576, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "as_namedtuple", "focal_method_txt": " def as_namedtuple(self):\n \"\"\"\n Export color register as namedtuple.\n \"\"\"\n d = self.as_dict()\n return namedtuple(\"StyleRegister\", d.keys())(*d.values())", "focal_method_lines": [194, 199], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def as_namedtuple(self):\n \"\"\"\n Export color register as namedtuple.\n \"\"\"\n d = self.as_dict()\n return namedtuple(\"StyleRegister\", d.keys())(*d.values())", "has_branch": false, "total_branches": 0} {"prompt_id": 577, "project": "sty", "module": "sty.primitive", "class": "Register", "method": "copy", "focal_method_txt": " def copy(self) -> \"Register\":\n \"\"\"\n Make a deepcopy of a register-object.\n \"\"\"\n return deepcopy(self)", "focal_method_lines": [201, 205], "in_stack": false, "globals": ["Renderfuncs", "StylingRule"], "type_context": "from collections import namedtuple\nfrom copy import deepcopy\nfrom typing import Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union\nfrom .rendertype import RenderType\n\nRenderfuncs = Dict[Type[RenderType], Callable]\nStylingRule = Union[\"Style\", RenderType]\n\nclass Register:\n\n def __init__(self):\n self.renderfuncs: Renderfuncs = {}\n self.is_muted = False\n self.eightbit_call = lambda x: x\n self.rgb_call = lambda r, g, b: (r, g, b)\n\n def copy(self) -> \"Register\":\n \"\"\"\n Make a deepcopy of a register-object.\n \"\"\"\n return deepcopy(self)", "has_branch": false, "total_branches": 0} {"prompt_id": 578, "project": "thefuck", "module": "thefuck.argument_parser", "class": "Parser", "method": "__init__", "focal_method_txt": " def __init__(self):\n self._parser = ArgumentParser(prog='thefuck', add_help=False)\n self._add_arguments()", "focal_method_lines": [12, 14], "in_stack": false, "globals": [], "type_context": "import sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom .const import ARGUMENT_PLACEHOLDER\nfrom .utils import get_alias\n\n\n\nclass Parser(object):\n\n def __init__(self):\n self._parser = ArgumentParser(prog='thefuck', add_help=False)\n self._add_arguments()", "has_branch": false, "total_branches": 0} {"prompt_id": 579, "project": "thefuck", "module": "thefuck.argument_parser", "class": "Parser", "method": "parse", "focal_method_txt": " def parse(self, argv):\n arguments = self._prepare_arguments(argv[1:])\n return self._parser.parse_args(arguments)", "focal_method_lines": [83, 85], "in_stack": false, "globals": [], "type_context": "import sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom .const import ARGUMENT_PLACEHOLDER\nfrom .utils import get_alias\n\n\n\nclass Parser(object):\n\n def __init__(self):\n self._parser = ArgumentParser(prog='thefuck', add_help=False)\n self._add_arguments()\n\n def parse(self, argv):\n arguments = self._prepare_arguments(argv[1:])\n return self._parser.parse_args(arguments)", "has_branch": false, "total_branches": 0} {"prompt_id": 580, "project": "thefuck", "module": "thefuck.argument_parser", "class": "Parser", "method": "print_usage", "focal_method_txt": " def print_usage(self):\n self._parser.print_usage(sys.stderr)", "focal_method_lines": [87, 88], "in_stack": false, "globals": [], "type_context": "import sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom .const import ARGUMENT_PLACEHOLDER\nfrom .utils import get_alias\n\n\n\nclass Parser(object):\n\n def __init__(self):\n self._parser = ArgumentParser(prog='thefuck', add_help=False)\n self._add_arguments()\n\n def print_usage(self):\n self._parser.print_usage(sys.stderr)", "has_branch": false, "total_branches": 0} {"prompt_id": 581, "project": "thefuck", "module": "thefuck.argument_parser", "class": "Parser", "method": "print_help", "focal_method_txt": " def print_help(self):\n self._parser.print_help(sys.stderr)", "focal_method_lines": [90, 91], "in_stack": false, "globals": [], "type_context": "import sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom .const import ARGUMENT_PLACEHOLDER\nfrom .utils import get_alias\n\n\n\nclass Parser(object):\n\n def __init__(self):\n self._parser = ArgumentParser(prog='thefuck', add_help=False)\n self._add_arguments()\n\n def print_help(self):\n self._parser.print_help(sys.stderr)", "has_branch": false, "total_branches": 0} {"prompt_id": 582, "project": "thefuck", "module": "thefuck.conf", "class": "Settings", "method": "init", "focal_method_txt": " def init(self, args=None):\n \"\"\"Fills `settings` with values from `settings.py` and env.\"\"\"\n from .logs import exception\n\n self._setup_user_dir()\n self._init_settings_file()\n\n try:\n self.update(self._settings_from_file())\n except Exception:\n exception(\"Can't load settings from file\", sys.exc_info())\n\n try:\n self.update(self._settings_from_env())\n except Exception:\n exception(\"Can't load settings from env\", sys.exc_info())\n\n self.update(self._settings_from_args(args))", "focal_method_lines": [16, 33], "in_stack": false, "globals": ["settings"], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom warnings import warn\nfrom six import text_type\nfrom . import const\nfrom .system import Path\n\nsettings = Settings(const.DEFAULT_SETTINGS)\n\nclass Settings(dict):\n\n def init(self, args=None):\n \"\"\"Fills `settings` with values from `settings.py` and env.\"\"\"\n from .logs import exception\n\n self._setup_user_dir()\n self._init_settings_file()\n\n try:\n self.update(self._settings_from_file())\n except Exception:\n exception(\"Can't load settings from file\", sys.exc_info())\n\n try:\n self.update(self._settings_from_env())\n except Exception:\n exception(\"Can't load settings from env\", sys.exc_info())\n\n self.update(self._settings_from_args(args))", "has_branch": false, "total_branches": 0} {"prompt_id": 583, "project": "thefuck", "module": "thefuck.corrector", "class": "", "method": "get_loaded_rules", "focal_method_txt": "def get_loaded_rules(rules_paths):\n \"\"\"Yields all available rules.\n\n :type rules_paths: [Path]\n :rtype: Iterable[Rule]\n\n \"\"\"\n for path in rules_paths:\n if path.name != '__init__.py':\n rule = Rule.from_path(path)\n if rule and rule.is_enabled:\n yield rule", "focal_method_lines": [7, 18], "in_stack": false, "globals": [], "type_context": "import sys\nfrom .conf import settings\nfrom .types import Rule\nfrom .system import Path\nfrom . import logs\n\n\n\ndef get_loaded_rules(rules_paths):\n \"\"\"Yields all available rules.\n\n :type rules_paths: [Path]\n :rtype: Iterable[Rule]\n\n \"\"\"\n for path in rules_paths:\n if path.name != '__init__.py':\n rule = Rule.from_path(path)\n if rule and rule.is_enabled:\n yield rule", "has_branch": true, "total_branches": 2} {"prompt_id": 584, "project": "thefuck", "module": "thefuck.corrector", "class": "", "method": "get_rules_import_paths", "focal_method_txt": "def get_rules_import_paths():\n \"\"\"Yields all rules import paths.\n\n :rtype: Iterable[Path]\n\n \"\"\"\n # Bundled rules:\n yield Path(__file__).parent.joinpath('rules')\n # Rules defined by user:\n yield settings.user_dir.joinpath('rules')\n # Packages with third-party rules:\n for path in sys.path:\n for contrib_module in Path(path).glob('thefuck_contrib_*'):\n contrib_rules = contrib_module.joinpath('rules')\n if contrib_rules.is_dir():\n yield contrib_rules", "focal_method_lines": [21, 36], "in_stack": false, "globals": [], "type_context": "import sys\nfrom .conf import settings\nfrom .types import Rule\nfrom .system import Path\nfrom . import logs\n\n\n\ndef get_rules_import_paths():\n \"\"\"Yields all rules import paths.\n\n :rtype: Iterable[Path]\n\n \"\"\"\n # Bundled rules:\n yield Path(__file__).parent.joinpath('rules')\n # Rules defined by user:\n yield settings.user_dir.joinpath('rules')\n # Packages with third-party rules:\n for path in sys.path:\n for contrib_module in Path(path).glob('thefuck_contrib_*'):\n contrib_rules = contrib_module.joinpath('rules')\n if contrib_rules.is_dir():\n yield contrib_rules", "has_branch": true, "total_branches": 2} {"prompt_id": 585, "project": "thefuck", "module": "thefuck.corrector", "class": "", "method": "get_rules", "focal_method_txt": "def get_rules():\n \"\"\"Returns all enabled rules.\n\n :rtype: [Rule]\n\n \"\"\"\n paths = [rule_path for path in get_rules_import_paths()\n for rule_path in sorted(path.glob('*.py'))]\n return sorted(get_loaded_rules(paths),\n key=lambda rule: rule.priority)", "focal_method_lines": [39, 47], "in_stack": false, "globals": [], "type_context": "import sys\nfrom .conf import settings\nfrom .types import Rule\nfrom .system import Path\nfrom . import logs\n\n\n\ndef get_rules():\n \"\"\"Returns all enabled rules.\n\n :rtype: [Rule]\n\n \"\"\"\n paths = [rule_path for path in get_rules_import_paths()\n for rule_path in sorted(path.glob('*.py'))]\n return sorted(get_loaded_rules(paths),\n key=lambda rule: rule.priority)", "has_branch": false, "total_branches": 0} {"prompt_id": 586, "project": "thefuck", "module": "thefuck.corrector", "class": "", "method": "organize_commands", "focal_method_txt": "def organize_commands(corrected_commands):\n \"\"\"Yields sorted commands without duplicates.\n\n :type corrected_commands: Iterable[thefuck.types.CorrectedCommand]\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n \"\"\"\n try:\n first_command = next(corrected_commands)\n yield first_command\n except StopIteration:\n return\n\n without_duplicates = {\n command for command in sorted(\n corrected_commands, key=lambda command: command.priority)\n if command != first_command}\n\n sorted_commands = sorted(\n without_duplicates,\n key=lambda corrected_command: corrected_command.priority)\n\n logs.debug(u'Corrected commands: {}'.format(\n ', '.join(u'{}'.format(cmd) for cmd in [first_command] + sorted_commands)))\n\n for command in sorted_commands:\n yield command", "focal_method_lines": [51, 77], "in_stack": false, "globals": [], "type_context": "import sys\nfrom .conf import settings\nfrom .types import Rule\nfrom .system import Path\nfrom . import logs\n\n\n\ndef organize_commands(corrected_commands):\n \"\"\"Yields sorted commands without duplicates.\n\n :type corrected_commands: Iterable[thefuck.types.CorrectedCommand]\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n \"\"\"\n try:\n first_command = next(corrected_commands)\n yield first_command\n except StopIteration:\n return\n\n without_duplicates = {\n command for command in sorted(\n corrected_commands, key=lambda command: command.priority)\n if command != first_command}\n\n sorted_commands = sorted(\n without_duplicates,\n key=lambda corrected_command: corrected_command.priority)\n\n logs.debug(u'Corrected commands: {}'.format(\n ', '.join(u'{}'.format(cmd) for cmd in [first_command] + sorted_commands)))\n\n for command in sorted_commands:\n yield command", "has_branch": true, "total_branches": 2} {"prompt_id": 587, "project": "thefuck", "module": "thefuck.corrector", "class": "", "method": "get_corrected_commands", "focal_method_txt": "def get_corrected_commands(command):\n \"\"\"Returns generator with sorted and unique corrected commands.\n\n :type command: thefuck.types.Command\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n \"\"\"\n corrected_commands = (\n corrected for rule in get_rules()\n if rule.is_match(command)\n for corrected in rule.get_corrected_commands(command))\n return organize_commands(corrected_commands)", "focal_method_lines": [80, 91], "in_stack": false, "globals": [], "type_context": "import sys\nfrom .conf import settings\nfrom .types import Rule\nfrom .system import Path\nfrom . import logs\n\n\n\ndef get_corrected_commands(command):\n \"\"\"Returns generator with sorted and unique corrected commands.\n\n :type command: thefuck.types.Command\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n \"\"\"\n corrected_commands = (\n corrected for rule in get_rules()\n if rule.is_match(command)\n for corrected in rule.get_corrected_commands(command))\n return organize_commands(corrected_commands)", "has_branch": false, "total_branches": 0} {"prompt_id": 588, "project": "thefuck", "module": "thefuck.entrypoints.fix_command", "class": "", "method": "fix_command", "focal_method_txt": "def fix_command(known_args):\n \"\"\"Fixes previous command. Used when `thefuck` called without arguments.\"\"\"\n settings.init(known_args)\n with logs.debug_time('Total'):\n logs.debug(u'Run with settings: {}'.format(pformat(settings)))\n raw_command = _get_raw_command(known_args)\n\n try:\n command = types.Command.from_raw_script(raw_command)\n except EmptyCommand:\n logs.debug('Empty command, nothing to do')\n return\n\n corrected_commands = get_corrected_commands(command)\n selected_command = select_command(corrected_commands)\n\n if selected_command:\n selected_command.run(command)\n else:\n sys.exit(1)", "focal_method_lines": [28, 47], "in_stack": false, "globals": [], "type_context": "from pprint import pformat\nimport os\nimport sys\nfrom difflib import SequenceMatcher\nfrom .. import logs, types, const\nfrom ..conf import settings\nfrom ..corrector import get_corrected_commands\nfrom ..exceptions import EmptyCommand\nfrom ..ui import select_command\nfrom ..utils import get_alias, get_all_executables\n\n\n\ndef fix_command(known_args):\n \"\"\"Fixes previous command. Used when `thefuck` called without arguments.\"\"\"\n settings.init(known_args)\n with logs.debug_time('Total'):\n logs.debug(u'Run with settings: {}'.format(pformat(settings)))\n raw_command = _get_raw_command(known_args)\n\n try:\n command = types.Command.from_raw_script(raw_command)\n except EmptyCommand:\n logs.debug('Empty command, nothing to do')\n return\n\n corrected_commands = get_corrected_commands(command)\n selected_command = select_command(corrected_commands)\n\n if selected_command:\n selected_command.run(command)\n else:\n sys.exit(1)", "has_branch": true, "total_branches": 2} {"prompt_id": 589, "project": "thefuck", "module": "thefuck.entrypoints.main", "class": "", "method": "main", "focal_method_txt": "def main():\n parser = Parser()\n known_args = parser.parse(sys.argv)\n\n if known_args.help:\n parser.print_help()\n elif known_args.version:\n logs.version(get_installation_info().version,\n sys.version.split()[0], shell.info())\n # It's important to check if an alias is being requested before checking if\n # `TF_HISTORY` is in `os.environ`, otherwise it might mess with subshells.\n # Check https://github.com/nvbn/thefuck/issues/921 for reference\n elif known_args.alias:\n print_alias(known_args)\n elif known_args.command or 'TF_HISTORY' in os.environ:\n fix_command(known_args)\n elif known_args.shell_logger:\n try:\n from .shell_logger import shell_logger # noqa: E402\n except ImportError:\n logs.warn('Shell logger supports only Linux and macOS')\n else:\n shell_logger(known_args.shell_logger)\n else:\n parser.print_usage()", "focal_method_lines": [15, 39], "in_stack": false, "globals": [], "type_context": "from ..system import init_output\nimport os\nimport sys\nfrom .. import logs\nfrom ..argument_parser import Parser\nfrom ..utils import get_installation_info\nfrom ..shells import shell\nfrom .alias import print_alias\nfrom .fix_command import fix_command\n\n\n\ndef main():\n parser = Parser()\n known_args = parser.parse(sys.argv)\n\n if known_args.help:\n parser.print_help()\n elif known_args.version:\n logs.version(get_installation_info().version,\n sys.version.split()[0], shell.info())\n # It's important to check if an alias is being requested before checking if\n # `TF_HISTORY` is in `os.environ`, otherwise it might mess with subshells.\n # Check https://github.com/nvbn/thefuck/issues/921 for reference\n elif known_args.alias:\n print_alias(known_args)\n elif known_args.command or 'TF_HISTORY' in os.environ:\n fix_command(known_args)\n elif known_args.shell_logger:\n try:\n from .shell_logger import shell_logger # noqa: E402\n except ImportError:\n logs.warn('Shell logger supports only Linux and macOS')\n else:\n shell_logger(known_args.shell_logger)\n else:\n parser.print_usage()", "has_branch": true, "total_branches": 2} {"prompt_id": 590, "project": "thefuck", "module": "thefuck.entrypoints.shell_logger", "class": "", "method": "shell_logger", "focal_method_txt": "def shell_logger(output):\n \"\"\"Logs shell output to the `output`.\n\n Works like unix script command with `-f` flag.\n\n \"\"\"\n if not os.environ.get('SHELL'):\n logs.warn(\"Shell logger doesn't support your platform.\")\n sys.exit(1)\n\n fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR)\n os.write(fd, b'\\x00' * const.LOG_SIZE_IN_BYTES)\n buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_WRITE)\n return_code = _spawn(os.environ['SHELL'], partial(_read, buffer))\n\n sys.exit(return_code)", "focal_method_lines": [63, 78], "in_stack": false, "globals": [], "type_context": "import array\nimport fcntl\nfrom functools import partial\nimport mmap\nimport os\nimport pty\nimport signal\nimport sys\nimport termios\nimport tty\nfrom .. import logs, const\n\n\n\ndef shell_logger(output):\n \"\"\"Logs shell output to the `output`.\n\n Works like unix script command with `-f` flag.\n\n \"\"\"\n if not os.environ.get('SHELL'):\n logs.warn(\"Shell logger doesn't support your platform.\")\n sys.exit(1)\n\n fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR)\n os.write(fd, b'\\x00' * const.LOG_SIZE_IN_BYTES)\n buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_WRITE)\n return_code = _spawn(os.environ['SHELL'], partial(_read, buffer))\n\n sys.exit(return_code)", "has_branch": true, "total_branches": 2} {"prompt_id": 591, "project": "thefuck", "module": "thefuck.logs", "class": "", "method": "color", "focal_method_txt": "def color(color_):\n \"\"\"Utility for ability to disabling colored output.\"\"\"\n if settings.no_colors:\n return ''\n else:\n return color_", "focal_method_lines": [11, 16], "in_stack": false, "globals": [], "type_context": "from contextlib import contextmanager\nfrom datetime import datetime\nimport sys\nfrom traceback import format_exception\nimport colorama\nfrom .conf import settings\nfrom . import const\n\n\n\ndef color(color_):\n \"\"\"Utility for ability to disabling colored output.\"\"\"\n if settings.no_colors:\n return ''\n else:\n return color_", "has_branch": true, "total_branches": 2} {"prompt_id": 592, "project": "thefuck", "module": "thefuck.logs", "class": "", "method": "show_corrected_command", "focal_method_txt": "def show_corrected_command(corrected_command):\n sys.stderr.write(u'{prefix}{bold}{script}{reset}{side_effect}\\n'.format(\n prefix=const.USER_COMMAND_MARK,\n script=corrected_command.script,\n side_effect=u' (+side effect)' if corrected_command.side_effect else u'',\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))", "focal_method_lines": [49, 50], "in_stack": false, "globals": [], "type_context": "from contextlib import contextmanager\nfrom datetime import datetime\nimport sys\nfrom traceback import format_exception\nimport colorama\nfrom .conf import settings\nfrom . import const\n\n\n\ndef show_corrected_command(corrected_command):\n sys.stderr.write(u'{prefix}{bold}{script}{reset}{side_effect}\\n'.format(\n prefix=const.USER_COMMAND_MARK,\n script=corrected_command.script,\n side_effect=u' (+side effect)' if corrected_command.side_effect else u'',\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))", "has_branch": false, "total_branches": 0} {"prompt_id": 593, "project": "thefuck", "module": "thefuck.logs", "class": "", "method": "confirm_text", "focal_method_txt": "def confirm_text(corrected_command):\n sys.stderr.write(\n (u'{prefix}{clear}{bold}{script}{reset}{side_effect} '\n u'[{green}enter{reset}/{blue}↑{reset}/{blue}↓{reset}'\n u'/{red}ctrl+c{reset}]').format(\n prefix=const.USER_COMMAND_MARK,\n script=corrected_command.script,\n side_effect=' (+side effect)' if corrected_command.side_effect else '',\n clear='\\033[1K\\r',\n bold=color(colorama.Style.BRIGHT),\n green=color(colorama.Fore.GREEN),\n red=color(colorama.Fore.RED),\n reset=color(colorama.Style.RESET_ALL),\n blue=color(colorama.Fore.BLUE)))", "focal_method_lines": [58, 59], "in_stack": false, "globals": [], "type_context": "from contextlib import contextmanager\nfrom datetime import datetime\nimport sys\nfrom traceback import format_exception\nimport colorama\nfrom .conf import settings\nfrom . import const\n\n\n\ndef confirm_text(corrected_command):\n sys.stderr.write(\n (u'{prefix}{clear}{bold}{script}{reset}{side_effect} '\n u'[{green}enter{reset}/{blue}↑{reset}/{blue}↓{reset}'\n u'/{red}ctrl+c{reset}]').format(\n prefix=const.USER_COMMAND_MARK,\n script=corrected_command.script,\n side_effect=' (+side effect)' if corrected_command.side_effect else '',\n clear='\\033[1K\\r',\n bold=color(colorama.Style.BRIGHT),\n green=color(colorama.Fore.GREEN),\n red=color(colorama.Fore.RED),\n reset=color(colorama.Style.RESET_ALL),\n blue=color(colorama.Fore.BLUE)))", "has_branch": false, "total_branches": 0} {"prompt_id": 594, "project": "thefuck", "module": "thefuck.logs", "class": "", "method": "debug", "focal_method_txt": "def debug(msg):\n if settings.debug:\n sys.stderr.write(u'{blue}{bold}DEBUG:{reset} {msg}\\n'.format(\n msg=msg,\n reset=color(colorama.Style.RESET_ALL),\n blue=color(colorama.Fore.BLUE),\n bold=color(colorama.Style.BRIGHT)))", "focal_method_lines": [74, 76], "in_stack": false, "globals": [], "type_context": "from contextlib import contextmanager\nfrom datetime import datetime\nimport sys\nfrom traceback import format_exception\nimport colorama\nfrom .conf import settings\nfrom . import const\n\n\n\ndef debug(msg):\n if settings.debug:\n sys.stderr.write(u'{blue}{bold}DEBUG:{reset} {msg}\\n'.format(\n msg=msg,\n reset=color(colorama.Style.RESET_ALL),\n blue=color(colorama.Fore.BLUE),\n bold=color(colorama.Style.BRIGHT)))", "has_branch": true, "total_branches": 2} {"prompt_id": 595, "project": "thefuck", "module": "thefuck.logs", "class": "", "method": "how_to_configure_alias", "focal_method_txt": "def how_to_configure_alias(configuration_details):\n print(u\"Seems like {bold}fuck{reset} alias isn't configured!\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))\n\n if configuration_details:\n print(\n u\"Please put {bold}{content}{reset} in your \"\n u\"{bold}{path}{reset} and apply \"\n u\"changes with {bold}{reload}{reset} or restart your shell.\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL),\n **configuration_details._asdict()))\n\n if configuration_details.can_configure_automatically:\n print(\n u\"Or run {bold}fuck{reset} a second time to configure\"\n u\" it automatically.\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))\n\n print(u'More details - https://github.com/nvbn/thefuck#manual-installation')", "focal_method_lines": [92, 113], "in_stack": false, "globals": [], "type_context": "from contextlib import contextmanager\nfrom datetime import datetime\nimport sys\nfrom traceback import format_exception\nimport colorama\nfrom .conf import settings\nfrom . import const\n\n\n\ndef how_to_configure_alias(configuration_details):\n print(u\"Seems like {bold}fuck{reset} alias isn't configured!\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))\n\n if configuration_details:\n print(\n u\"Please put {bold}{content}{reset} in your \"\n u\"{bold}{path}{reset} and apply \"\n u\"changes with {bold}{reload}{reset} or restart your shell.\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL),\n **configuration_details._asdict()))\n\n if configuration_details.can_configure_automatically:\n print(\n u\"Or run {bold}fuck{reset} a second time to configure\"\n u\" it automatically.\".format(\n bold=color(colorama.Style.BRIGHT),\n reset=color(colorama.Style.RESET_ALL)))\n\n print(u'More details - https://github.com/nvbn/thefuck#manual-installation')", "has_branch": true, "total_branches": 2} {"prompt_id": 596, "project": "thefuck", "module": "thefuck.rules.aws_cli", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n mistake = re.search(INVALID_CHOICE, command.output).group(0)\n options = re.findall(OPTIONS, command.output, flags=re.MULTILINE)\n return [replace_argument(command.script, mistake, o) for o in options]", "focal_method_lines": [13, 16], "in_stack": false, "globals": ["INVALID_CHOICE", "OPTIONS"], "type_context": "import re\nfrom thefuck.utils import for_app, replace_argument\n\nINVALID_CHOICE = \"(?<=Invalid choice: ')(.*)(?=', maybe you meant:)\"\nOPTIONS = \"^\\\\s*\\\\*\\\\s(.*)\"\n\ndef get_new_command(command):\n mistake = re.search(INVALID_CHOICE, command.output).group(0)\n options = re.findall(OPTIONS, command.output, flags=re.MULTILINE)\n return [replace_argument(command.script, mistake, o) for o in options]", "has_branch": false, "total_branches": 0} {"prompt_id": 597, "project": "thefuck", "module": "thefuck.rules.brew_install", "class": "", "method": "match", "focal_method_txt": "def match(command):\n is_proper_command = ('brew install' in command.script and\n 'No available formula' in command.output)\n\n if is_proper_command:\n formula = re.findall(r'Error: No available formula for ([a-z]+)',\n command.output)[0]\n return bool(_get_similar_formula(formula))\n return False", "focal_method_lines": [25, 33], "in_stack": false, "globals": ["enabled_by_default"], "type_context": "import os\nimport re\nfrom thefuck.utils import get_closest, replace_argument\nfrom thefuck.specific.brew import get_brew_path_prefix, brew_available\n\nenabled_by_default = brew_available\n\ndef match(command):\n is_proper_command = ('brew install' in command.script and\n 'No available formula' in command.output)\n\n if is_proper_command:\n formula = re.findall(r'Error: No available formula for ([a-z]+)',\n command.output)[0]\n return bool(_get_similar_formula(formula))\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 598, "project": "thefuck", "module": "thefuck.rules.brew_install", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n not_exist_formula = re.findall(r'Error: No available formula for ([a-z]+)',\n command.output)[0]\n exist_formula = _get_similar_formula(not_exist_formula)\n\n return replace_argument(command.script, not_exist_formula, exist_formula)", "focal_method_lines": [36, 41], "in_stack": false, "globals": ["enabled_by_default"], "type_context": "import os\nimport re\nfrom thefuck.utils import get_closest, replace_argument\nfrom thefuck.specific.brew import get_brew_path_prefix, brew_available\n\nenabled_by_default = brew_available\n\ndef get_new_command(command):\n not_exist_formula = re.findall(r'Error: No available formula for ([a-z]+)',\n command.output)[0]\n exist_formula = _get_similar_formula(not_exist_formula)\n\n return replace_argument(command.script, not_exist_formula, exist_formula)", "has_branch": false, "total_branches": 0} {"prompt_id": 599, "project": "thefuck", "module": "thefuck.rules.choco_install", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n # Find the argument that is the package name\n for script_part in command.script_parts:\n if (\n script_part not in [\"choco\", \"cinst\", \"install\"]\n # Need exact match (bc chocolatey is a package)\n and not script_part.startswith('-')\n # Leading hyphens are parameters; some packages contain them though\n and '=' not in script_part and '/' not in script_part\n # These are certainly parameters\n ):\n return command.script.replace(script_part, script_part + \".install\")\n return []", "focal_method_lines": [9, 21], "in_stack": false, "globals": ["enabled_by_default"], "type_context": "from thefuck.utils import for_app, which\n\nenabled_by_default = bool(which(\"choco\")) or bool(which(\"cinst\"))\n\ndef get_new_command(command):\n # Find the argument that is the package name\n for script_part in command.script_parts:\n if (\n script_part not in [\"choco\", \"cinst\", \"install\"]\n # Need exact match (bc chocolatey is a package)\n and not script_part.startswith('-')\n # Leading hyphens are parameters; some packages contain them though\n and '=' not in script_part and '/' not in script_part\n # These are certainly parameters\n ):\n return command.script.replace(script_part, script_part + \".install\")\n return []", "has_branch": true, "total_branches": 2} {"prompt_id": 600, "project": "thefuck", "module": "thefuck.rules.dirty_unzip", "class": "", "method": "side_effect", "focal_method_txt": "def side_effect(old_cmd, command):\n with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:\n for file in archive.namelist():\n if not os.path.abspath(file).startswith(os.getcwd()):\n # it's unsafe to overwrite files outside of the current directory\n continue\n\n try:\n os.remove(file)\n except OSError:\n # does not try to remove directories as we cannot know if they\n # already existed before\n pass", "focal_method_lines": [44, 56], "in_stack": false, "globals": ["requires_output"], "type_context": "import os\nimport zipfile\nfrom thefuck.utils import for_app\nfrom thefuck.shells import shell\n\nrequires_output = False\n\ndef side_effect(old_cmd, command):\n with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:\n for file in archive.namelist():\n if not os.path.abspath(file).startswith(os.getcwd()):\n # it's unsafe to overwrite files outside of the current directory\n continue\n\n try:\n os.remove(file)\n except OSError:\n # does not try to remove directories as we cannot know if they\n # already existed before\n pass", "has_branch": true, "total_branches": 2} {"prompt_id": 601, "project": "thefuck", "module": "thefuck.rules.django_south_merge", "class": "", "method": "match", "focal_method_txt": "def match(command):\n return 'manage.py' in command.script and \\\n 'migrate' in command.script \\\n and '--merge: will just attempt the migration' in command.output", "focal_method_lines": [0, 1], "in_stack": false, "globals": [], "type_context": "\n\n\n\ndef match(command):\n return 'manage.py' in command.script and \\\n 'migrate' in command.script \\\n and '--merge: will just attempt the migration' in command.output", "has_branch": false, "total_branches": 0} {"prompt_id": 602, "project": "thefuck", "module": "thefuck.rules.no_such_file", "class": "", "method": "match", "focal_method_txt": "def match(command):\n for pattern in patterns:\n if re.search(pattern, command.output):\n return True\n\n return False", "focal_method_lines": [12, 17], "in_stack": false, "globals": ["patterns"], "type_context": "import re\nfrom thefuck.shells import shell\n\npatterns = (\n r\"mv: cannot move '[^']*' to '([^']*)': No such file or directory\",\n r\"mv: cannot move '[^']*' to '([^']*)': Not a directory\",\n r\"cp: cannot create regular file '([^']*)': No such file or directory\",\n r\"cp: cannot create regular file '([^']*)': Not a directory\",\n)\n\ndef match(command):\n for pattern in patterns:\n if re.search(pattern, command.output):\n return True\n\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 603, "project": "thefuck", "module": "thefuck.rules.no_such_file", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n for pattern in patterns:\n file = re.findall(pattern, command.output)\n\n if file:\n file = file[0]\n dir = file[0:file.rfind('/')]\n\n formatme = shell.and_('mkdir -p {}', '{}')\n return formatme.format(dir, command.script)", "focal_method_lines": [20, 29], "in_stack": false, "globals": ["patterns"], "type_context": "import re\nfrom thefuck.shells import shell\n\npatterns = (\n r\"mv: cannot move '[^']*' to '([^']*)': No such file or directory\",\n r\"mv: cannot move '[^']*' to '([^']*)': Not a directory\",\n r\"cp: cannot create regular file '([^']*)': No such file or directory\",\n r\"cp: cannot create regular file '([^']*)': Not a directory\",\n)\n\ndef get_new_command(command):\n for pattern in patterns:\n file = re.findall(pattern, command.output)\n\n if file:\n file = file[0]\n dir = file[0:file.rfind('/')]\n\n formatme = shell.and_('mkdir -p {}', '{}')\n return formatme.format(dir, command.script)", "has_branch": true, "total_branches": 2} {"prompt_id": 604, "project": "thefuck", "module": "thefuck.rules.pacman_invalid_option", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n option = re.findall(r\" -[dfqrstuv]\", command.script)[0]\n return re.sub(option, option.upper(), command.script)", "focal_method_lines": [14, 16], "in_stack": false, "globals": ["enabled_by_default"], "type_context": "from thefuck.specific.archlinux import archlinux_env\nfrom thefuck.specific.sudo import sudo_support\nfrom thefuck.utils import for_app\nimport re\n\nenabled_by_default = archlinux_env()\n\ndef get_new_command(command):\n option = re.findall(r\" -[dfqrstuv]\", command.script)[0]\n return re.sub(option, option.upper(), command.script)", "has_branch": false, "total_branches": 0} {"prompt_id": 605, "project": "thefuck", "module": "thefuck.rules.sudo_command_from_user_path", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n command_name = _get_command_name(command)\n return replace_argument(command.script, command_name,\n u'env \"PATH=$PATH\" {}'.format(command_name))", "focal_method_lines": [17, 19], "in_stack": false, "globals": [], "type_context": "import re\nfrom thefuck.utils import for_app, which, replace_argument\n\n\n\ndef get_new_command(command):\n command_name = _get_command_name(command)\n return replace_argument(command.script, command_name,\n u'env \"PATH=$PATH\" {}'.format(command_name))", "has_branch": false, "total_branches": 0} {"prompt_id": 606, "project": "thefuck", "module": "thefuck.rules.tsuru_not_command", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n broken_cmd = re.findall(r'tsuru: \"([^\"]*)\" is not a tsuru command',\n command.output)[0]\n return replace_command(command, broken_cmd,\n get_all_matched_commands(command.output))", "focal_method_lines": [10, 13], "in_stack": false, "globals": [], "type_context": "import re\nfrom thefuck.utils import get_all_matched_commands, replace_command, for_app\n\n\n\ndef get_new_command(command):\n broken_cmd = re.findall(r'tsuru: \"([^\"]*)\" is not a tsuru command',\n command.output)[0]\n return replace_command(command, broken_cmd,\n get_all_matched_commands(command.output))", "has_branch": false, "total_branches": 0} {"prompt_id": 607, "project": "thefuck", "module": "thefuck.rules.vagrant_up", "class": "", "method": "get_new_command", "focal_method_txt": "def get_new_command(command):\n cmds = command.script_parts\n machine = None\n if len(cmds) >= 3:\n machine = cmds[2]\n\n start_all_instances = shell.and_(u\"vagrant up\", command.script)\n if machine is None:\n return start_all_instances\n else:\n return [shell.and_(u\"vagrant up {}\".format(machine), command.script),\n start_all_instances]", "focal_method_lines": [9, 19], "in_stack": false, "globals": [], "type_context": "from thefuck.shells import shell\nfrom thefuck.utils import for_app\n\n\n\ndef get_new_command(command):\n cmds = command.script_parts\n machine = None\n if len(cmds) >= 3:\n machine = cmds[2]\n\n start_all_instances = shell.and_(u\"vagrant up\", command.script)\n if machine is None:\n return start_all_instances\n else:\n return [shell.and_(u\"vagrant up {}\".format(machine), command.script),\n start_all_instances]", "has_branch": true, "total_branches": 2} {"prompt_id": 608, "project": "thefuck", "module": "thefuck.system.unix", "class": "", "method": "getch", "focal_method_txt": "def getch():\n fd = sys.stdin.fileno()\n old = termios.tcgetattr(fd)\n try:\n tty.setraw(fd)\n return sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old)", "focal_method_lines": [11, 18], "in_stack": false, "globals": ["init_output"], "type_context": "import os\nimport sys\nimport tty\nimport termios\nimport colorama\nfrom distutils.spawn import find_executable\nfrom .. import const\n\ninit_output = colorama.init\n\ndef getch():\n fd = sys.stdin.fileno()\n old = termios.tcgetattr(fd)\n try:\n tty.setraw(fd)\n return sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old)", "has_branch": false, "total_branches": 0} {"prompt_id": 609, "project": "thefuck", "module": "thefuck.system.unix", "class": "", "method": "get_key", "focal_method_txt": "def get_key():\n ch = getch()\n\n if ch in const.KEY_MAPPING:\n return const.KEY_MAPPING[ch]\n elif ch == '\\x1b':\n next_ch = getch()\n if next_ch == '[':\n last_ch = getch()\n\n if last_ch == 'A':\n return const.KEY_UP\n elif last_ch == 'B':\n return const.KEY_DOWN\n\n return ch", "focal_method_lines": [21, 36], "in_stack": false, "globals": ["init_output"], "type_context": "import os\nimport sys\nimport tty\nimport termios\nimport colorama\nfrom distutils.spawn import find_executable\nfrom .. import const\n\ninit_output = colorama.init\n\ndef get_key():\n ch = getch()\n\n if ch in const.KEY_MAPPING:\n return const.KEY_MAPPING[ch]\n elif ch == '\\x1b':\n next_ch = getch()\n if next_ch == '[':\n last_ch = getch()\n\n if last_ch == 'A':\n return const.KEY_UP\n elif last_ch == 'B':\n return const.KEY_DOWN\n\n return ch", "has_branch": true, "total_branches": 2} {"prompt_id": 610, "project": "thefuck", "module": "thefuck.system.unix", "class": "", "method": "open_command", "focal_method_txt": "def open_command(arg):\n if find_executable('xdg-open'):\n return 'xdg-open ' + arg\n return 'open ' + arg", "focal_method_lines": [39, 42], "in_stack": false, "globals": ["init_output"], "type_context": "import os\nimport sys\nimport tty\nimport termios\nimport colorama\nfrom distutils.spawn import find_executable\nfrom .. import const\n\ninit_output = colorama.init\n\ndef open_command(arg):\n if find_executable('xdg-open'):\n return 'xdg-open ' + arg\n return 'open ' + arg", "has_branch": true, "total_branches": 2} {"prompt_id": 611, "project": "thefuck", "module": "thefuck.types", "class": "Command", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n if isinstance(other, Command):\n return (self.script, self.output) == (other.script, other.output)\n else:\n return False", "focal_method_lines": [47, 51], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Command(object):\n\n def __init__(self, script, output):\n \"\"\"Initializes command with given values.\n\n :type script: basestring\n :type output: basestring\n\n \"\"\"\n self.script = script\n self.output = output\n\n def __eq__(self, other):\n if isinstance(other, Command):\n return (self.script, self.output) == (other.script, other.output)\n else:\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 612, "project": "thefuck", "module": "thefuck.types", "class": "Rule", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n if isinstance(other, Rule):\n return ((self.name, self.match, self.get_new_command,\n self.enabled_by_default, self.side_effect,\n self.priority, self.requires_output)\n == (other.name, other.match, other.get_new_command,\n other.enabled_by_default, other.side_effect,\n other.priority, other.requires_output))\n else:\n return False", "focal_method_lines": [110, 119], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Rule(object):\n\n def __init__(self, name, match, get_new_command,\n enabled_by_default, side_effect,\n priority, requires_output):\n \"\"\"Initializes rule with given fields.\n\n :type name: basestring\n :type match: (Command) -> bool\n :type get_new_command: (Command) -> (basestring | [basestring])\n :type enabled_by_default: boolean\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n :type requires_output: bool\n\n \"\"\"\n self.name = name\n self.match = match\n self.get_new_command = get_new_command\n self.enabled_by_default = enabled_by_default\n self.side_effect = side_effect\n self.priority = priority\n self.requires_output = requires_output\n\n def __eq__(self, other):\n if isinstance(other, Rule):\n return ((self.name, self.match, self.get_new_command,\n self.enabled_by_default, self.side_effect,\n self.priority, self.requires_output)\n == (other.name, other.match, other.get_new_command,\n other.enabled_by_default, other.side_effect,\n other.priority, other.requires_output))\n else:\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 613, "project": "thefuck", "module": "thefuck.types", "class": "Rule", "method": "is_match", "focal_method_txt": " def is_match(self, command):\n \"\"\"Returns `True` if rule matches the command.\n\n :type command: Command\n :rtype: bool\n\n \"\"\"\n if command.output is None and self.requires_output:\n return False\n\n try:\n with logs.debug_time(u'Trying rule: {};'.format(self.name)):\n if self.match(command):\n return True\n except Exception:\n logs.rule_failed(self, sys.exc_info())", "focal_method_lines": [168, 183], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Command(object):\n\n def __init__(self, script, output):\n \"\"\"Initializes command with given values.\n\n :type script: basestring\n :type output: basestring\n\n \"\"\"\n self.script = script\n self.output = output\n\nclass Rule(object):\n\n def __init__(self, name, match, get_new_command,\n enabled_by_default, side_effect,\n priority, requires_output):\n \"\"\"Initializes rule with given fields.\n\n :type name: basestring\n :type match: (Command) -> bool\n :type get_new_command: (Command) -> (basestring | [basestring])\n :type enabled_by_default: boolean\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n :type requires_output: bool\n\n \"\"\"\n self.name = name\n self.match = match\n self.get_new_command = get_new_command\n self.enabled_by_default = enabled_by_default\n self.side_effect = side_effect\n self.priority = priority\n self.requires_output = requires_output\n\n def is_match(self, command):\n \"\"\"Returns `True` if rule matches the command.\n\n :type command: Command\n :rtype: bool\n\n \"\"\"\n if command.output is None and self.requires_output:\n return False\n\n try:\n with logs.debug_time(u'Trying rule: {};'.format(self.name)):\n if self.match(command):\n return True\n except Exception:\n logs.rule_failed(self, sys.exc_info())", "has_branch": true, "total_branches": 2} {"prompt_id": 614, "project": "thefuck", "module": "thefuck.types", "class": "Rule", "method": "get_corrected_commands", "focal_method_txt": " def get_corrected_commands(self, command):\n \"\"\"Returns generator with corrected commands.\n\n :type command: Command\n :rtype: Iterable[CorrectedCommand]\n\n \"\"\"\n new_commands = self.get_new_command(command)\n if not isinstance(new_commands, list):\n new_commands = (new_commands,)\n for n, new_command in enumerate(new_commands):\n yield CorrectedCommand(script=new_command,\n side_effect=self.side_effect,\n priority=(n + 1) * self.priority)", "focal_method_lines": [185, 196], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Command(object):\n\n def __init__(self, script, output):\n \"\"\"Initializes command with given values.\n\n :type script: basestring\n :type output: basestring\n\n \"\"\"\n self.script = script\n self.output = output\n\nclass CorrectedCommand(object):\n\n def __init__(self, script, side_effect, priority):\n \"\"\"Initializes instance with given fields.\n\n :type script: basestring\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n\n \"\"\"\n self.script = script\n self.side_effect = side_effect\n self.priority = priority\n\nclass Rule(object):\n\n def __init__(self, name, match, get_new_command,\n enabled_by_default, side_effect,\n priority, requires_output):\n \"\"\"Initializes rule with given fields.\n\n :type name: basestring\n :type match: (Command) -> bool\n :type get_new_command: (Command) -> (basestring | [basestring])\n :type enabled_by_default: boolean\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n :type requires_output: bool\n\n \"\"\"\n self.name = name\n self.match = match\n self.get_new_command = get_new_command\n self.enabled_by_default = enabled_by_default\n self.side_effect = side_effect\n self.priority = priority\n self.requires_output = requires_output\n\n def get_corrected_commands(self, command):\n \"\"\"Returns generator with corrected commands.\n\n :type command: Command\n :rtype: Iterable[CorrectedCommand]\n\n \"\"\"\n new_commands = self.get_new_command(command)\n if not isinstance(new_commands, list):\n new_commands = (new_commands,)\n for n, new_command in enumerate(new_commands):\n yield CorrectedCommand(script=new_command,\n side_effect=self.side_effect,\n priority=(n + 1) * self.priority)", "has_branch": true, "total_branches": 2} {"prompt_id": 615, "project": "thefuck", "module": "thefuck.types", "class": "CorrectedCommand", "method": "__eq__", "focal_method_txt": " def __eq__(self, other):\n \"\"\"Ignores `priority` field.\"\"\"\n if isinstance(other, CorrectedCommand):\n return (other.script, other.side_effect) == \\\n (self.script, self.side_effect)\n else:\n return False", "focal_method_lines": [216, 222], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Command(object):\n\n def __init__(self, script, output):\n \"\"\"Initializes command with given values.\n\n :type script: basestring\n :type output: basestring\n\n \"\"\"\n self.script = script\n self.output = output\n\nclass CorrectedCommand(object):\n\n def __init__(self, script, side_effect, priority):\n \"\"\"Initializes instance with given fields.\n\n :type script: basestring\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n\n \"\"\"\n self.script = script\n self.side_effect = side_effect\n self.priority = priority\n\n def __eq__(self, other):\n \"\"\"Ignores `priority` field.\"\"\"\n if isinstance(other, CorrectedCommand):\n return (other.script, other.side_effect) == \\\n (self.script, self.side_effect)\n else:\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 616, "project": "thefuck", "module": "thefuck.types", "class": "CorrectedCommand", "method": "run", "focal_method_txt": " def run(self, old_cmd):\n \"\"\"Runs command from rule for passed command.\n\n :type old_cmd: Command\n\n \"\"\"\n if self.side_effect:\n self.side_effect(old_cmd, self.script)\n if settings.alter_history:\n shell.put_to_history(self.script)\n # This depends on correct setting of PYTHONIOENCODING by the alias:\n logs.debug(u'PYTHONIOENCODING: {}'.format(\n os.environ.get('PYTHONIOENCODING', '!!not-set!!')))\n\n sys.stdout.write(self._get_script())", "focal_method_lines": [247, 261], "in_stack": false, "globals": [], "type_context": "from imp import load_source\nimport os\nimport sys\nfrom . import logs\nfrom .shells import shell\nfrom .conf import settings\nfrom .const import DEFAULT_PRIORITY, ALL_ENABLED\nfrom .exceptions import EmptyCommand\nfrom .utils import get_alias, format_raw_script\nfrom .output_readers import get_output\n\n\n\nclass Command(object):\n\n def __init__(self, script, output):\n \"\"\"Initializes command with given values.\n\n :type script: basestring\n :type output: basestring\n\n \"\"\"\n self.script = script\n self.output = output\n\nclass CorrectedCommand(object):\n\n def __init__(self, script, side_effect, priority):\n \"\"\"Initializes instance with given fields.\n\n :type script: basestring\n :type side_effect: (Command, basestring) -> None\n :type priority: int\n\n \"\"\"\n self.script = script\n self.side_effect = side_effect\n self.priority = priority\n\n def run(self, old_cmd):\n \"\"\"Runs command from rule for passed command.\n\n :type old_cmd: Command\n\n \"\"\"\n if self.side_effect:\n self.side_effect(old_cmd, self.script)\n if settings.alter_history:\n shell.put_to_history(self.script)\n # This depends on correct setting of PYTHONIOENCODING by the alias:\n logs.debug(u'PYTHONIOENCODING: {}'.format(\n os.environ.get('PYTHONIOENCODING', '!!not-set!!')))\n\n sys.stdout.write(self._get_script())", "has_branch": true, "total_branches": 2} {"prompt_id": 617, "project": "thonny", "module": "thonny.jedi_utils", "class": "", "method": "get_script_completions", "focal_method_txt": "def get_script_completions(source: str, row: int, column: int, filename: str, sys_path=None):\n import jedi\n\n if _using_older_jedi(jedi):\n try:\n script = jedi.Script(source, row, column, filename, sys_path=sys_path)\n except Exception as e:\n logger.info(\"Could not get completions with given sys_path\", exc_info=e)\n script = jedi.Script(source, row, column, filename)\n\n completions = script.completions()\n else:\n script = jedi.Script(code=source, path=filename, project=_get_new_jedi_project(sys_path))\n completions = script.complete(line=row, column=column)\n\n return _tweak_completions(completions)", "focal_method_lines": [51, 66], "in_stack": true, "globals": ["logger"], "type_context": "import logging\nfrom typing import List, Dict\n\nlogger = logging.getLogger(__name__)\n\ndef get_script_completions(source: str, row: int, column: int, filename: str, sys_path=None):\n import jedi\n\n if _using_older_jedi(jedi):\n try:\n script = jedi.Script(source, row, column, filename, sys_path=sys_path)\n except Exception as e:\n logger.info(\"Could not get completions with given sys_path\", exc_info=e)\n script = jedi.Script(source, row, column, filename)\n\n completions = script.completions()\n else:\n script = jedi.Script(code=source, path=filename, project=_get_new_jedi_project(sys_path))\n completions = script.complete(line=row, column=column)\n\n return _tweak_completions(completions)", "has_branch": true, "total_branches": 2} {"prompt_id": 618, "project": "thonny", "module": "thonny.jedi_utils", "class": "", "method": "get_interpreter_completions", "focal_method_txt": "def get_interpreter_completions(source: str, namespaces: List[Dict], sys_path=None):\n import jedi\n\n if _using_older_jedi(jedi):\n try:\n interpreter = jedi.Interpreter(source, namespaces, sys_path=sys_path)\n except Exception as e:\n logger.info(\"Could not get completions with given sys_path\", exc_info=e)\n interpreter = jedi.Interpreter(source, namespaces)\n else:\n # NB! Can't send project for Interpreter in 0.18\n # https://github.com/davidhalter/jedi/pull/1734\n interpreter = jedi.Interpreter(source, namespaces)\n if hasattr(interpreter, \"completions\"):\n # up to jedi 0.17\n return _tweak_completions(interpreter.completions())\n else:\n return _tweak_completions(interpreter.complete())", "focal_method_lines": [69, 86], "in_stack": true, "globals": ["logger"], "type_context": "import logging\nfrom typing import List, Dict\n\nlogger = logging.getLogger(__name__)\n\ndef get_interpreter_completions(source: str, namespaces: List[Dict], sys_path=None):\n import jedi\n\n if _using_older_jedi(jedi):\n try:\n interpreter = jedi.Interpreter(source, namespaces, sys_path=sys_path)\n except Exception as e:\n logger.info(\"Could not get completions with given sys_path\", exc_info=e)\n interpreter = jedi.Interpreter(source, namespaces)\n else:\n # NB! Can't send project for Interpreter in 0.18\n # https://github.com/davidhalter/jedi/pull/1734\n interpreter = jedi.Interpreter(source, namespaces)\n if hasattr(interpreter, \"completions\"):\n # up to jedi 0.17\n return _tweak_completions(interpreter.completions())\n else:\n return _tweak_completions(interpreter.complete())", "has_branch": true, "total_branches": 2} {"prompt_id": 619, "project": "thonny", "module": "thonny.jedi_utils", "class": "", "method": "get_definitions", "focal_method_txt": "def get_definitions(source: str, row: int, column: int, filename: str):\n import jedi\n\n if _using_older_jedi(jedi):\n script = jedi.Script(source, row, column, filename)\n return script.goto_definitions()\n else:\n script = jedi.Script(code=source, path=filename)\n return script.infer(line=row, column=column)", "focal_method_lines": [122, 130], "in_stack": true, "globals": ["logger"], "type_context": "import logging\nfrom typing import List, Dict\n\nlogger = logging.getLogger(__name__)\n\ndef get_definitions(source: str, row: int, column: int, filename: str):\n import jedi\n\n if _using_older_jedi(jedi):\n script = jedi.Script(source, row, column, filename)\n return script.goto_definitions()\n else:\n script = jedi.Script(code=source, path=filename)\n return script.infer(line=row, column=column)", "has_branch": true, "total_branches": 2} {"prompt_id": 620, "project": "thonny", "module": "thonny.plugins.pgzero_frontend", "class": "", "method": "toggle_variable", "focal_method_txt": "def toggle_variable():\n var = get_workbench().get_variable(_OPTION_NAME)\n var.set(not var.get())\n update_environment()", "focal_method_lines": [8, 11], "in_stack": true, "globals": ["_OPTION_NAME"], "type_context": "import os\nfrom thonny import get_workbench\nfrom thonny.languages import tr\n\n_OPTION_NAME = \"run.pgzero_mode\"\n\ndef toggle_variable():\n var = get_workbench().get_variable(_OPTION_NAME)\n var.set(not var.get())\n update_environment()", "has_branch": false, "total_branches": 0} {"prompt_id": 621, "project": "thonny", "module": "thonny.plugins.pgzero_frontend", "class": "", "method": "update_environment", "focal_method_txt": "def update_environment():\n if get_workbench().in_simple_mode():\n os.environ[\"PGZERO_MODE\"] = \"auto\"\n else:\n os.environ[\"PGZERO_MODE\"] = str(get_workbench().get_option(_OPTION_NAME))", "focal_method_lines": [14, 18], "in_stack": true, "globals": ["_OPTION_NAME"], "type_context": "import os\nfrom thonny import get_workbench\nfrom thonny.languages import tr\n\n_OPTION_NAME = \"run.pgzero_mode\"\n\ndef update_environment():\n if get_workbench().in_simple_mode():\n os.environ[\"PGZERO_MODE\"] = \"auto\"\n else:\n os.environ[\"PGZERO_MODE\"] = str(get_workbench().get_option(_OPTION_NAME))", "has_branch": true, "total_branches": 2} {"prompt_id": 622, "project": "thonny", "module": "thonny.plugins.pgzero_frontend", "class": "", "method": "load_plugin", "focal_method_txt": "def load_plugin():\n get_workbench().set_default(_OPTION_NAME, False)\n get_workbench().add_command(\n \"toggle_pgzero_mode\",\n \"run\",\n tr(\"Pygame Zero mode\"),\n toggle_variable,\n flag_name=_OPTION_NAME,\n group=40,\n )\n update_environment()", "focal_method_lines": [21, 31], "in_stack": true, "globals": ["_OPTION_NAME"], "type_context": "import os\nfrom thonny import get_workbench\nfrom thonny.languages import tr\n\n_OPTION_NAME = \"run.pgzero_mode\"\n\ndef load_plugin():\n get_workbench().set_default(_OPTION_NAME, False)\n get_workbench().add_command(\n \"toggle_pgzero_mode\",\n \"run\",\n tr(\"Pygame Zero mode\"),\n toggle_variable,\n flag_name=_OPTION_NAME,\n group=40,\n )\n update_environment()", "has_branch": false, "total_branches": 0} {"prompt_id": 623, "project": "thonny", "module": "thonny.roughparse", "class": "StringTranslatePseudoMapping", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, item):\n return self._get(item)", "focal_method_lines": [148, 149], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass StringTranslatePseudoMapping(Mapping):\n\n def __init__(self, non_defaults, default_value):\n self._non_defaults = non_defaults\n self._default_value = default_value\n\n def _get(key, _get=non_defaults.get, _default=default_value):\n return _get(key, _default)\n\n self._get = _get\n\n def __getitem__(self, item):\n return self._get(item)", "has_branch": false, "total_branches": 0} {"prompt_id": 624, "project": "thonny", "module": "thonny.roughparse", "class": "StringTranslatePseudoMapping", "method": "__len__", "focal_method_txt": " def __len__(self):\n return len(self._non_defaults)", "focal_method_lines": [151, 152], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass StringTranslatePseudoMapping(Mapping):\n\n def __init__(self, non_defaults, default_value):\n self._non_defaults = non_defaults\n self._default_value = default_value\n\n def _get(key, _get=non_defaults.get, _default=default_value):\n return _get(key, _default)\n\n self._get = _get\n\n def __len__(self):\n return len(self._non_defaults)", "has_branch": false, "total_branches": 0} {"prompt_id": 625, "project": "thonny", "module": "thonny.roughparse", "class": "StringTranslatePseudoMapping", "method": "__iter__", "focal_method_txt": " def __iter__(self):\n return iter(self._non_defaults)", "focal_method_lines": [154, 155], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass StringTranslatePseudoMapping(Mapping):\n\n def __init__(self, non_defaults, default_value):\n self._non_defaults = non_defaults\n self._default_value = default_value\n\n def _get(key, _get=non_defaults.get, _default=default_value):\n return _get(key, _default)\n\n self._get = _get\n\n def __iter__(self):\n return iter(self._non_defaults)", "has_branch": false, "total_branches": 0} {"prompt_id": 626, "project": "thonny", "module": "thonny.roughparse", "class": "StringTranslatePseudoMapping", "method": "get", "focal_method_txt": " def get(self, key, default=None):\n return self._get(key)", "focal_method_lines": [157, 158], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass StringTranslatePseudoMapping(Mapping):\n\n def __init__(self, non_defaults, default_value):\n self._non_defaults = non_defaults\n self._default_value = default_value\n\n def _get(key, _get=non_defaults.get, _default=default_value):\n return _get(key, _default)\n\n self._get = _get\n\n def get(self, key, default=None):\n return self._get(key)", "has_branch": false, "total_branches": 0} {"prompt_id": 627, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "set_str", "focal_method_txt": " def set_str(self, s):\n assert len(s) == 0 or s[-1] == \"\\n\"\n self.str = s\n self.study_level = 0", "focal_method_lines": [166, 169], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def set_str(self, s):\n assert len(s) == 0 or s[-1] == \"\\n\"\n self.str = s\n self.study_level = 0", "has_branch": false, "total_branches": 0} {"prompt_id": 628, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "find_good_parse_start", "focal_method_txt": " def find_good_parse_start(self, is_char_in_string=None, _synchre=_synchre):\n # pylint: disable=redefined-builtin\n\n str, pos = self.str, None # @ReservedAssignment\n\n if not is_char_in_string:\n # no clue -- make the caller pass everything\n return None\n\n # Peek back from the end for a good place to start,\n # but don't try too often; pos will be left None, or\n # bumped to a legitimate synch point.\n limit = len(str)\n for _ in range(5):\n i = str.rfind(\":\\n\", 0, limit)\n if i < 0:\n break\n i = str.rfind(\"\\n\", 0, i) + 1 # start of colon line\n m = _synchre(str, i, limit)\n if m and not is_char_in_string(m.start()):\n pos = m.start()\n break\n limit = i\n if pos is None:\n # Nothing looks like a block-opener, or stuff does\n # but is_char_in_string keeps returning true; most likely\n # we're in or near a giant string, the colorizer hasn't\n # caught up enough to be helpful, or there simply *aren't*\n # any interesting stmts. In any of these cases we're\n # going to have to parse the whole thing to be sure, so\n # give it one last try from the start, but stop wasting\n # time here regardless of the outcome.\n m = _synchre(str)\n if m and not is_char_in_string(m.start()):\n pos = m.start()\n return pos\n\n # Peeking back worked; look forward until _synchre no longer\n # matches.\n i = pos + 1\n while 1:\n m = _synchre(str, i)\n if m:\n s, i = m.span()\n if not is_char_in_string(s):\n pos = s\n else:\n break\n return pos", "focal_method_lines": [182, 230], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def find_good_parse_start(self, is_char_in_string=None, _synchre=_synchre):\n # pylint: disable=redefined-builtin\n\n str, pos = self.str, None # @ReservedAssignment\n\n if not is_char_in_string:\n # no clue -- make the caller pass everything\n return None\n\n # Peek back from the end for a good place to start,\n # but don't try too often; pos will be left None, or\n # bumped to a legitimate synch point.\n limit = len(str)\n for _ in range(5):\n i = str.rfind(\":\\n\", 0, limit)\n if i < 0:\n break\n i = str.rfind(\"\\n\", 0, i) + 1 # start of colon line\n m = _synchre(str, i, limit)\n if m and not is_char_in_string(m.start()):\n pos = m.start()\n break\n limit = i\n if pos is None:\n # Nothing looks like a block-opener, or stuff does\n # but is_char_in_string keeps returning true; most likely\n # we're in or near a giant string, the colorizer hasn't\n # caught up enough to be helpful, or there simply *aren't*\n # any interesting stmts. In any of these cases we're\n # going to have to parse the whole thing to be sure, so\n # give it one last try from the start, but stop wasting\n # time here regardless of the outcome.\n m = _synchre(str)\n if m and not is_char_in_string(m.start()):\n pos = m.start()\n return pos\n\n # Peeking back worked; look forward until _synchre no longer\n # matches.\n i = pos + 1\n while 1:\n m = _synchre(str, i)\n if m:\n s, i = m.span()\n if not is_char_in_string(s):\n pos = s\n else:\n break\n return pos", "has_branch": true, "total_branches": 2} {"prompt_id": 629, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "set_lo", "focal_method_txt": " def set_lo(self, lo):\n assert lo == 0 or self.str[lo - 1] == \"\\n\"\n if lo > 0:\n self.str = self.str[lo:]", "focal_method_lines": [235, 238], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def set_lo(self, lo):\n assert lo == 0 or self.str[lo - 1] == \"\\n\"\n if lo > 0:\n self.str = self.str[lo:]", "has_branch": true, "total_branches": 2} {"prompt_id": 630, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "get_continuation_type", "focal_method_txt": " def get_continuation_type(self):\n self._study1()\n return self.continuation", "focal_method_lines": [391, 393], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def get_continuation_type(self):\n self._study1()\n return self.continuation", "has_branch": false, "total_branches": 0} {"prompt_id": 631, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "compute_bracket_indent", "focal_method_txt": " def compute_bracket_indent(self):\n # pylint: disable=redefined-builtin\n self._study2()\n assert self.continuation == C_BRACKET\n j = self.lastopenbracketpos\n str = self.str # @ReservedAssignment\n n = len(str)\n origi = i = str.rfind(\"\\n\", 0, j) + 1\n j = j + 1 # one beyond open bracket\n # find first list item; set i to start of its line\n while j < n:\n m = _itemre(str, j)\n if m:\n j = m.end() - 1 # index of first interesting char\n extra = 0\n break\n else:\n # this line is junk; advance to next line\n i = j = str.find(\"\\n\", j) + 1\n else:\n # nothing interesting follows the bracket;\n # reproduce the bracket line's indentation + a level\n j = i = origi\n while str[j] in \" \\t\":\n j = j + 1\n extra = self.indent_width\n return len(str[i:j].expandtabs(self.tabwidth)) + extra", "focal_method_lines": [523, 549], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def compute_bracket_indent(self):\n # pylint: disable=redefined-builtin\n self._study2()\n assert self.continuation == C_BRACKET\n j = self.lastopenbracketpos\n str = self.str # @ReservedAssignment\n n = len(str)\n origi = i = str.rfind(\"\\n\", 0, j) + 1\n j = j + 1 # one beyond open bracket\n # find first list item; set i to start of its line\n while j < n:\n m = _itemre(str, j)\n if m:\n j = m.end() - 1 # index of first interesting char\n extra = 0\n break\n else:\n # this line is junk; advance to next line\n i = j = str.find(\"\\n\", j) + 1\n else:\n # nothing interesting follows the bracket;\n # reproduce the bracket line's indentation + a level\n j = i = origi\n while str[j] in \" \\t\":\n j = j + 1\n extra = self.indent_width\n return len(str[i:j].expandtabs(self.tabwidth)) + extra", "has_branch": true, "total_branches": 2} {"prompt_id": 632, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "get_num_lines_in_stmt", "focal_method_txt": " def get_num_lines_in_stmt(self):\n self._study1()\n goodlines = self.goodlines\n return goodlines[-1] - goodlines[-2]", "focal_method_lines": [555, 558], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def get_num_lines_in_stmt(self):\n self._study1()\n goodlines = self.goodlines\n return goodlines[-1] - goodlines[-2]", "has_branch": false, "total_branches": 0} {"prompt_id": 633, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "compute_backslash_indent", "focal_method_txt": " def compute_backslash_indent(self):\n # pylint: disable=redefined-builtin\n self._study2()\n assert self.continuation == C_BACKSLASH\n str = self.str # @ReservedAssignment\n i = self.stmt_start\n while str[i] in \" \\t\":\n i = i + 1\n startpos = i\n\n # See whether the initial line starts an assignment stmt; i.e.,\n # look for an = operator\n endpos = str.find(\"\\n\", startpos) + 1\n found = level = 0\n while i < endpos:\n ch = str[i]\n if ch in \"([{\":\n level = level + 1\n i = i + 1\n elif ch in \")]}\":\n if level:\n level = level - 1\n i = i + 1\n elif ch == '\"' or ch == \"'\":\n i = _match_stringre(str, i, endpos).end()\n elif ch == \"#\":\n break\n elif (\n level == 0\n and ch == \"=\"\n and (i == 0 or str[i - 1] not in \"=<>!\")\n and str[i + 1] != \"=\"\n ):\n found = 1\n break\n else:\n i = i + 1\n\n if found:\n # found a legit =, but it may be the last interesting\n # thing on the line\n i = i + 1 # move beyond the =\n found = re.match(r\"\\s*\\\\\", str[i:endpos]) is None\n\n if not found:\n # oh well ... settle for moving beyond the first chunk\n # of non-whitespace chars\n i = startpos\n while str[i] not in \" \\t\\n\":\n i = i + 1\n\n return len(str[self.stmt_start : i].expandtabs(self.tabwidth)) + 1", "focal_method_lines": [564, 615], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def compute_backslash_indent(self):\n # pylint: disable=redefined-builtin\n self._study2()\n assert self.continuation == C_BACKSLASH\n str = self.str # @ReservedAssignment\n i = self.stmt_start\n while str[i] in \" \\t\":\n i = i + 1\n startpos = i\n\n # See whether the initial line starts an assignment stmt; i.e.,\n # look for an = operator\n endpos = str.find(\"\\n\", startpos) + 1\n found = level = 0\n while i < endpos:\n ch = str[i]\n if ch in \"([{\":\n level = level + 1\n i = i + 1\n elif ch in \")]}\":\n if level:\n level = level - 1\n i = i + 1\n elif ch == '\"' or ch == \"'\":\n i = _match_stringre(str, i, endpos).end()\n elif ch == \"#\":\n break\n elif (\n level == 0\n and ch == \"=\"\n and (i == 0 or str[i - 1] not in \"=<>!\")\n and str[i + 1] != \"=\"\n ):\n found = 1\n break\n else:\n i = i + 1\n\n if found:\n # found a legit =, but it may be the last interesting\n # thing on the line\n i = i + 1 # move beyond the =\n found = re.match(r\"\\s*\\\\\", str[i:endpos]) is None\n\n if not found:\n # oh well ... settle for moving beyond the first chunk\n # of non-whitespace chars\n i = startpos\n while str[i] not in \" \\t\\n\":\n i = i + 1\n\n return len(str[self.stmt_start : i].expandtabs(self.tabwidth)) + 1", "has_branch": true, "total_branches": 2} {"prompt_id": 634, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "get_base_indent_string", "focal_method_txt": " def get_base_indent_string(self):\n self._study2()\n i, n = self.stmt_start, self.stmt_end\n j = i\n str_ = self.str\n while j < n and str_[j] in \" \\t\":\n j = j + 1\n return str_[i:j]", "focal_method_lines": [620, 627], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def get_base_indent_string(self):\n self._study2()\n i, n = self.stmt_start, self.stmt_end\n j = i\n str_ = self.str\n while j < n and str_[j] in \" \\t\":\n j = j + 1\n return str_[i:j]", "has_branch": true, "total_branches": 2} {"prompt_id": 635, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "is_block_opener", "focal_method_txt": " def is_block_opener(self):\n self._study2()\n return self.lastch == \":\"", "focal_method_lines": [631, 633], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def is_block_opener(self):\n self._study2()\n return self.lastch == \":\"", "has_branch": false, "total_branches": 0} {"prompt_id": 636, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "is_block_closer", "focal_method_txt": " def is_block_closer(self):\n self._study2()\n return _closere(self.str, self.stmt_start) is not None", "focal_method_lines": [637, 639], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def is_block_closer(self):\n self._study2()\n return _closere(self.str, self.stmt_start) is not None", "has_branch": false, "total_branches": 0} {"prompt_id": 637, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "get_last_open_bracket_pos", "focal_method_txt": " def get_last_open_bracket_pos(self):\n self._study2()\n return self.lastopenbracketpos", "focal_method_lines": [644, 646], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def get_last_open_bracket_pos(self):\n self._study2()\n return self.lastopenbracketpos", "has_branch": false, "total_branches": 0} {"prompt_id": 638, "project": "thonny", "module": "thonny.roughparse", "class": "RoughParser", "method": "get_last_stmt_bracketing", "focal_method_txt": " def get_last_stmt_bracketing(self):\n self._study2()\n return self.stmt_bracketing", "focal_method_lines": [653, 655], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\n def get_last_stmt_bracketing(self):\n self._study2()\n return self.stmt_bracketing", "has_branch": false, "total_branches": 0} {"prompt_id": 639, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "__init__", "focal_method_txt": " def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)", "focal_method_lines": [678, 718], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass RoughParser:\n\n _tran1 = {}\n\n _tran = StringTranslatePseudoMapping(_tran1, default_value=ord(\"x\"))\n\n lastopenbracketpos = None\n\n stmt_bracketing = None\n\n def __init__(self, indent_width, tabwidth):\n self.indent_width = indent_width\n self.tabwidth = tabwidth\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)", "has_branch": true, "total_branches": 2} {"prompt_id": 640, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "set_index", "focal_method_txt": " def set_index(self, index):\n \"\"\"Set the index to which the functions relate.\n\n The index must be in the same statement.\n \"\"\"\n indexinrawtext = len(self.rawtext) - len(self.text.get(index, self.stopatindex))\n if indexinrawtext < 0:\n raise ValueError(\"Index %s precedes the analyzed statement\" % index)\n self.indexinrawtext = indexinrawtext\n # find the rightmost bracket to which index belongs\n self.indexbracket = 0\n while (\n self.indexbracket < len(self.bracketing) - 1\n and self.bracketing[self.indexbracket + 1][0] < self.indexinrawtext\n ):\n self.indexbracket += 1\n if (\n self.indexbracket < len(self.bracketing) - 1\n and self.bracketing[self.indexbracket + 1][0] == self.indexinrawtext\n and not self.isopener[self.indexbracket + 1]\n ):\n self.indexbracket += 1", "focal_method_lines": [720, 741], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)\n\n def set_index(self, index):\n \"\"\"Set the index to which the functions relate.\n\n The index must be in the same statement.\n \"\"\"\n indexinrawtext = len(self.rawtext) - len(self.text.get(index, self.stopatindex))\n if indexinrawtext < 0:\n raise ValueError(\"Index %s precedes the analyzed statement\" % index)\n self.indexinrawtext = indexinrawtext\n # find the rightmost bracket to which index belongs\n self.indexbracket = 0\n while (\n self.indexbracket < len(self.bracketing) - 1\n and self.bracketing[self.indexbracket + 1][0] < self.indexinrawtext\n ):\n self.indexbracket += 1\n if (\n self.indexbracket < len(self.bracketing) - 1\n and self.bracketing[self.indexbracket + 1][0] == self.indexinrawtext\n and not self.isopener[self.indexbracket + 1]\n ):\n self.indexbracket += 1", "has_branch": true, "total_branches": 2} {"prompt_id": 641, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "is_in_string", "focal_method_txt": " def is_in_string(self):\n \"\"\"Is the index given to the HyperParser in a string?\"\"\"\n # The bracket to which we belong should be an opener.\n # If it's an opener, it has to have a character.\n return self.isopener[self.indexbracket] and self.rawtext[\n self.bracketing[self.indexbracket][0]\n ] in ('\"', \"'\")", "focal_method_lines": [743, 747], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)\n\n def is_in_string(self):\n \"\"\"Is the index given to the HyperParser in a string?\"\"\"\n # The bracket to which we belong should be an opener.\n # If it's an opener, it has to have a character.\n return self.isopener[self.indexbracket] and self.rawtext[\n self.bracketing[self.indexbracket][0]\n ] in ('\"', \"'\")", "has_branch": false, "total_branches": 0} {"prompt_id": 642, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "is_in_code", "focal_method_txt": " def is_in_code(self):\n \"\"\"Is the index given to the HyperParser in normal code?\"\"\"\n return not self.isopener[self.indexbracket] or self.rawtext[\n self.bracketing[self.indexbracket][0]\n ] not in (\"#\", '\"', \"'\")", "focal_method_lines": [751, 753], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)\n\n def is_in_code(self):\n \"\"\"Is the index given to the HyperParser in normal code?\"\"\"\n return not self.isopener[self.indexbracket] or self.rawtext[\n self.bracketing[self.indexbracket][0]\n ] not in (\"#\", '\"', \"'\")", "has_branch": false, "total_branches": 0} {"prompt_id": 643, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "get_surrounding_brackets", "focal_method_txt": " def get_surrounding_brackets(self, openers=\"([{\", mustclose=False):\n \"\"\"Return bracket indexes or None.\n\n If the index given to the HyperParser is surrounded by a\n bracket defined in openers (or at least has one before it),\n return the indices of the opening bracket and the closing\n bracket (or the end of line, whichever comes first).\n\n If it is not surrounded by brackets, or the end of line comes\n before the closing bracket and mustclose is True, returns None.\n \"\"\"\n\n bracketinglevel = self.bracketing[self.indexbracket][1]\n before = self.indexbracket\n while (\n not self.isopener[before]\n or self.rawtext[self.bracketing[before][0]] not in openers\n or self.bracketing[before][1] > bracketinglevel\n ):\n before -= 1\n if before < 0:\n return None\n bracketinglevel = min(bracketinglevel, self.bracketing[before][1])\n after = self.indexbracket + 1\n while after < len(self.bracketing) and self.bracketing[after][1] >= bracketinglevel:\n after += 1\n\n beforeindex = self.text.index(\n \"%s-%dc\" % (self.stopatindex, len(self.rawtext) - self.bracketing[before][0])\n )\n if after >= len(self.bracketing) or self.bracketing[after][0] > len(self.rawtext):\n if mustclose:\n return None\n afterindex = self.stopatindex\n else:\n # We are after a real char, so it is a ')' and we give the\n # index before it.\n afterindex = self.text.index(\n \"%s-%dc\" % (self.stopatindex, len(self.rawtext) - (self.bracketing[after][0] - 1))\n )\n\n return beforeindex, afterindex", "focal_method_lines": [757, 798], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)\n\n def get_surrounding_brackets(self, openers=\"([{\", mustclose=False):\n \"\"\"Return bracket indexes or None.\n\n If the index given to the HyperParser is surrounded by a\n bracket defined in openers (or at least has one before it),\n return the indices of the opening bracket and the closing\n bracket (or the end of line, whichever comes first).\n\n If it is not surrounded by brackets, or the end of line comes\n before the closing bracket and mustclose is True, returns None.\n \"\"\"\n\n bracketinglevel = self.bracketing[self.indexbracket][1]\n before = self.indexbracket\n while (\n not self.isopener[before]\n or self.rawtext[self.bracketing[before][0]] not in openers\n or self.bracketing[before][1] > bracketinglevel\n ):\n before -= 1\n if before < 0:\n return None\n bracketinglevel = min(bracketinglevel, self.bracketing[before][1])\n after = self.indexbracket + 1\n while after < len(self.bracketing) and self.bracketing[after][1] >= bracketinglevel:\n after += 1\n\n beforeindex = self.text.index(\n \"%s-%dc\" % (self.stopatindex, len(self.rawtext) - self.bracketing[before][0])\n )\n if after >= len(self.bracketing) or self.bracketing[after][0] > len(self.rawtext):\n if mustclose:\n return None\n afterindex = self.stopatindex\n else:\n # We are after a real char, so it is a ')' and we give the\n # index before it.\n afterindex = self.text.index(\n \"%s-%dc\" % (self.stopatindex, len(self.rawtext) - (self.bracketing[after][0] - 1))\n )\n\n return beforeindex, afterindex", "has_branch": true, "total_branches": 2} {"prompt_id": 644, "project": "thonny", "module": "thonny.roughparse", "class": "HyperParser", "method": "get_expression", "focal_method_txt": " def get_expression(self):\n \"\"\"Return a string with the Python expression which ends at the\n given index, which is empty if there is no real one.\n \"\"\"\n if not self.is_in_code():\n raise ValueError(\"get_expression should only be called\" \"if index is inside a code.\")\n\n rawtext = self.rawtext\n bracketing = self.bracketing\n\n brck_index = self.indexbracket\n brck_limit = bracketing[brck_index][0]\n pos = self.indexinrawtext\n\n last_identifier_pos = pos\n postdot_phase = True\n\n while 1:\n # Eat whitespaces, comments, and if postdot_phase is False - a dot\n while 1:\n if pos > brck_limit and rawtext[pos - 1] in self._whitespace_chars:\n # Eat a whitespace\n pos -= 1\n elif not postdot_phase and pos > brck_limit and rawtext[pos - 1] == \".\":\n # Eat a dot\n pos -= 1\n postdot_phase = True\n # The next line will fail if we are *inside* a comment,\n # but we shouldn't be.\n elif (\n pos == brck_limit\n and brck_index > 0\n and rawtext[bracketing[brck_index - 1][0]] == \"#\"\n ):\n # Eat a comment\n brck_index -= 2\n brck_limit = bracketing[brck_index][0]\n pos = bracketing[brck_index + 1][0]\n else:\n # If we didn't eat anything, quit.\n break\n\n if not postdot_phase:\n # We didn't find a dot, so the expression end at the\n # last identifier pos.\n break\n\n ret = self._eat_identifier(rawtext, brck_limit, pos)\n if ret:\n # There is an identifier to eat\n pos = pos - ret\n last_identifier_pos = pos\n # Now, to continue the search, we must find a dot.\n postdot_phase = False\n # (the loop continues now)\n\n elif pos == brck_limit:\n # We are at a bracketing limit. If it is a closing\n # bracket, eat the bracket, otherwise, stop the search.\n level = bracketing[brck_index][1]\n while brck_index > 0 and bracketing[brck_index - 1][1] > level:\n brck_index -= 1\n if bracketing[brck_index][0] == brck_limit:\n # We were not at the end of a closing bracket\n break\n pos = bracketing[brck_index][0]\n brck_index -= 1\n brck_limit = bracketing[brck_index][0]\n last_identifier_pos = pos\n if rawtext[pos] in \"([\":\n # [] and () may be used after an identifier, so we\n # continue. postdot_phase is True, so we don't allow a dot.\n pass\n else:\n # We can't continue after other types of brackets\n if rawtext[pos] in \"'\\\"\":\n # Scan a string prefix\n while pos > 0 and rawtext[pos - 1] in \"rRbBuU\":\n pos -= 1\n last_identifier_pos = pos\n break\n\n else:\n # We've found an operator or something.\n break\n\n return rawtext[last_identifier_pos : self.indexinrawtext]", "focal_method_lines": [858, 944], "in_stack": true, "globals": ["NUM_CONTEXT_LINES", "C_NONE", "C_BACKSLASH", "C_STRING_FIRST_LINE", "C_STRING_NEXT_LINES", "C_BRACKET", "_synchre", "_junkre", "_match_stringre", "_itemre", "_closere", "_chew_ordinaryre", "_ASCII_ID_CHARS", "_ASCII_ID_FIRST_CHARS", "_IS_ASCII_ID_CHAR", "_IS_ASCII_ID_FIRST_CHAR"], "type_context": "import re\nimport string\nfrom collections.abc import Mapping\nfrom keyword import iskeyword\nfrom typing import Dict\n\nNUM_CONTEXT_LINES = (50, 500, 5000000)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE, C_STRING_NEXT_LINES, C_BRACKET) = range(5)\n_synchre = re.compile(\n r\"\"\"\n ^\n [ \\t]*\n (?: while\n | else\n | def\n | return\n | assert\n | break\n | class\n | continue\n | elif\n | try\n | except\n | raise\n | import\n | yield\n )\n \\b\n\"\"\",\n re.VERBOSE | re.MULTILINE,\n).search\n_junkre = re.compile(\n r\"\"\"\n [ \\t]*\n (?: \\# \\S .* )?\n \\n\n\"\"\",\n re.VERBOSE,\n).match\n_match_stringre = re.compile(\n r\"\"\"\n \\\"\"\" [^\"\\\\]* (?:\n (?: \\\\. | \"(?!\"\") )\n [^\"\\\\]*\n )*\n (?: \\\"\"\" )?\n\n| \" [^\"\\\\\\n]* (?: \\\\. [^\"\\\\\\n]* )* \"?\n\n| ''' [^'\\\\]* (?:\n (?: \\\\. | '(?!'') )\n [^'\\\\]*\n )*\n (?: ''' )?\n\n| ' [^'\\\\\\n]* (?: \\\\. [^'\\\\\\n]* )* '?\n\"\"\",\n re.VERBOSE | re.DOTALL,\n).match\n_itemre = re.compile(\n r\"\"\"\n [ \\t]*\n [^\\s#\\\\] # if we match, m.end()-1 is the interesting char\n\"\"\",\n re.VERBOSE,\n).match\n_closere = re.compile(\n r\"\"\"\n \\s*\n (?: return\n | break\n | continue\n | raise\n | pass\n )\n \\b\n\"\"\",\n re.VERBOSE,\n).match\n_chew_ordinaryre = re.compile(\n r\"\"\"\n [^[\\](){}#'\"\\\\]+\n\"\"\",\n re.VERBOSE,\n).match\n_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + \"_\")\n_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + \"_\")\n_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]\n_IS_ASCII_ID_FIRST_CHAR = [(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]\n\nclass HyperParser:\n\n _ID_KEYWORDS = frozenset({\"True\", \"False\", \"None\"})\n\n _whitespace_chars = \" \\t\\n\\\\\"\n\n def __init__(self, text, index):\n \"To initialize, analyze the surroundings of the given index.\"\n\n self.text = text\n\n parser = RoughParser(text.indent_width, text.tabwidth)\n\n def index2line(index):\n return int(float(index))\n\n lno = index2line(text.index(index))\n\n for context in NUM_CONTEXT_LINES:\n startat = max(lno - context, 1)\n startatindex = repr(startat) + \".0\"\n stopatindex = \"%d.end\" % lno\n # We add the newline because PyParse requires a newline\n # at end. We add a space so that index won't be at end\n # of line, so that its status will be the same as the\n # char before it, if should.\n parser.set_str(text.get(startatindex, stopatindex) + \" \\n\")\n bod = parser.find_good_parse_start(_build_char_in_string_func(startatindex))\n if bod is not None or startat == 1:\n break\n parser.set_lo(bod or 0)\n\n # We want what the parser has, minus the last newline and space.\n self.rawtext = parser.str[:-2]\n # Parser.str apparently preserves the statement we are in, so\n # that stopatindex can be used to synchronize the string with\n # the text box indices.\n self.stopatindex = stopatindex\n self.bracketing = parser.get_last_stmt_bracketing()\n # find which pairs of bracketing are openers. These always\n # correspond to a character of rawtext.\n self.isopener = [\n i > 0 and self.bracketing[i][1] > self.bracketing[i - 1][1]\n for i in range(len(self.bracketing))\n ]\n\n self.set_index(index)\n\n def get_expression(self):\n \"\"\"Return a string with the Python expression which ends at the\n given index, which is empty if there is no real one.\n \"\"\"\n if not self.is_in_code():\n raise ValueError(\"get_expression should only be called\" \"if index is inside a code.\")\n\n rawtext = self.rawtext\n bracketing = self.bracketing\n\n brck_index = self.indexbracket\n brck_limit = bracketing[brck_index][0]\n pos = self.indexinrawtext\n\n last_identifier_pos = pos\n postdot_phase = True\n\n while 1:\n # Eat whitespaces, comments, and if postdot_phase is False - a dot\n while 1:\n if pos > brck_limit and rawtext[pos - 1] in self._whitespace_chars:\n # Eat a whitespace\n pos -= 1\n elif not postdot_phase and pos > brck_limit and rawtext[pos - 1] == \".\":\n # Eat a dot\n pos -= 1\n postdot_phase = True\n # The next line will fail if we are *inside* a comment,\n # but we shouldn't be.\n elif (\n pos == brck_limit\n and brck_index > 0\n and rawtext[bracketing[brck_index - 1][0]] == \"#\"\n ):\n # Eat a comment\n brck_index -= 2\n brck_limit = bracketing[brck_index][0]\n pos = bracketing[brck_index + 1][0]\n else:\n # If we didn't eat anything, quit.\n break\n\n if not postdot_phase:\n # We didn't find a dot, so the expression end at the\n # last identifier pos.\n break\n\n ret = self._eat_identifier(rawtext, brck_limit, pos)\n if ret:\n # There is an identifier to eat\n pos = pos - ret\n last_identifier_pos = pos\n # Now, to continue the search, we must find a dot.\n postdot_phase = False\n # (the loop continues now)\n\n elif pos == brck_limit:\n # We are at a bracketing limit. If it is a closing\n # bracket, eat the bracket, otherwise, stop the search.\n level = bracketing[brck_index][1]\n while brck_index > 0 and bracketing[brck_index - 1][1] > level:\n brck_index -= 1\n if bracketing[brck_index][0] == brck_limit:\n # We were not at the end of a closing bracket\n break\n pos = bracketing[brck_index][0]\n brck_index -= 1\n brck_limit = bracketing[brck_index][0]\n last_identifier_pos = pos\n if rawtext[pos] in \"([\":\n # [] and () may be used after an identifier, so we\n # continue. postdot_phase is True, so we don't allow a dot.\n pass\n else:\n # We can't continue after other types of brackets\n if rawtext[pos] in \"'\\\"\":\n # Scan a string prefix\n while pos > 0 and rawtext[pos - 1] in \"rRbBuU\":\n pos -= 1\n last_identifier_pos = pos\n break\n\n else:\n # We've found an operator or something.\n break\n\n return rawtext[last_identifier_pos : self.indexinrawtext]", "has_branch": true, "total_branches": 2} {"prompt_id": 645, "project": "tornado", "module": "tornado.auth", "class": "OpenIdMixin", "method": "authenticate_redirect", "focal_method_txt": " def authenticate_redirect(\n self,\n callback_uri: Optional[str] = None,\n ax_attrs: List[str] = [\"name\", \"email\", \"language\", \"username\"],\n ) -> None:\n \"\"\"Redirects to the authentication URL for this service.\n\n After authentication, the service will redirect back to the given\n callback URI with additional parameters including ``openid.mode``.\n\n We request the given attributes for the authenticated user by\n default (name, email, language, and username). If you don't need\n all those attributes for your app, you can request fewer with\n the ax_attrs keyword argument.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed and this method no\n longer returns an awaitable object. It is now an ordinary\n synchronous function.\n \"\"\"\n handler = cast(RequestHandler, self)\n callback_uri = callback_uri or handler.request.uri\n assert callback_uri is not None\n args = self._openid_args(callback_uri, ax_attrs=ax_attrs)\n endpoint = self._OPENID_ENDPOINT # type: ignore\n handler.redirect(endpoint + \"?\" + urllib.parse.urlencode(args))", "focal_method_lines": [87, 113], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OpenIdMixin(object):\n\n def authenticate_redirect(\n self,\n callback_uri: Optional[str] = None,\n ax_attrs: List[str] = [\"name\", \"email\", \"language\", \"username\"],\n ) -> None:\n \"\"\"Redirects to the authentication URL for this service.\n\n After authentication, the service will redirect back to the given\n callback URI with additional parameters including ``openid.mode``.\n\n We request the given attributes for the authenticated user by\n default (name, email, language, and username). If you don't need\n all those attributes for your app, you can request fewer with\n the ax_attrs keyword argument.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed and this method no\n longer returns an awaitable object. It is now an ordinary\n synchronous function.\n \"\"\"\n handler = cast(RequestHandler, self)\n callback_uri = callback_uri or handler.request.uri\n assert callback_uri is not None\n args = self._openid_args(callback_uri, ax_attrs=ax_attrs)\n endpoint = self._OPENID_ENDPOINT # type: ignore\n handler.redirect(endpoint + \"?\" + urllib.parse.urlencode(args))", "has_branch": false, "total_branches": 0} {"prompt_id": 646, "project": "tornado", "module": "tornado.auth", "class": "OpenIdMixin", "method": "get_authenticated_user", "focal_method_txt": " async def get_authenticated_user(\n self, http_client: Optional[httpclient.AsyncHTTPClient] = None\n ) -> Dict[str, Any]:\n \"\"\"Fetches the authenticated user data upon redirect.\n\n This method should be called by the handler that receives the\n redirect from the `authenticate_redirect()` method (which is\n often the same as the one that calls it; in that case you would\n call `get_authenticated_user` if the ``openid.mode`` parameter\n is present and `authenticate_redirect` if it is not).\n\n The result of this method will generally be used to set a cookie.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n handler = cast(RequestHandler, self)\n # Verify the OpenID response via direct request to the OP\n args = dict(\n (k, v[-1]) for k, v in handler.request.arguments.items()\n ) # type: Dict[str, Union[str, bytes]]\n args[\"openid.mode\"] = u\"check_authentication\"\n url = self._OPENID_ENDPOINT # type: ignore\n if http_client is None:\n http_client = self.get_auth_http_client()\n resp = await http_client.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(args)\n )\n return self._on_authentication_verified(resp)", "focal_method_lines": [115, 145], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OpenIdMixin(object):\n\n async def get_authenticated_user(\n self, http_client: Optional[httpclient.AsyncHTTPClient] = None\n ) -> Dict[str, Any]:\n \"\"\"Fetches the authenticated user data upon redirect.\n\n This method should be called by the handler that receives the\n redirect from the `authenticate_redirect()` method (which is\n often the same as the one that calls it; in that case you would\n call `get_authenticated_user` if the ``openid.mode`` parameter\n is present and `authenticate_redirect` if it is not).\n\n The result of this method will generally be used to set a cookie.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n handler = cast(RequestHandler, self)\n # Verify the OpenID response via direct request to the OP\n args = dict(\n (k, v[-1]) for k, v in handler.request.arguments.items()\n ) # type: Dict[str, Union[str, bytes]]\n args[\"openid.mode\"] = u\"check_authentication\"\n url = self._OPENID_ENDPOINT # type: ignore\n if http_client is None:\n http_client = self.get_auth_http_client()\n resp = await http_client.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(args)\n )\n return self._on_authentication_verified(resp)", "has_branch": true, "total_branches": 2} {"prompt_id": 647, "project": "tornado", "module": "tornado.auth", "class": "OAuthMixin", "method": "authorize_redirect", "focal_method_txt": " async def authorize_redirect(\n self,\n callback_uri: Optional[str] = None,\n extra_params: Optional[Dict[str, Any]] = None,\n http_client: Optional[httpclient.AsyncHTTPClient] = None,\n ) -> None:\n \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n The ``callback_uri`` may be omitted if you have previously\n registered a callback URI with the third-party service. For\n some services, you must use a previously-registered callback\n URI and cannot specify a callback via this method.\n\n This method sets a cookie called ``_oauth_request_token`` which is\n subsequently used (and cleared) in `get_authenticated_user` for\n security purposes.\n\n This method is asynchronous and must be called with ``await``\n or ``yield`` (This is different from other ``auth*_redirect``\n methods defined in this module). It calls\n `.RequestHandler.finish` for you so you should not write any\n other response after it returns.\n\n .. versionchanged:: 3.1\n Now returns a `.Future` and takes an optional callback, for\n compatibility with `.gen.coroutine`.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n\n \"\"\"\n if callback_uri and getattr(self, \"_OAUTH_NO_CALLBACKS\", False):\n raise Exception(\"This service does not support oauth_callback\")\n if http_client is None:\n http_client = self.get_auth_http_client()\n assert http_client is not None\n if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n response = await http_client.fetch(\n self._oauth_request_token_url(\n callback_uri=callback_uri, extra_params=extra_params\n )\n )\n else:\n response = await http_client.fetch(self._oauth_request_token_url())\n url = self._OAUTH_AUTHORIZE_URL # type: ignore\n self._on_request_token(url, callback_uri, response)", "focal_method_lines": [289, 336], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OAuthMixin(object):\n\n async def authorize_redirect(\n self,\n callback_uri: Optional[str] = None,\n extra_params: Optional[Dict[str, Any]] = None,\n http_client: Optional[httpclient.AsyncHTTPClient] = None,\n ) -> None:\n \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n The ``callback_uri`` may be omitted if you have previously\n registered a callback URI with the third-party service. For\n some services, you must use a previously-registered callback\n URI and cannot specify a callback via this method.\n\n This method sets a cookie called ``_oauth_request_token`` which is\n subsequently used (and cleared) in `get_authenticated_user` for\n security purposes.\n\n This method is asynchronous and must be called with ``await``\n or ``yield`` (This is different from other ``auth*_redirect``\n methods defined in this module). It calls\n `.RequestHandler.finish` for you so you should not write any\n other response after it returns.\n\n .. versionchanged:: 3.1\n Now returns a `.Future` and takes an optional callback, for\n compatibility with `.gen.coroutine`.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n\n \"\"\"\n if callback_uri and getattr(self, \"_OAUTH_NO_CALLBACKS\", False):\n raise Exception(\"This service does not support oauth_callback\")\n if http_client is None:\n http_client = self.get_auth_http_client()\n assert http_client is not None\n if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n response = await http_client.fetch(\n self._oauth_request_token_url(\n callback_uri=callback_uri, extra_params=extra_params\n )\n )\n else:\n response = await http_client.fetch(self._oauth_request_token_url())\n url = self._OAUTH_AUTHORIZE_URL # type: ignore\n self._on_request_token(url, callback_uri, response)", "has_branch": true, "total_branches": 2} {"prompt_id": 648, "project": "tornado", "module": "tornado.auth", "class": "OAuthMixin", "method": "get_authenticated_user", "focal_method_txt": " async def get_authenticated_user(\n self, http_client: Optional[httpclient.AsyncHTTPClient] = None\n ) -> Dict[str, Any]:\n \"\"\"Gets the OAuth authorized user and access token.\n\n This method should be called from the handler for your\n OAuth callback URL to complete the registration process. We run the\n callback with the authenticated user dictionary. This dictionary\n will contain an ``access_key`` which can be used to make authorized\n requests to this service on behalf of the user. The dictionary will\n also contain other fields such as ``name``, depending on the service\n used.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n handler = cast(RequestHandler, self)\n request_key = escape.utf8(handler.get_argument(\"oauth_token\"))\n oauth_verifier = handler.get_argument(\"oauth_verifier\", None)\n request_cookie = handler.get_cookie(\"_oauth_request_token\")\n if not request_cookie:\n raise AuthError(\"Missing OAuth request token cookie\")\n handler.clear_cookie(\"_oauth_request_token\")\n cookie_key, cookie_secret = [\n base64.b64decode(escape.utf8(i)) for i in request_cookie.split(\"|\")\n ]\n if cookie_key != request_key:\n raise AuthError(\"Request token does not match cookie\")\n token = dict(\n key=cookie_key, secret=cookie_secret\n ) # type: Dict[str, Union[str, bytes]]\n if oauth_verifier:\n token[\"verifier\"] = oauth_verifier\n if http_client is None:\n http_client = self.get_auth_http_client()\n assert http_client is not None\n response = await http_client.fetch(self._oauth_access_token_url(token))\n access_token = _oauth_parse_response(response.body)\n user = await self._oauth_get_user_future(access_token)\n if not user:\n raise AuthError(\"Error getting user\")\n user[\"access_token\"] = access_token\n return user", "focal_method_lines": [338, 382], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OAuthMixin(object):\n\n async def get_authenticated_user(\n self, http_client: Optional[httpclient.AsyncHTTPClient] = None\n ) -> Dict[str, Any]:\n \"\"\"Gets the OAuth authorized user and access token.\n\n This method should be called from the handler for your\n OAuth callback URL to complete the registration process. We run the\n callback with the authenticated user dictionary. This dictionary\n will contain an ``access_key`` which can be used to make authorized\n requests to this service on behalf of the user. The dictionary will\n also contain other fields such as ``name``, depending on the service\n used.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n handler = cast(RequestHandler, self)\n request_key = escape.utf8(handler.get_argument(\"oauth_token\"))\n oauth_verifier = handler.get_argument(\"oauth_verifier\", None)\n request_cookie = handler.get_cookie(\"_oauth_request_token\")\n if not request_cookie:\n raise AuthError(\"Missing OAuth request token cookie\")\n handler.clear_cookie(\"_oauth_request_token\")\n cookie_key, cookie_secret = [\n base64.b64decode(escape.utf8(i)) for i in request_cookie.split(\"|\")\n ]\n if cookie_key != request_key:\n raise AuthError(\"Request token does not match cookie\")\n token = dict(\n key=cookie_key, secret=cookie_secret\n ) # type: Dict[str, Union[str, bytes]]\n if oauth_verifier:\n token[\"verifier\"] = oauth_verifier\n if http_client is None:\n http_client = self.get_auth_http_client()\n assert http_client is not None\n response = await http_client.fetch(self._oauth_access_token_url(token))\n access_token = _oauth_parse_response(response.body)\n user = await self._oauth_get_user_future(access_token)\n if not user:\n raise AuthError(\"Error getting user\")\n user[\"access_token\"] = access_token\n return user", "has_branch": true, "total_branches": 2} {"prompt_id": 649, "project": "tornado", "module": "tornado.auth", "class": "OAuth2Mixin", "method": "authorize_redirect", "focal_method_txt": " def authorize_redirect(\n self,\n redirect_uri: Optional[str] = None,\n client_id: Optional[str] = None,\n client_secret: Optional[str] = None,\n extra_params: Optional[Dict[str, Any]] = None,\n scope: Optional[List[str]] = None,\n response_type: str = \"code\",\n ) -> None:\n \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n Some providers require that you register a redirect URL with\n your application instead of passing one via this method. You\n should call this method to log the user in, and then call\n ``get_authenticated_user`` in the handler for your\n redirect URL to complete the authorization process.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument and returned awaitable were removed;\n this is now an ordinary synchronous function.\n \"\"\"\n handler = cast(RequestHandler, self)\n args = {\"response_type\": response_type}\n if redirect_uri is not None:\n args[\"redirect_uri\"] = redirect_uri\n if client_id is not None:\n args[\"client_id\"] = client_id\n if extra_params:\n args.update(extra_params)\n if scope:\n args[\"scope\"] = \" \".join(scope)\n url = self._OAUTH_AUTHORIZE_URL # type: ignore\n handler.redirect(url_concat(url, args))", "focal_method_lines": [552, 585], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OAuth2Mixin(object):\n\n def authorize_redirect(\n self,\n redirect_uri: Optional[str] = None,\n client_id: Optional[str] = None,\n client_secret: Optional[str] = None,\n extra_params: Optional[Dict[str, Any]] = None,\n scope: Optional[List[str]] = None,\n response_type: str = \"code\",\n ) -> None:\n \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n Some providers require that you register a redirect URL with\n your application instead of passing one via this method. You\n should call this method to log the user in, and then call\n ``get_authenticated_user`` in the handler for your\n redirect URL to complete the authorization process.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument and returned awaitable were removed;\n this is now an ordinary synchronous function.\n \"\"\"\n handler = cast(RequestHandler, self)\n args = {\"response_type\": response_type}\n if redirect_uri is not None:\n args[\"redirect_uri\"] = redirect_uri\n if client_id is not None:\n args[\"client_id\"] = client_id\n if extra_params:\n args.update(extra_params)\n if scope:\n args[\"scope\"] = \" \".join(scope)\n url = self._OAUTH_AUTHORIZE_URL # type: ignore\n handler.redirect(url_concat(url, args))", "has_branch": true, "total_branches": 2} {"prompt_id": 650, "project": "tornado", "module": "tornado.auth", "class": "OAuth2Mixin", "method": "oauth2_request", "focal_method_txt": " async def oauth2_request(\n self,\n url: str,\n access_token: Optional[str] = None,\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given URL auth an OAuth2 access token.\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n Example usage:\n\n ..testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.oauth2_request(\n \"https://graph.facebook.com/me/feed\",\n post_args={\"message\": \"I am posting from my Tornado application!\"},\n access_token=self.current_user[\"access_token\"])\n\n if not new_entry:\n # Call failed; perhaps missing permission?\n self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n .. versionadded:: 4.3\n\n .. versionchanged::: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n all_args = {}\n if access_token:\n all_args[\"access_token\"] = access_token\n all_args.update(args)\n\n if all_args:\n url += \"?\" + urllib.parse.urlencode(all_args)\n http = self.get_auth_http_client()\n if post_args is not None:\n response = await http.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(post_args)\n )\n else:\n response = await http.fetch(url)\n return escape.json_decode(response.body)", "focal_method_lines": [609, 663], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass OAuth2Mixin(object):\n\n async def oauth2_request(\n self,\n url: str,\n access_token: Optional[str] = None,\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given URL auth an OAuth2 access token.\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n Example usage:\n\n ..testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.oauth2_request(\n \"https://graph.facebook.com/me/feed\",\n post_args={\"message\": \"I am posting from my Tornado application!\"},\n access_token=self.current_user[\"access_token\"])\n\n if not new_entry:\n # Call failed; perhaps missing permission?\n self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n .. versionadded:: 4.3\n\n .. versionchanged::: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n all_args = {}\n if access_token:\n all_args[\"access_token\"] = access_token\n all_args.update(args)\n\n if all_args:\n url += \"?\" + urllib.parse.urlencode(all_args)\n http = self.get_auth_http_client()\n if post_args is not None:\n response = await http.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(post_args)\n )\n else:\n response = await http.fetch(url)\n return escape.json_decode(response.body)", "has_branch": true, "total_branches": 2} {"prompt_id": 651, "project": "tornado", "module": "tornado.auth", "class": "TwitterMixin", "method": "authenticate_redirect", "focal_method_txt": " async def authenticate_redirect(self, callback_uri: Optional[str] = None) -> None:\n \"\"\"Just like `~OAuthMixin.authorize_redirect`, but\n auto-redirects if authorized.\n\n This is generally the right interface to use if you are using\n Twitter for single-sign on.\n\n .. versionchanged:: 3.1\n Now returns a `.Future` and takes an optional callback, for\n compatibility with `.gen.coroutine`.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n http = self.get_auth_http_client()\n response = await http.fetch(\n self._oauth_request_token_url(callback_uri=callback_uri)\n )\n self._on_request_token(self._OAUTH_AUTHENTICATE_URL, None, response)", "focal_method_lines": [716, 736], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass TwitterMixin(OAuthMixin):\n\n _OAUTH_REQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\n\n _OAUTH_ACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n\n _OAUTH_AUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\n\n _OAUTH_AUTHENTICATE_URL = \"https://api.twitter.com/oauth/authenticate\"\n\n _OAUTH_NO_CALLBACKS = False\n\n _TWITTER_BASE_URL = \"https://api.twitter.com/1.1\"\n\n async def authenticate_redirect(self, callback_uri: Optional[str] = None) -> None:\n \"\"\"Just like `~OAuthMixin.authorize_redirect`, but\n auto-redirects if authorized.\n\n This is generally the right interface to use if you are using\n Twitter for single-sign on.\n\n .. versionchanged:: 3.1\n Now returns a `.Future` and takes an optional callback, for\n compatibility with `.gen.coroutine`.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n http = self.get_auth_http_client()\n response = await http.fetch(\n self._oauth_request_token_url(callback_uri=callback_uri)\n )\n self._on_request_token(self._OAUTH_AUTHENTICATE_URL, None, response)", "has_branch": false, "total_branches": 0} {"prompt_id": 652, "project": "tornado", "module": "tornado.auth", "class": "TwitterMixin", "method": "twitter_request", "focal_method_txt": " async def twitter_request(\n self,\n path: str,\n access_token: Dict[str, Any],\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n The path should not include the format or API version number.\n (we automatically use JSON format and API version 1).\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n All the Twitter methods are documented at http://dev.twitter.com/\n\n Many methods require an OAuth access token which you can\n obtain through `~OAuthMixin.authorize_redirect` and\n `~OAuthMixin.get_authenticated_user`. The user returned through that\n process includes an 'access_token' attribute that can be used\n to make authenticated requests via this method. Example\n usage:\n\n .. testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.TwitterMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.twitter_request(\n \"/statuses/update\",\n post_args={\"status\": \"Testing Tornado Web Server\"},\n access_token=self.current_user[\"access_token\"])\n if not new_entry:\n # Call failed; perhaps missing permission?\n await self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n if path.startswith(\"http:\") or path.startswith(\"https:\"):\n # Raw urls are useful for e.g. search which doesn't follow the\n # usual pattern: http://search.twitter.com/search.json\n url = path\n else:\n url = self._TWITTER_BASE_URL + path + \".json\"\n # Add the OAuth resource request signature if we have credentials\n if access_token:\n all_args = {}\n all_args.update(args)\n all_args.update(post_args or {})\n method = \"POST\" if post_args is not None else \"GET\"\n oauth = self._oauth_request_parameters(\n url, access_token, all_args, method=method\n )\n args.update(oauth)\n if args:\n url += \"?\" + urllib.parse.urlencode(args)\n http = self.get_auth_http_client()\n if post_args is not None:\n response = await http.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(post_args)\n )\n else:\n response = await http.fetch(url)\n return escape.json_decode(response.body)", "focal_method_lines": [738, 811], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass TwitterMixin(OAuthMixin):\n\n _OAUTH_REQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\n\n _OAUTH_ACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n\n _OAUTH_AUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\n\n _OAUTH_AUTHENTICATE_URL = \"https://api.twitter.com/oauth/authenticate\"\n\n _OAUTH_NO_CALLBACKS = False\n\n _TWITTER_BASE_URL = \"https://api.twitter.com/1.1\"\n\n async def twitter_request(\n self,\n path: str,\n access_token: Dict[str, Any],\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n The path should not include the format or API version number.\n (we automatically use JSON format and API version 1).\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n All the Twitter methods are documented at http://dev.twitter.com/\n\n Many methods require an OAuth access token which you can\n obtain through `~OAuthMixin.authorize_redirect` and\n `~OAuthMixin.get_authenticated_user`. The user returned through that\n process includes an 'access_token' attribute that can be used\n to make authenticated requests via this method. Example\n usage:\n\n .. testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.TwitterMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.twitter_request(\n \"/statuses/update\",\n post_args={\"status\": \"Testing Tornado Web Server\"},\n access_token=self.current_user[\"access_token\"])\n if not new_entry:\n # Call failed; perhaps missing permission?\n await self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n awaitable object instead.\n \"\"\"\n if path.startswith(\"http:\") or path.startswith(\"https:\"):\n # Raw urls are useful for e.g. search which doesn't follow the\n # usual pattern: http://search.twitter.com/search.json\n url = path\n else:\n url = self._TWITTER_BASE_URL + path + \".json\"\n # Add the OAuth resource request signature if we have credentials\n if access_token:\n all_args = {}\n all_args.update(args)\n all_args.update(post_args or {})\n method = \"POST\" if post_args is not None else \"GET\"\n oauth = self._oauth_request_parameters(\n url, access_token, all_args, method=method\n )\n args.update(oauth)\n if args:\n url += \"?\" + urllib.parse.urlencode(args)\n http = self.get_auth_http_client()\n if post_args is not None:\n response = await http.fetch(\n url, method=\"POST\", body=urllib.parse.urlencode(post_args)\n )\n else:\n response = await http.fetch(url)\n return escape.json_decode(response.body)", "has_branch": true, "total_branches": 2} {"prompt_id": 653, "project": "tornado", "module": "tornado.auth", "class": "GoogleOAuth2Mixin", "method": "get_authenticated_user", "focal_method_txt": " async def get_authenticated_user(\n self, redirect_uri: str, code: str\n ) -> Dict[str, Any]:\n \"\"\"Handles the login for the Google user, returning an access token.\n\n The result is a dictionary containing an ``access_token`` field\n ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n Unlike other ``get_authenticated_user`` methods in this package,\n this method does not return any additional information about the user.\n The returned access token can be used with `OAuth2Mixin.oauth2_request`\n to request additional information (perhaps from\n ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n Example usage:\n\n .. testcode::\n\n class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n tornado.auth.GoogleOAuth2Mixin):\n async def get(self):\n if self.get_argument('code', False):\n access = await self.get_authenticated_user(\n redirect_uri='http://your.site.com/auth/google',\n code=self.get_argument('code'))\n user = await self.oauth2_request(\n \"https://www.googleapis.com/oauth2/v1/userinfo\",\n access_token=access[\"access_token\"])\n # Save the user and access token with\n # e.g. set_secure_cookie.\n else:\n self.authorize_redirect(\n redirect_uri='http://your.site.com/auth/google',\n client_id=self.settings['google_oauth']['key'],\n scope=['profile', 'email'],\n response_type='code',\n extra_params={'approval_prompt': 'auto'})\n\n .. testoutput::\n :hide:\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\" # noqa: E501\n handler = cast(RequestHandler, self)\n http = self.get_auth_http_client()\n body = urllib.parse.urlencode(\n {\n \"redirect_uri\": redirect_uri,\n \"code\": code,\n \"client_id\": handler.settings[self._OAUTH_SETTINGS_KEY][\"key\"],\n \"client_secret\": handler.settings[self._OAUTH_SETTINGS_KEY][\"secret\"],\n \"grant_type\": \"authorization_code\",\n }\n )\n\n response = await http.fetch(\n self._OAUTH_ACCESS_TOKEN_URL,\n method=\"POST\",\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n body=body,\n )\n return escape.json_decode(response.body)", "focal_method_lines": [858, 920], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass GoogleOAuth2Mixin(OAuth2Mixin):\n\n _OAUTH_AUTHORIZE_URL = \"https://accounts.google.com/o/oauth2/v2/auth\"\n\n _OAUTH_ACCESS_TOKEN_URL = \"https://www.googleapis.com/oauth2/v4/token\"\n\n _OAUTH_USERINFO_URL = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n\n _OAUTH_NO_CALLBACKS = False\n\n _OAUTH_SETTINGS_KEY = \"google_oauth\"\n\n async def get_authenticated_user(\n self, redirect_uri: str, code: str\n ) -> Dict[str, Any]:\n \"\"\"Handles the login for the Google user, returning an access token.\n\n The result is a dictionary containing an ``access_token`` field\n ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n Unlike other ``get_authenticated_user`` methods in this package,\n this method does not return any additional information about the user.\n The returned access token can be used with `OAuth2Mixin.oauth2_request`\n to request additional information (perhaps from\n ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n Example usage:\n\n .. testcode::\n\n class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n tornado.auth.GoogleOAuth2Mixin):\n async def get(self):\n if self.get_argument('code', False):\n access = await self.get_authenticated_user(\n redirect_uri='http://your.site.com/auth/google',\n code=self.get_argument('code'))\n user = await self.oauth2_request(\n \"https://www.googleapis.com/oauth2/v1/userinfo\",\n access_token=access[\"access_token\"])\n # Save the user and access token with\n # e.g. set_secure_cookie.\n else:\n self.authorize_redirect(\n redirect_uri='http://your.site.com/auth/google',\n client_id=self.settings['google_oauth']['key'],\n scope=['profile', 'email'],\n response_type='code',\n extra_params={'approval_prompt': 'auto'})\n\n .. testoutput::\n :hide:\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\" # noqa: E501\n handler = cast(RequestHandler, self)\n http = self.get_auth_http_client()\n body = urllib.parse.urlencode(\n {\n \"redirect_uri\": redirect_uri,\n \"code\": code,\n \"client_id\": handler.settings[self._OAUTH_SETTINGS_KEY][\"key\"],\n \"client_secret\": handler.settings[self._OAUTH_SETTINGS_KEY][\"secret\"],\n \"grant_type\": \"authorization_code\",\n }\n )\n\n response = await http.fetch(\n self._OAUTH_ACCESS_TOKEN_URL,\n method=\"POST\",\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n body=body,\n )\n return escape.json_decode(response.body)", "has_branch": false, "total_branches": 0} {"prompt_id": 654, "project": "tornado", "module": "tornado.auth", "class": "FacebookGraphMixin", "method": "get_authenticated_user", "focal_method_txt": " async def get_authenticated_user(\n self,\n redirect_uri: str,\n client_id: str,\n client_secret: str,\n code: str,\n extra_fields: Optional[Dict[str, Any]] = None,\n ) -> Optional[Dict[str, Any]]:\n \"\"\"Handles the login for the Facebook user, returning a user object.\n\n Example usage:\n\n .. testcode::\n\n class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n async def get(self):\n if self.get_argument(\"code\", False):\n user = await self.get_authenticated_user(\n redirect_uri='/auth/facebookgraph/',\n client_id=self.settings[\"facebook_api_key\"],\n client_secret=self.settings[\"facebook_secret\"],\n code=self.get_argument(\"code\"))\n # Save the user with e.g. set_secure_cookie\n else:\n self.authorize_redirect(\n redirect_uri='/auth/facebookgraph/',\n client_id=self.settings[\"facebook_api_key\"],\n extra_params={\"scope\": \"read_stream,offline_access\"})\n\n .. testoutput::\n :hide:\n\n This method returns a dictionary which may contain the following fields:\n\n * ``access_token``, a string which may be passed to `facebook_request`\n * ``session_expires``, an integer encoded as a string representing\n the time until the access token expires in seconds. This field should\n be used like ``int(user['session_expires'])``; in a future version of\n Tornado it will change from a string to an integer.\n * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``,\n ``link``, plus any fields named in the ``extra_fields`` argument. These\n fields are copied from the Facebook graph API\n `user object `_\n\n .. versionchanged:: 4.5\n The ``session_expires`` field was updated to support changes made to the\n Facebook API in March 2017.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n http = self.get_auth_http_client()\n args = {\n \"redirect_uri\": redirect_uri,\n \"code\": code,\n \"client_id\": client_id,\n \"client_secret\": client_secret,\n }\n\n fields = set(\n [\"id\", \"name\", \"first_name\", \"last_name\", \"locale\", \"picture\", \"link\"]\n )\n if extra_fields:\n fields.update(extra_fields)\n\n response = await http.fetch(\n self._oauth_request_token_url(**args) # type: ignore\n )\n args = escape.json_decode(response.body)\n session = {\n \"access_token\": args.get(\"access_token\"),\n \"expires_in\": args.get(\"expires_in\"),\n }\n assert session[\"access_token\"] is not None\n\n user = await self.facebook_request(\n path=\"/me\",\n access_token=session[\"access_token\"],\n appsecret_proof=hmac.new(\n key=client_secret.encode(\"utf8\"),\n msg=session[\"access_token\"].encode(\"utf8\"),\n digestmod=hashlib.sha256,\n ).hexdigest(),\n fields=\",\".join(fields),\n )\n\n if user is None:\n return None\n\n fieldmap = {}\n for field in fields:\n fieldmap[field] = user.get(field)\n\n # session_expires is converted to str for compatibility with\n # older versions in which the server used url-encoding and\n # this code simply returned the string verbatim.\n # This should change in Tornado 5.0.\n fieldmap.update(\n {\n \"access_token\": session[\"access_token\"],\n \"session_expires\": str(session.get(\"expires_in\")),\n }\n )\n return fieldmap", "focal_method_lines": [931, 1036], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass FacebookGraphMixin(OAuth2Mixin):\n\n _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n\n _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n\n _OAUTH_NO_CALLBACKS = False\n\n _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n async def get_authenticated_user(\n self,\n redirect_uri: str,\n client_id: str,\n client_secret: str,\n code: str,\n extra_fields: Optional[Dict[str, Any]] = None,\n ) -> Optional[Dict[str, Any]]:\n \"\"\"Handles the login for the Facebook user, returning a user object.\n\n Example usage:\n\n .. testcode::\n\n class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n async def get(self):\n if self.get_argument(\"code\", False):\n user = await self.get_authenticated_user(\n redirect_uri='/auth/facebookgraph/',\n client_id=self.settings[\"facebook_api_key\"],\n client_secret=self.settings[\"facebook_secret\"],\n code=self.get_argument(\"code\"))\n # Save the user with e.g. set_secure_cookie\n else:\n self.authorize_redirect(\n redirect_uri='/auth/facebookgraph/',\n client_id=self.settings[\"facebook_api_key\"],\n extra_params={\"scope\": \"read_stream,offline_access\"})\n\n .. testoutput::\n :hide:\n\n This method returns a dictionary which may contain the following fields:\n\n * ``access_token``, a string which may be passed to `facebook_request`\n * ``session_expires``, an integer encoded as a string representing\n the time until the access token expires in seconds. This field should\n be used like ``int(user['session_expires'])``; in a future version of\n Tornado it will change from a string to an integer.\n * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``,\n ``link``, plus any fields named in the ``extra_fields`` argument. These\n fields are copied from the Facebook graph API\n `user object `_\n\n .. versionchanged:: 4.5\n The ``session_expires`` field was updated to support changes made to the\n Facebook API in March 2017.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n http = self.get_auth_http_client()\n args = {\n \"redirect_uri\": redirect_uri,\n \"code\": code,\n \"client_id\": client_id,\n \"client_secret\": client_secret,\n }\n\n fields = set(\n [\"id\", \"name\", \"first_name\", \"last_name\", \"locale\", \"picture\", \"link\"]\n )\n if extra_fields:\n fields.update(extra_fields)\n\n response = await http.fetch(\n self._oauth_request_token_url(**args) # type: ignore\n )\n args = escape.json_decode(response.body)\n session = {\n \"access_token\": args.get(\"access_token\"),\n \"expires_in\": args.get(\"expires_in\"),\n }\n assert session[\"access_token\"] is not None\n\n user = await self.facebook_request(\n path=\"/me\",\n access_token=session[\"access_token\"],\n appsecret_proof=hmac.new(\n key=client_secret.encode(\"utf8\"),\n msg=session[\"access_token\"].encode(\"utf8\"),\n digestmod=hashlib.sha256,\n ).hexdigest(),\n fields=\",\".join(fields),\n )\n\n if user is None:\n return None\n\n fieldmap = {}\n for field in fields:\n fieldmap[field] = user.get(field)\n\n # session_expires is converted to str for compatibility with\n # older versions in which the server used url-encoding and\n # this code simply returned the string verbatim.\n # This should change in Tornado 5.0.\n fieldmap.update(\n {\n \"access_token\": session[\"access_token\"],\n \"session_expires\": str(session.get(\"expires_in\")),\n }\n )\n return fieldmap", "has_branch": true, "total_branches": 2} {"prompt_id": 655, "project": "tornado", "module": "tornado.auth", "class": "FacebookGraphMixin", "method": "facebook_request", "focal_method_txt": " async def facebook_request(\n self,\n path: str,\n access_token: Optional[str] = None,\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n An introduction to the Facebook Graph API can be found at\n http://developers.facebook.com/docs/api\n\n Many methods require an OAuth access token which you can\n obtain through `~OAuth2Mixin.authorize_redirect` and\n `get_authenticated_user`. The user returned through that\n process includes an ``access_token`` attribute that can be\n used to make authenticated requests via this method.\n\n Example usage:\n\n .. testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.facebook_request(\n \"/me/feed\",\n post_args={\"message\": \"I am posting from my Tornado application!\"},\n access_token=self.current_user[\"access_token\"])\n\n if not new_entry:\n # Call failed; perhaps missing permission?\n self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n The given path is relative to ``self._FACEBOOK_BASE_URL``,\n by default \"https://graph.facebook.com\".\n\n This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n the only difference is that this method takes a relative path,\n while ``oauth2_request`` takes a complete url.\n\n .. versionchanged:: 3.1\n Added the ability to override ``self._FACEBOOK_BASE_URL``.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n url = self._FACEBOOK_BASE_URL + path\n return await self.oauth2_request(\n url, access_token=access_token, post_args=post_args, **args\n )", "focal_method_lines": [1038, 1096], "in_stack": false, "globals": [], "type_context": "import base64\nimport binascii\nimport hashlib\nimport hmac\nimport time\nimport urllib.parse\nimport uuid\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.util import unicode_type\nfrom tornado.web import RequestHandler\nfrom typing import List, Any, Dict, cast, Iterable, Union, Optional\n\n\n\nclass FacebookGraphMixin(OAuth2Mixin):\n\n _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n\n _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n\n _OAUTH_NO_CALLBACKS = False\n\n _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n async def facebook_request(\n self,\n path: str,\n access_token: Optional[str] = None,\n post_args: Optional[Dict[str, Any]] = None,\n **args: Any\n ) -> Any:\n \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n An introduction to the Facebook Graph API can be found at\n http://developers.facebook.com/docs/api\n\n Many methods require an OAuth access token which you can\n obtain through `~OAuth2Mixin.authorize_redirect` and\n `get_authenticated_user`. The user returned through that\n process includes an ``access_token`` attribute that can be\n used to make authenticated requests via this method.\n\n Example usage:\n\n .. testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n @tornado.web.authenticated\n async def get(self):\n new_entry = await self.facebook_request(\n \"/me/feed\",\n post_args={\"message\": \"I am posting from my Tornado application!\"},\n access_token=self.current_user[\"access_token\"])\n\n if not new_entry:\n # Call failed; perhaps missing permission?\n self.authorize_redirect()\n return\n self.finish(\"Posted a message!\")\n\n .. testoutput::\n :hide:\n\n The given path is relative to ``self._FACEBOOK_BASE_URL``,\n by default \"https://graph.facebook.com\".\n\n This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n the only difference is that this method takes a relative path,\n while ``oauth2_request`` takes a complete url.\n\n .. versionchanged:: 3.1\n Added the ability to override ``self._FACEBOOK_BASE_URL``.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned awaitable object instead.\n \"\"\"\n url = self._FACEBOOK_BASE_URL + path\n return await self.oauth2_request(\n url, access_token=access_token, post_args=post_args, **args\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 656, "project": "tornado", "module": "tornado.concurrent", "class": "", "method": "run_on_executor", "focal_method_txt": "def run_on_executor(*args: Any, **kwargs: Any) -> Callable:\n \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n Returns a future.\n\n The executor to be used is determined by the ``executor``\n attributes of ``self``. To use a different attribute name, pass a\n keyword argument to the decorator::\n\n @run_on_executor(executor='_thread_pool')\n def foo(self):\n pass\n\n This decorator should not be confused with the similarly-named\n `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n when *calling* a blocking method is recommended instead of using\n this decorator when *defining* a method. If compatibility with older\n versions of Tornado is required, consider defining an executor\n and using ``executor.submit()`` at the call site.\n\n .. versionchanged:: 4.2\n Added keyword arguments to use alternative attributes.\n\n .. versionchanged:: 5.0\n Always uses the current IOLoop instead of ``self.io_loop``.\n\n .. versionchanged:: 5.1\n Returns a `.Future` compatible with ``await`` instead of a\n `concurrent.futures.Future`.\n\n .. deprecated:: 5.1\n\n The ``callback`` argument is deprecated and will be removed in\n 6.0. The decorator itself is discouraged in new code but will\n not be removed in 6.0.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed.\n \"\"\"\n # Fully type-checking decorators is tricky, and this one is\n # discouraged anyway so it doesn't have all the generic magic.\n def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:\n executor = kwargs.get(\"executor\", \"executor\")\n\n @functools.wraps(fn)\n def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:\n async_future = Future() # type: Future\n conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n chain_future(conc_future, async_future)\n return async_future\n\n return wrapper\n\n if args and kwargs:\n raise ValueError(\"cannot combine positional and keyword args\")\n if len(args) == 1:\n return run_on_executor_decorator(args[0])\n elif len(args) != 0:\n raise ValueError(\"expected 1 argument, got %d\", len(args))\n return run_on_executor_decorator", "focal_method_lines": [73, 133], "in_stack": false, "globals": ["_T", "Future", "FUTURES", "dummy_executor", "_NO_RESULT"], "type_context": "import asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\nfrom tornado.log import app_log\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\nFuture = asyncio.Future\nFUTURES = (futures.Future, Future)\ndummy_executor = DummyExecutor()\n_NO_RESULT = object()\n\ndef run_on_executor(*args: Any, **kwargs: Any) -> Callable:\n \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n Returns a future.\n\n The executor to be used is determined by the ``executor``\n attributes of ``self``. To use a different attribute name, pass a\n keyword argument to the decorator::\n\n @run_on_executor(executor='_thread_pool')\n def foo(self):\n pass\n\n This decorator should not be confused with the similarly-named\n `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n when *calling* a blocking method is recommended instead of using\n this decorator when *defining* a method. If compatibility with older\n versions of Tornado is required, consider defining an executor\n and using ``executor.submit()`` at the call site.\n\n .. versionchanged:: 4.2\n Added keyword arguments to use alternative attributes.\n\n .. versionchanged:: 5.0\n Always uses the current IOLoop instead of ``self.io_loop``.\n\n .. versionchanged:: 5.1\n Returns a `.Future` compatible with ``await`` instead of a\n `concurrent.futures.Future`.\n\n .. deprecated:: 5.1\n\n The ``callback`` argument is deprecated and will be removed in\n 6.0. The decorator itself is discouraged in new code but will\n not be removed in 6.0.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed.\n \"\"\"\n # Fully type-checking decorators is tricky, and this one is\n # discouraged anyway so it doesn't have all the generic magic.\n def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:\n executor = kwargs.get(\"executor\", \"executor\")\n\n @functools.wraps(fn)\n def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:\n async_future = Future() # type: Future\n conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n chain_future(conc_future, async_future)\n return async_future\n\n return wrapper\n\n if args and kwargs:\n raise ValueError(\"cannot combine positional and keyword args\")\n if len(args) == 1:\n return run_on_executor_decorator(args[0])\n elif len(args) != 0:\n raise ValueError(\"expected 1 argument, got %d\", len(args))\n return run_on_executor_decorator", "has_branch": true, "total_branches": 2} {"prompt_id": 657, "project": "tornado", "module": "tornado.concurrent", "class": "", "method": "chain_future", "focal_method_txt": "def chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n \"\"\"Chain two futures together so that when one completes, so does the other.\n\n The result (success or failure) of ``a`` will be copied to ``b``, unless\n ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n .. versionchanged:: 5.0\n\n Now accepts both Tornado/asyncio `Future` objects and\n `concurrent.futures.Future`.\n\n \"\"\"\n\n def copy(future: \"Future[_T]\") -> None:\n assert future is a\n if b.done():\n return\n if hasattr(a, \"exc_info\") and a.exc_info() is not None: # type: ignore\n future_set_exc_info(b, a.exc_info()) # type: ignore\n elif a.exception() is not None:\n b.set_exception(a.exception())\n else:\n b.set_result(a.result())\n\n if isinstance(a, Future):\n future_add_done_callback(a, copy)\n else:\n # concurrent.futures.Future\n from tornado.ioloop import IOLoop\n\n IOLoop.current().add_future(a, copy)", "focal_method_lines": [139, 169], "in_stack": false, "globals": ["_T", "Future", "FUTURES", "dummy_executor", "_NO_RESULT"], "type_context": "import asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\nfrom tornado.log import app_log\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\nFuture = asyncio.Future\nFUTURES = (futures.Future, Future)\ndummy_executor = DummyExecutor()\n_NO_RESULT = object()\n\ndef chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n \"\"\"Chain two futures together so that when one completes, so does the other.\n\n The result (success or failure) of ``a`` will be copied to ``b``, unless\n ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n .. versionchanged:: 5.0\n\n Now accepts both Tornado/asyncio `Future` objects and\n `concurrent.futures.Future`.\n\n \"\"\"\n\n def copy(future: \"Future[_T]\") -> None:\n assert future is a\n if b.done():\n return\n if hasattr(a, \"exc_info\") and a.exc_info() is not None: # type: ignore\n future_set_exc_info(b, a.exc_info()) # type: ignore\n elif a.exception() is not None:\n b.set_exception(a.exception())\n else:\n b.set_result(a.result())\n\n if isinstance(a, Future):\n future_add_done_callback(a, copy)\n else:\n # concurrent.futures.Future\n from tornado.ioloop import IOLoop\n\n IOLoop.current().add_future(a, copy)", "has_branch": true, "total_branches": 2} {"prompt_id": 658, "project": "tornado", "module": "tornado.concurrent", "class": "", "method": "future_set_result_unless_cancelled", "focal_method_txt": "def future_set_result_unless_cancelled(\n future: \"Union[futures.Future[_T], Future[_T]]\", value: _T\n) -> None:\n \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on\n a cancelled `asyncio.Future`.\n\n .. versionadded:: 5.0\n \"\"\"\n if not future.cancelled():\n future.set_result(value)", "focal_method_lines": [172, 183], "in_stack": false, "globals": ["_T", "Future", "FUTURES", "dummy_executor", "_NO_RESULT"], "type_context": "import asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\nfrom tornado.log import app_log\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\nFuture = asyncio.Future\nFUTURES = (futures.Future, Future)\ndummy_executor = DummyExecutor()\n_NO_RESULT = object()\n\ndef future_set_result_unless_cancelled(\n future: \"Union[futures.Future[_T], Future[_T]]\", value: _T\n) -> None:\n \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on\n a cancelled `asyncio.Future`.\n\n .. versionadded:: 5.0\n \"\"\"\n if not future.cancelled():\n future.set_result(value)", "has_branch": true, "total_branches": 2} {"prompt_id": 659, "project": "tornado", "module": "tornado.concurrent", "class": "", "method": "future_set_exception_unless_cancelled", "focal_method_txt": "def future_set_exception_unless_cancelled(\n future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n \"\"\"Set the given ``exc`` as the `Future`'s exception.\n\n If the Future is already canceled, logs the exception instead. If\n this logging is not desired, the caller should explicitly check\n the state of the Future and call ``Future.set_exception`` instead of\n this wrapper.\n\n Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n a cancelled `asyncio.Future`.\n\n .. versionadded:: 6.0\n\n \"\"\"\n if not future.cancelled():\n future.set_exception(exc)\n else:\n app_log.error(\"Exception after Future was cancelled\", exc_info=exc)", "focal_method_lines": [186, 205], "in_stack": false, "globals": ["_T", "Future", "FUTURES", "dummy_executor", "_NO_RESULT"], "type_context": "import asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\nfrom tornado.log import app_log\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\nFuture = asyncio.Future\nFUTURES = (futures.Future, Future)\ndummy_executor = DummyExecutor()\n_NO_RESULT = object()\n\ndef future_set_exception_unless_cancelled(\n future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n \"\"\"Set the given ``exc`` as the `Future`'s exception.\n\n If the Future is already canceled, logs the exception instead. If\n this logging is not desired, the caller should explicitly check\n the state of the Future and call ``Future.set_exception`` instead of\n this wrapper.\n\n Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n a cancelled `asyncio.Future`.\n\n .. versionadded:: 6.0\n\n \"\"\"\n if not future.cancelled():\n future.set_exception(exc)\n else:\n app_log.error(\"Exception after Future was cancelled\", exc_info=exc)", "has_branch": true, "total_branches": 2} {"prompt_id": 660, "project": "tornado", "module": "tornado.concurrent", "class": "DummyExecutor", "method": "submit", "focal_method_txt": " def submit(\n self, fn: Callable[..., _T], *args: Any, **kwargs: Any\n ) -> \"futures.Future[_T]\":\n future = futures.Future() # type: futures.Future[_T]\n try:\n future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n except Exception:\n future_set_exc_info(future, sys.exc_info())\n return future", "focal_method_lines": [56, 64], "in_stack": false, "globals": ["_T", "Future", "FUTURES", "dummy_executor", "_NO_RESULT"], "type_context": "import asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\nfrom tornado.log import app_log\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\nFuture = asyncio.Future\nFUTURES = (futures.Future, Future)\ndummy_executor = DummyExecutor()\n_NO_RESULT = object()\n\nclass DummyExecutor(futures.Executor):\n\n def submit(\n self, fn: Callable[..., _T], *args: Any, **kwargs: Any\n ) -> \"futures.Future[_T]\":\n future = futures.Future() # type: futures.Future[_T]\n try:\n future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n except Exception:\n future_set_exc_info(future, sys.exc_info())\n return future", "has_branch": false, "total_branches": 0} {"prompt_id": 661, "project": "tornado", "module": "tornado.escape", "class": "", "method": "url_unescape", "focal_method_txt": "def url_unescape( # noqa: F811\n value: Union[str, bytes], encoding: Optional[str] = \"utf-8\", plus: bool = True\n) -> Union[str, bytes]:\n \"\"\"Decodes the given value from a URL.\n\n The argument may be either a byte or unicode string.\n\n If encoding is None, the result will be a byte string. Otherwise,\n the result is a unicode string in the specified encoding.\n\n If ``plus`` is true (the default), plus signs will be interpreted\n as spaces (literal plus signs must be represented as \"%2B\"). This\n is appropriate for query strings and form-encoded values but not\n for the path component of a URL. Note that this default is the\n reverse of Python's urllib module.\n\n .. versionadded:: 3.1\n The ``plus`` argument\n \"\"\"\n if encoding is None:\n if plus:\n # unquote_to_bytes doesn't have a _plus variant\n value = to_basestring(value).replace(\"+\", \" \")\n return urllib.parse.unquote_to_bytes(value)\n else:\n unquote = urllib.parse.unquote_plus if plus else urllib.parse.unquote\n return unquote(to_basestring(value), encoding=encoding)", "focal_method_lines": [117, 143], "in_stack": false, "globals": ["_XHTML_ESCAPE_RE", "_XHTML_ESCAPE_DICT", "_UTF8_TYPES", "_TO_UNICODE_TYPES", "_unicode", "native_str", "to_basestring", "_URL_RE", "_HTML_UNICODE_MAP"], "type_context": "import html.entities\nimport json\nimport re\nimport urllib.parse\nfrom tornado.util import unicode_type\nimport typing\nfrom typing import Union, Any, Optional, Dict, List, Callable\n\n_XHTML_ESCAPE_RE = re.compile(\"[&<>\\\"']\")\n_XHTML_ESCAPE_DICT = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n}\n_UTF8_TYPES = (bytes, type(None))\n_TO_UNICODE_TYPES = (unicode_type, type(None))\n_unicode = to_unicode\nnative_str = to_unicode\nto_basestring = to_unicode\n_URL_RE = re.compile(\n to_unicode(\n r\"\"\"\\b((?:([\\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\\s&()]|&|")*(?:[^!\"#$%&'()*+,.:;<=>?@\\[\\]^`{|}~\\s]))|(?:\\((?:[^\\s&()]|&|")*\\)))+)\"\"\" # noqa: E501\n )\n)\n_HTML_UNICODE_MAP = _build_unicode_map()\n\ndef url_unescape( # noqa: F811\n value: Union[str, bytes], encoding: Optional[str] = \"utf-8\", plus: bool = True\n) -> Union[str, bytes]:\n \"\"\"Decodes the given value from a URL.\n\n The argument may be either a byte or unicode string.\n\n If encoding is None, the result will be a byte string. Otherwise,\n the result is a unicode string in the specified encoding.\n\n If ``plus`` is true (the default), plus signs will be interpreted\n as spaces (literal plus signs must be represented as \"%2B\"). This\n is appropriate for query strings and form-encoded values but not\n for the path component of a URL. Note that this default is the\n reverse of Python's urllib module.\n\n .. versionadded:: 3.1\n The ``plus`` argument\n \"\"\"\n if encoding is None:\n if plus:\n # unquote_to_bytes doesn't have a _plus variant\n value = to_basestring(value).replace(\"+\", \" \")\n return urllib.parse.unquote_to_bytes(value)\n else:\n unquote = urllib.parse.unquote_plus if plus else urllib.parse.unquote\n return unquote(to_basestring(value), encoding=encoding)", "has_branch": true, "total_branches": 2} {"prompt_id": 662, "project": "tornado", "module": "tornado.escape", "class": "", "method": "utf8", "focal_method_txt": "def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811\n \"\"\"Converts a string argument to a byte string.\n\n If the argument is already a byte string or None, it is returned unchanged.\n Otherwise it must be a unicode string and is encoded as utf8.\n \"\"\"\n if isinstance(value, _UTF8_TYPES):\n return value\n if not isinstance(value, unicode_type):\n raise TypeError(\"Expected bytes, unicode, or None; got %r\" % type(value))\n return value.encode(\"utf-8\")", "focal_method_lines": [187, 197], "in_stack": false, "globals": ["_XHTML_ESCAPE_RE", "_XHTML_ESCAPE_DICT", "_UTF8_TYPES", "_TO_UNICODE_TYPES", "_unicode", "native_str", "to_basestring", "_URL_RE", "_HTML_UNICODE_MAP"], "type_context": "import html.entities\nimport json\nimport re\nimport urllib.parse\nfrom tornado.util import unicode_type\nimport typing\nfrom typing import Union, Any, Optional, Dict, List, Callable\n\n_XHTML_ESCAPE_RE = re.compile(\"[&<>\\\"']\")\n_XHTML_ESCAPE_DICT = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n}\n_UTF8_TYPES = (bytes, type(None))\n_TO_UNICODE_TYPES = (unicode_type, type(None))\n_unicode = to_unicode\nnative_str = to_unicode\nto_basestring = to_unicode\n_URL_RE = re.compile(\n to_unicode(\n r\"\"\"\\b((?:([\\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\\s&()]|&|")*(?:[^!\"#$%&'()*+,.:;<=>?@\\[\\]^`{|}~\\s]))|(?:\\((?:[^\\s&()]|&|")*\\)))+)\"\"\" # noqa: E501\n )\n)\n_HTML_UNICODE_MAP = _build_unicode_map()\n\ndef utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811\n \"\"\"Converts a string argument to a byte string.\n\n If the argument is already a byte string or None, it is returned unchanged.\n Otherwise it must be a unicode string and is encoded as utf8.\n \"\"\"\n if isinstance(value, _UTF8_TYPES):\n return value\n if not isinstance(value, unicode_type):\n raise TypeError(\"Expected bytes, unicode, or None; got %r\" % type(value))\n return value.encode(\"utf-8\")", "has_branch": true, "total_branches": 2} {"prompt_id": 663, "project": "tornado", "module": "tornado.escape", "class": "", "method": "recursive_unicode", "focal_method_txt": "def recursive_unicode(obj: Any) -> Any:\n \"\"\"Walks a simple data structure, converting byte strings to unicode.\n\n Supports lists, tuples, and dictionaries.\n \"\"\"\n if isinstance(obj, dict):\n return dict(\n (recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()\n )\n elif isinstance(obj, list):\n return list(recursive_unicode(i) for i in obj)\n elif isinstance(obj, tuple):\n return tuple(recursive_unicode(i) for i in obj)\n elif isinstance(obj, bytes):\n return to_unicode(obj)\n else:\n return obj", "focal_method_lines": [241, 257], "in_stack": false, "globals": ["_XHTML_ESCAPE_RE", "_XHTML_ESCAPE_DICT", "_UTF8_TYPES", "_TO_UNICODE_TYPES", "_unicode", "native_str", "to_basestring", "_URL_RE", "_HTML_UNICODE_MAP"], "type_context": "import html.entities\nimport json\nimport re\nimport urllib.parse\nfrom tornado.util import unicode_type\nimport typing\nfrom typing import Union, Any, Optional, Dict, List, Callable\n\n_XHTML_ESCAPE_RE = re.compile(\"[&<>\\\"']\")\n_XHTML_ESCAPE_DICT = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n}\n_UTF8_TYPES = (bytes, type(None))\n_TO_UNICODE_TYPES = (unicode_type, type(None))\n_unicode = to_unicode\nnative_str = to_unicode\nto_basestring = to_unicode\n_URL_RE = re.compile(\n to_unicode(\n r\"\"\"\\b((?:([\\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\\s&()]|&|")*(?:[^!\"#$%&'()*+,.:;<=>?@\\[\\]^`{|}~\\s]))|(?:\\((?:[^\\s&()]|&|")*\\)))+)\"\"\" # noqa: E501\n )\n)\n_HTML_UNICODE_MAP = _build_unicode_map()\n\ndef recursive_unicode(obj: Any) -> Any:\n \"\"\"Walks a simple data structure, converting byte strings to unicode.\n\n Supports lists, tuples, and dictionaries.\n \"\"\"\n if isinstance(obj, dict):\n return dict(\n (recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()\n )\n elif isinstance(obj, list):\n return list(recursive_unicode(i) for i in obj)\n elif isinstance(obj, tuple):\n return tuple(recursive_unicode(i) for i in obj)\n elif isinstance(obj, bytes):\n return to_unicode(obj)\n else:\n return obj", "has_branch": true, "total_branches": 2} {"prompt_id": 664, "project": "tornado", "module": "tornado.escape", "class": "", "method": "linkify", "focal_method_txt": "def linkify(\n text: Union[str, bytes],\n shorten: bool = False,\n extra_params: Union[str, Callable[[str], str]] = \"\",\n require_protocol: bool = False,\n permitted_protocols: List[str] = [\"http\", \"https\"],\n) -> str:\n \"\"\"Converts plain text into HTML with links.\n\n For example: ``linkify(\"Hello http://tornadoweb.org!\")`` would return\n ``Hello http://tornadoweb.org!``\n\n Parameters:\n\n * ``shorten``: Long urls will be shortened for display.\n\n * ``extra_params``: Extra text to include in the link tag, or a callable\n taking the link as an argument and returning the extra text\n e.g. ``linkify(text, extra_params='rel=\"nofollow\" class=\"external\"')``,\n or::\n\n def extra_params_cb(url):\n if url.startswith(\"http://example.com\"):\n return 'class=\"internal\"'\n else:\n return 'class=\"external\" rel=\"nofollow\"'\n linkify(text, extra_params=extra_params_cb)\n\n * ``require_protocol``: Only linkify urls which include a protocol. If\n this is False, urls such as www.facebook.com will also be linkified.\n\n * ``permitted_protocols``: List (or set) of protocols which should be\n linkified, e.g. ``linkify(text, permitted_protocols=[\"http\", \"ftp\",\n \"mailto\"])``. It is very unsafe to include protocols such as\n ``javascript``.\n \"\"\"\n if extra_params and not callable(extra_params):\n extra_params = \" \" + extra_params.strip()\n\n def make_link(m: typing.Match) -> str:\n url = m.group(1)\n proto = m.group(2)\n if require_protocol and not proto:\n return url # not protocol, no linkify\n\n if proto and proto not in permitted_protocols:\n return url # bad protocol, no linkify\n\n href = m.group(1)\n if not proto:\n href = \"http://\" + href # no proto specified, use http\n\n if callable(extra_params):\n params = \" \" + extra_params(href).strip()\n else:\n params = extra_params\n\n # clip long urls. max_len is just an approximation\n max_len = 30\n if shorten and len(url) > max_len:\n before_clip = url\n if proto:\n proto_len = len(proto) + 1 + len(m.group(3) or \"\") # +1 for :\n else:\n proto_len = 0\n\n parts = url[proto_len:].split(\"/\")\n if len(parts) > 1:\n # Grab the whole host part plus the first bit of the path\n # The path is usually not that interesting once shortened\n # (no more slug, etc), so it really just provides a little\n # extra indication of shortening.\n url = (\n url[:proto_len]\n + parts[0]\n + \"/\"\n + parts[1][:8].split(\"?\")[0].split(\".\")[0]\n )\n\n if len(url) > max_len * 1.5: # still too long\n url = url[:max_len]\n\n if url != before_clip:\n amp = url.rfind(\"&\")\n # avoid splitting html char entities\n if amp > max_len - 5:\n url = url[:amp]\n url += \"...\"\n\n if len(url) >= len(before_clip):\n url = before_clip\n else:\n # full url is visible on mouse-over (for those who don't\n # have a status bar, such as Safari by default)\n params += ' title=\"%s\"' % href\n\n return u'%s' % (href, params, url)\n\n # First HTML-escape so that our strings are all safe.\n # The regex is modified to avoid character entites other than & so\n # that we won't pick up ", etc.\n text = _unicode(xhtml_escape(text))\n return _URL_RE.sub(make_link, text)", "focal_method_lines": [274, 376], "in_stack": false, "globals": ["_XHTML_ESCAPE_RE", "_XHTML_ESCAPE_DICT", "_UTF8_TYPES", "_TO_UNICODE_TYPES", "_unicode", "native_str", "to_basestring", "_URL_RE", "_HTML_UNICODE_MAP"], "type_context": "import html.entities\nimport json\nimport re\nimport urllib.parse\nfrom tornado.util import unicode_type\nimport typing\nfrom typing import Union, Any, Optional, Dict, List, Callable\n\n_XHTML_ESCAPE_RE = re.compile(\"[&<>\\\"']\")\n_XHTML_ESCAPE_DICT = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n}\n_UTF8_TYPES = (bytes, type(None))\n_TO_UNICODE_TYPES = (unicode_type, type(None))\n_unicode = to_unicode\nnative_str = to_unicode\nto_basestring = to_unicode\n_URL_RE = re.compile(\n to_unicode(\n r\"\"\"\\b((?:([\\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\\s&()]|&|")*(?:[^!\"#$%&'()*+,.:;<=>?@\\[\\]^`{|}~\\s]))|(?:\\((?:[^\\s&()]|&|")*\\)))+)\"\"\" # noqa: E501\n )\n)\n_HTML_UNICODE_MAP = _build_unicode_map()\n\ndef linkify(\n text: Union[str, bytes],\n shorten: bool = False,\n extra_params: Union[str, Callable[[str], str]] = \"\",\n require_protocol: bool = False,\n permitted_protocols: List[str] = [\"http\", \"https\"],\n) -> str:\n \"\"\"Converts plain text into HTML with links.\n\n For example: ``linkify(\"Hello http://tornadoweb.org!\")`` would return\n ``Hello http://tornadoweb.org!``\n\n Parameters:\n\n * ``shorten``: Long urls will be shortened for display.\n\n * ``extra_params``: Extra text to include in the link tag, or a callable\n taking the link as an argument and returning the extra text\n e.g. ``linkify(text, extra_params='rel=\"nofollow\" class=\"external\"')``,\n or::\n\n def extra_params_cb(url):\n if url.startswith(\"http://example.com\"):\n return 'class=\"internal\"'\n else:\n return 'class=\"external\" rel=\"nofollow\"'\n linkify(text, extra_params=extra_params_cb)\n\n * ``require_protocol``: Only linkify urls which include a protocol. If\n this is False, urls such as www.facebook.com will also be linkified.\n\n * ``permitted_protocols``: List (or set) of protocols which should be\n linkified, e.g. ``linkify(text, permitted_protocols=[\"http\", \"ftp\",\n \"mailto\"])``. It is very unsafe to include protocols such as\n ``javascript``.\n \"\"\"\n if extra_params and not callable(extra_params):\n extra_params = \" \" + extra_params.strip()\n\n def make_link(m: typing.Match) -> str:\n url = m.group(1)\n proto = m.group(2)\n if require_protocol and not proto:\n return url # not protocol, no linkify\n\n if proto and proto not in permitted_protocols:\n return url # bad protocol, no linkify\n\n href = m.group(1)\n if not proto:\n href = \"http://\" + href # no proto specified, use http\n\n if callable(extra_params):\n params = \" \" + extra_params(href).strip()\n else:\n params = extra_params\n\n # clip long urls. max_len is just an approximation\n max_len = 30\n if shorten and len(url) > max_len:\n before_clip = url\n if proto:\n proto_len = len(proto) + 1 + len(m.group(3) or \"\") # +1 for :\n else:\n proto_len = 0\n\n parts = url[proto_len:].split(\"/\")\n if len(parts) > 1:\n # Grab the whole host part plus the first bit of the path\n # The path is usually not that interesting once shortened\n # (no more slug, etc), so it really just provides a little\n # extra indication of shortening.\n url = (\n url[:proto_len]\n + parts[0]\n + \"/\"\n + parts[1][:8].split(\"?\")[0].split(\".\")[0]\n )\n\n if len(url) > max_len * 1.5: # still too long\n url = url[:max_len]\n\n if url != before_clip:\n amp = url.rfind(\"&\")\n # avoid splitting html char entities\n if amp > max_len - 5:\n url = url[:amp]\n url += \"...\"\n\n if len(url) >= len(before_clip):\n url = before_clip\n else:\n # full url is visible on mouse-over (for those who don't\n # have a status bar, such as Safari by default)\n params += ' title=\"%s\"' % href\n\n return u'%s' % (href, params, url)\n\n # First HTML-escape so that our strings are all safe.\n # The regex is modified to avoid character entites other than & so\n # that we won't pick up ", etc.\n text = _unicode(xhtml_escape(text))\n return _URL_RE.sub(make_link, text)", "has_branch": true, "total_branches": 2} {"prompt_id": 665, "project": "tornado", "module": "tornado.httpclient", "class": "", "method": "main", "focal_method_txt": "def main() -> None:\n from tornado.options import define, options, parse_command_line\n\n define(\"print_headers\", type=bool, default=False)\n define(\"print_body\", type=bool, default=True)\n define(\"follow_redirects\", type=bool, default=True)\n define(\"validate_cert\", type=bool, default=True)\n define(\"proxy_host\", type=str)\n define(\"proxy_port\", type=int)\n args = parse_command_line()\n client = HTTPClient()\n for arg in args:\n try:\n response = client.fetch(\n arg,\n follow_redirects=options.follow_redirects,\n validate_cert=options.validate_cert,\n proxy_host=options.proxy_host,\n proxy_port=options.proxy_port,\n )\n except HTTPError as e:\n if e.response is not None:\n response = e.response\n else:\n raise\n if options.print_headers:\n print(response.headers)\n if options.print_body:\n print(native_str(response.body))\n client.close()", "focal_method_lines": [756, 785], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False\n\ndef main() -> None:\n from tornado.options import define, options, parse_command_line\n\n define(\"print_headers\", type=bool, default=False)\n define(\"print_body\", type=bool, default=True)\n define(\"follow_redirects\", type=bool, default=True)\n define(\"validate_cert\", type=bool, default=True)\n define(\"proxy_host\", type=str)\n define(\"proxy_port\", type=int)\n args = parse_command_line()\n client = HTTPClient()\n for arg in args:\n try:\n response = client.fetch(\n arg,\n follow_redirects=options.follow_redirects,\n validate_cert=options.validate_cert,\n proxy_host=options.proxy_host,\n proxy_port=options.proxy_port,\n )\n except HTTPError as e:\n if e.response is not None:\n response = e.response\n else:\n raise\n if options.print_headers:\n print(response.headers)\n if options.print_body:\n print(native_str(response.body))\n client.close()", "has_branch": true, "total_branches": 2} {"prompt_id": 666, "project": "tornado", "module": "tornado.httpclient", "class": "HTTPClient", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False", "focal_method_lines": [88, 109], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False", "has_branch": true, "total_branches": 2} {"prompt_id": 667, "project": "tornado", "module": "tornado.httpclient", "class": "HTTPClient", "method": "fetch", "focal_method_txt": " def fetch(\n self, request: Union[\"HTTPRequest\", str], **kwargs: Any\n ) -> \"HTTPResponse\":\n \"\"\"Executes a request, returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n If an error occurs during the fetch, we raise an `HTTPError` unless\n the ``raise_error`` keyword argument is set to False.\n \"\"\"\n response = self._io_loop.run_sync(\n functools.partial(self._async_client.fetch, request, **kwargs)\n )\n return response", "focal_method_lines": [121, 136], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False\n\n def fetch(\n self, request: Union[\"HTTPRequest\", str], **kwargs: Any\n ) -> \"HTTPResponse\":\n \"\"\"Executes a request, returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n If an error occurs during the fetch, we raise an `HTTPError` unless\n the ``raise_error`` keyword argument is set to False.\n \"\"\"\n response = self._io_loop.run_sync(\n functools.partial(self._async_client.fetch, request, **kwargs)\n )\n return response", "has_branch": false, "total_branches": 0} {"prompt_id": 668, "project": "tornado", "module": "tornado.httpclient", "class": "AsyncHTTPClient", "method": "__new__", "focal_method_txt": " def __new__(cls, force_instance: bool = False, **kwargs: Any) -> \"AsyncHTTPClient\":\n io_loop = IOLoop.current()\n if force_instance:\n instance_cache = None\n else:\n instance_cache = cls._async_clients()\n if instance_cache is not None and io_loop in instance_cache:\n return instance_cache[io_loop]\n instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs) # type: ignore\n # Make sure the instance knows which cache to remove itself from.\n # It can't simply call _async_clients() because we may be in\n # __new__(AsyncHTTPClient) but instance.__class__ may be\n # SimpleAsyncHTTPClient.\n instance._instance_cache = instance_cache\n if instance_cache is not None:\n instance_cache[instance.io_loop] = instance\n return instance", "focal_method_lines": [197, 213], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False\n\nclass AsyncHTTPClient(Configurable):\n\n _instance_cache = None\n\n def __new__(cls, force_instance: bool = False, **kwargs: Any) -> \"AsyncHTTPClient\":\n io_loop = IOLoop.current()\n if force_instance:\n instance_cache = None\n else:\n instance_cache = cls._async_clients()\n if instance_cache is not None and io_loop in instance_cache:\n return instance_cache[io_loop]\n instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs) # type: ignore\n # Make sure the instance knows which cache to remove itself from.\n # It can't simply call _async_clients() because we may be in\n # __new__(AsyncHTTPClient) but instance.__class__ may be\n # SimpleAsyncHTTPClient.\n instance._instance_cache = instance_cache\n if instance_cache is not None:\n instance_cache[instance.io_loop] = instance\n return instance", "has_branch": true, "total_branches": 2} {"prompt_id": 669, "project": "tornado", "module": "tornado.httpclient", "class": "AsyncHTTPClient", "method": "initialize", "focal_method_txt": " def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None:\n self.io_loop = IOLoop.current()\n self.defaults = dict(HTTPRequest._DEFAULTS)\n if defaults is not None:\n self.defaults.update(defaults)\n self._closed = False", "focal_method_lines": [215, 220], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()\n\nclass AsyncHTTPClient(Configurable):\n\n _instance_cache = None\n\n def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None:\n self.io_loop = IOLoop.current()\n self.defaults = dict(HTTPRequest._DEFAULTS)\n if defaults is not None:\n self.defaults.update(defaults)\n self._closed = False", "has_branch": true, "total_branches": 2} {"prompt_id": 670, "project": "tornado", "module": "tornado.httpclient", "class": "AsyncHTTPClient", "method": "close", "focal_method_txt": " def close(self) -> None:\n \"\"\"Destroys this HTTP client, freeing any file descriptors used.\n\n This method is **not needed in normal use** due to the way\n that `AsyncHTTPClient` objects are transparently reused.\n ``close()`` is generally only necessary when either the\n `.IOLoop` is also being closed, or the ``force_instance=True``\n argument was used when creating the `AsyncHTTPClient`.\n\n No other methods may be called on the `AsyncHTTPClient` after\n ``close()``.\n\n \"\"\"\n if self._closed:\n return\n self._closed = True\n if self._instance_cache is not None:\n cached_val = self._instance_cache.pop(self.io_loop, None)\n # If there's an object other than self in the instance\n # cache for our IOLoop, something has gotten mixed up. A\n # value of None appears to be possible when this is called\n # from a destructor (HTTPClient.__del__) as the weakref\n # gets cleared before the destructor runs.\n if cached_val is not None and cached_val is not self:\n raise RuntimeError(\"inconsistent AsyncHTTPClient cache\")", "focal_method_lines": [222, 246], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False\n\nclass AsyncHTTPClient(Configurable):\n\n _instance_cache = None\n\n def close(self) -> None:\n \"\"\"Destroys this HTTP client, freeing any file descriptors used.\n\n This method is **not needed in normal use** due to the way\n that `AsyncHTTPClient` objects are transparently reused.\n ``close()`` is generally only necessary when either the\n `.IOLoop` is also being closed, or the ``force_instance=True``\n argument was used when creating the `AsyncHTTPClient`.\n\n No other methods may be called on the `AsyncHTTPClient` after\n ``close()``.\n\n \"\"\"\n if self._closed:\n return\n self._closed = True\n if self._instance_cache is not None:\n cached_val = self._instance_cache.pop(self.io_loop, None)\n # If there's an object other than self in the instance\n # cache for our IOLoop, something has gotten mixed up. A\n # value of None appears to be possible when this is called\n # from a destructor (HTTPClient.__del__) as the weakref\n # gets cleared before the destructor runs.\n if cached_val is not None and cached_val is not self:\n raise RuntimeError(\"inconsistent AsyncHTTPClient cache\")", "has_branch": true, "total_branches": 2} {"prompt_id": 671, "project": "tornado", "module": "tornado.httpclient", "class": "AsyncHTTPClient", "method": "fetch", "focal_method_txt": " def fetch(\n self,\n request: Union[str, \"HTTPRequest\"],\n raise_error: bool = True,\n **kwargs: Any\n ) -> \"Future[HTTPResponse]\":\n \"\"\"Executes a request, asynchronously returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n This method returns a `.Future` whose result is an\n `HTTPResponse`. By default, the ``Future`` will raise an\n `HTTPError` if the request returned a non-200 response code\n (other errors may also be raised if the server could not be\n contacted). Instead, if ``raise_error`` is set to False, the\n response will always be returned regardless of the response\n code.\n\n If a ``callback`` is given, it will be invoked with the `HTTPResponse`.\n In the callback interface, `HTTPError` is not automatically raised.\n Instead, you must check the response's ``error`` attribute or\n call its `~HTTPResponse.rethrow` method.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n `.Future` instead.\n\n The ``raise_error=False`` argument only affects the\n `HTTPError` raised when a non-200 response code is used,\n instead of suppressing all errors.\n \"\"\"\n if self._closed:\n raise RuntimeError(\"fetch() called on closed AsyncHTTPClient\")\n if not isinstance(request, HTTPRequest):\n request = HTTPRequest(url=request, **kwargs)\n else:\n if kwargs:\n raise ValueError(\n \"kwargs can't be used if request is an HTTPRequest object\"\n )\n # We may modify this (to add Host, Accept-Encoding, etc),\n # so make sure we don't modify the caller's object. This is also\n # where normal dicts get converted to HTTPHeaders objects.\n request.headers = httputil.HTTPHeaders(request.headers)\n request_proxy = _RequestProxy(request, self.defaults)\n future = Future() # type: Future[HTTPResponse]\n\n def handle_response(response: \"HTTPResponse\") -> None:\n if response.error:\n if raise_error or not response._error_is_response_code:\n future_set_exception_unless_cancelled(future, response.error)\n return\n future_set_result_unless_cancelled(future, response)\n\n self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response)\n return future", "focal_method_lines": [248, 306], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPClient(object):\n\n def __init__(\n self,\n async_client_class: \"Optional[Type[AsyncHTTPClient]]\" = None,\n **kwargs: Any\n ) -> None:\n # Initialize self._closed at the beginning of the constructor\n # so that an exception raised here doesn't lead to confusing\n # failures in __del__.\n self._closed = True\n self._io_loop = IOLoop(make_current=False)\n if async_client_class is None:\n async_client_class = AsyncHTTPClient\n\n # Create the client while our IOLoop is \"current\", without\n # clobbering the thread's real current IOLoop (if any).\n async def make_client() -> \"AsyncHTTPClient\":\n await gen.sleep(0)\n assert async_client_class is not None\n return async_client_class(**kwargs)\n\n self._async_client = self._io_loop.run_sync(make_client)\n self._closed = False\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}\n\nclass _RequestProxy(object):\n\n def __init__(\n self, request: HTTPRequest, defaults: Optional[Dict[str, Any]]\n ) -> None:\n self.request = request\n self.defaults = defaults\n\nclass AsyncHTTPClient(Configurable):\n\n _instance_cache = None\n\n def fetch(\n self,\n request: Union[str, \"HTTPRequest\"],\n raise_error: bool = True,\n **kwargs: Any\n ) -> \"Future[HTTPResponse]\":\n \"\"\"Executes a request, asynchronously returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n This method returns a `.Future` whose result is an\n `HTTPResponse`. By default, the ``Future`` will raise an\n `HTTPError` if the request returned a non-200 response code\n (other errors may also be raised if the server could not be\n contacted). Instead, if ``raise_error`` is set to False, the\n response will always be returned regardless of the response\n code.\n\n If a ``callback`` is given, it will be invoked with the `HTTPResponse`.\n In the callback interface, `HTTPError` is not automatically raised.\n Instead, you must check the response's ``error`` attribute or\n call its `~HTTPResponse.rethrow` method.\n\n .. versionchanged:: 6.0\n\n The ``callback`` argument was removed. Use the returned\n `.Future` instead.\n\n The ``raise_error=False`` argument only affects the\n `HTTPError` raised when a non-200 response code is used,\n instead of suppressing all errors.\n \"\"\"\n if self._closed:\n raise RuntimeError(\"fetch() called on closed AsyncHTTPClient\")\n if not isinstance(request, HTTPRequest):\n request = HTTPRequest(url=request, **kwargs)\n else:\n if kwargs:\n raise ValueError(\n \"kwargs can't be used if request is an HTTPRequest object\"\n )\n # We may modify this (to add Host, Accept-Encoding, etc),\n # so make sure we don't modify the caller's object. This is also\n # where normal dicts get converted to HTTPHeaders objects.\n request.headers = httputil.HTTPHeaders(request.headers)\n request_proxy = _RequestProxy(request, self.defaults)\n future = Future() # type: Future[HTTPResponse]\n\n def handle_response(response: \"HTTPResponse\") -> None:\n if response.error:\n if raise_error or not response._error_is_response_code:\n future_set_exception_unless_cancelled(future, response.error)\n return\n future_set_result_unless_cancelled(future, response)\n\n self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response)\n return future", "has_branch": true, "total_branches": 2} {"prompt_id": 672, "project": "tornado", "module": "tornado.httpclient", "class": "AsyncHTTPClient", "method": "fetch_impl", "focal_method_txt": " def fetch_impl(\n self, request: \"HTTPRequest\", callback: Callable[[\"HTTPResponse\"], None]\n ) -> None:\n raise NotImplementedError()", "focal_method_lines": [308, 311], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}\n\nclass AsyncHTTPClient(Configurable):\n\n _instance_cache = None\n\n def fetch_impl(\n self, request: \"HTTPRequest\", callback: Callable[[\"HTTPResponse\"], None]\n ) -> None:\n raise NotImplementedError()", "has_branch": false, "total_branches": 0} {"prompt_id": 673, "project": "tornado", "module": "tornado.httpclient", "class": "HTTPRequest", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()", "focal_method_lines": [357, 548], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()", "has_branch": true, "total_branches": 2} {"prompt_id": 674, "project": "tornado", "module": "tornado.httpclient", "class": "HTTPResponse", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}", "focal_method_lines": [628, 668], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPRequest(object):\n\n _headers = None\n\n _DEFAULTS = dict(\n connect_timeout=20.0,\n request_timeout=20.0,\n follow_redirects=True,\n max_redirects=5,\n decompress_response=True,\n proxy_password=\"\",\n allow_nonstandard_methods=False,\n validate_cert=True,\n )\n\n def __init__(\n self,\n url: str,\n method: str = \"GET\",\n headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,\n body: Optional[Union[bytes, str]] = None,\n auth_username: Optional[str] = None,\n auth_password: Optional[str] = None,\n auth_mode: Optional[str] = None,\n connect_timeout: Optional[float] = None,\n request_timeout: Optional[float] = None,\n if_modified_since: Optional[Union[float, datetime.datetime]] = None,\n follow_redirects: Optional[bool] = None,\n max_redirects: Optional[int] = None,\n user_agent: Optional[str] = None,\n use_gzip: Optional[bool] = None,\n network_interface: Optional[str] = None,\n streaming_callback: Optional[Callable[[bytes], None]] = None,\n header_callback: Optional[Callable[[str], None]] = None,\n prepare_curl_callback: Optional[Callable[[Any], None]] = None,\n proxy_host: Optional[str] = None,\n proxy_port: Optional[int] = None,\n proxy_username: Optional[str] = None,\n proxy_password: Optional[str] = None,\n proxy_auth_mode: Optional[str] = None,\n allow_nonstandard_methods: Optional[bool] = None,\n validate_cert: Optional[bool] = None,\n ca_certs: Optional[str] = None,\n allow_ipv6: Optional[bool] = None,\n client_key: Optional[str] = None,\n client_cert: Optional[str] = None,\n body_producer: Optional[\n Callable[[Callable[[bytes], None]], \"Future[None]\"]\n ] = None,\n expect_100_continue: bool = False,\n decompress_response: Optional[bool] = None,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n ) -> None:\n r\"\"\"All parameters except ``url`` are optional.\n\n :arg str url: URL to fetch\n :arg str method: HTTP method, e.g. \"GET\" or \"POST\"\n :arg headers: Additional HTTP headers to pass on the request\n :type headers: `~tornado.httputil.HTTPHeaders` or `dict`\n :arg body: HTTP request body as a string (byte or unicode; if unicode\n the utf-8 encoding will be used)\n :type body: `str` or `bytes`\n :arg collections.abc.Callable body_producer: Callable used for\n lazy/asynchronous request bodies.\n It is called with one argument, a ``write`` function, and should\n return a `.Future`. It should call the write function with new\n data as it becomes available. The write function returns a\n `.Future` which can be used for flow control.\n Only one of ``body`` and ``body_producer`` may\n be specified. ``body_producer`` is not supported on\n ``curl_httpclient``. When using ``body_producer`` it is recommended\n to pass a ``Content-Length`` in the headers as otherwise chunked\n encoding will be used, and many servers do not support chunked\n encoding on requests. New in Tornado 4.0\n :arg str auth_username: Username for HTTP authentication\n :arg str auth_password: Password for HTTP authentication\n :arg str auth_mode: Authentication mode; default is \"basic\".\n Allowed values are implementation-defined; ``curl_httpclient``\n supports \"basic\" and \"digest\"; ``simple_httpclient`` only supports\n \"basic\"\n :arg float connect_timeout: Timeout for initial connection in seconds,\n default 20 seconds (0 means no timeout)\n :arg float request_timeout: Timeout for entire request in seconds,\n default 20 seconds (0 means no timeout)\n :arg if_modified_since: Timestamp for ``If-Modified-Since`` header\n :type if_modified_since: `datetime` or `float`\n :arg bool follow_redirects: Should redirects be followed automatically\n or return the 3xx response? Default True.\n :arg int max_redirects: Limit for ``follow_redirects``, default 5.\n :arg str user_agent: String to send as ``User-Agent`` header\n :arg bool decompress_response: Request a compressed response from\n the server and decompress it after downloading. Default is True.\n New in Tornado 4.0.\n :arg bool use_gzip: Deprecated alias for ``decompress_response``\n since Tornado 4.0.\n :arg str network_interface: Network interface or source IP to use for request.\n See ``curl_httpclient`` note below.\n :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will\n be run with each chunk of data as it is received, and\n ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in\n the final response.\n :arg collections.abc.Callable header_callback: If set, ``header_callback`` will\n be run with each header line as it is received (including the\n first line, e.g. ``HTTP/1.0 200 OK\\r\\n``, and a final line\n containing only ``\\r\\n``. All lines include the trailing newline\n characters). ``HTTPResponse.headers`` will be empty in the final\n response. This is most useful in conjunction with\n ``streaming_callback``, because it's the only way to get access to\n header data while the request is in progress.\n :arg collections.abc.Callable prepare_curl_callback: If set, will be called with\n a ``pycurl.Curl`` object to allow the application to make additional\n ``setopt`` calls.\n :arg str proxy_host: HTTP proxy hostname. To use proxies,\n ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``,\n ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are\n currently only supported with ``curl_httpclient``.\n :arg int proxy_port: HTTP proxy port\n :arg str proxy_username: HTTP proxy username\n :arg str proxy_password: HTTP proxy password\n :arg str proxy_auth_mode: HTTP proxy Authentication mode;\n default is \"basic\". supports \"basic\" and \"digest\"\n :arg bool allow_nonstandard_methods: Allow unknown values for ``method``\n argument? Default is False.\n :arg bool validate_cert: For HTTPS requests, validate the server's\n certificate? Default is True.\n :arg str ca_certs: filename of CA certificates in PEM format,\n or None to use defaults. See note below when used with\n ``curl_httpclient``.\n :arg str client_key: Filename for client SSL key, if any. See\n note below when used with ``curl_httpclient``.\n :arg str client_cert: Filename for client SSL certificate, if any.\n See note below when used with ``curl_httpclient``.\n :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in\n ``simple_httpclient`` (unsupported by ``curl_httpclient``).\n Overrides ``validate_cert``, ``ca_certs``, ``client_key``,\n and ``client_cert``.\n :arg bool allow_ipv6: Use IPv6 when available? Default is True.\n :arg bool expect_100_continue: If true, send the\n ``Expect: 100-continue`` header and wait for a continue response\n before sending the request body. Only supported with\n ``simple_httpclient``.\n\n .. note::\n\n When using ``curl_httpclient`` certain options may be\n inherited by subsequent fetches because ``pycurl`` does\n not allow them to be cleanly reset. This applies to the\n ``ca_certs``, ``client_key``, ``client_cert``, and\n ``network_interface`` arguments. If you use these\n options, you should pass them on every request (you don't\n have to always use the same values, but it's not possible\n to mix requests that specify these options with ones that\n use the defaults).\n\n .. versionadded:: 3.1\n The ``auth_mode`` argument.\n\n .. versionadded:: 4.0\n The ``body_producer`` and ``expect_100_continue`` arguments.\n\n .. versionadded:: 4.2\n The ``ssl_options`` argument.\n\n .. versionadded:: 4.5\n The ``proxy_auth_mode`` argument.\n \"\"\"\n # Note that some of these attributes go through property setters\n # defined below.\n self.headers = headers # type: ignore\n if if_modified_since:\n self.headers[\"If-Modified-Since\"] = httputil.format_timestamp(\n if_modified_since\n )\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n self.proxy_username = proxy_username\n self.proxy_password = proxy_password\n self.proxy_auth_mode = proxy_auth_mode\n self.url = url\n self.method = method\n self.body = body # type: ignore\n self.body_producer = body_producer\n self.auth_username = auth_username\n self.auth_password = auth_password\n self.auth_mode = auth_mode\n self.connect_timeout = connect_timeout\n self.request_timeout = request_timeout\n self.follow_redirects = follow_redirects\n self.max_redirects = max_redirects\n self.user_agent = user_agent\n if decompress_response is not None:\n self.decompress_response = decompress_response # type: Optional[bool]\n else:\n self.decompress_response = use_gzip\n self.network_interface = network_interface\n self.streaming_callback = streaming_callback\n self.header_callback = header_callback\n self.prepare_curl_callback = prepare_curl_callback\n self.allow_nonstandard_methods = allow_nonstandard_methods\n self.validate_cert = validate_cert\n self.ca_certs = ca_certs\n self.allow_ipv6 = allow_ipv6\n self.client_key = client_key\n self.client_cert = client_cert\n self.ssl_options = ssl_options\n self.expect_100_continue = expect_100_continue\n self.start_time = time.time()\n\nclass _RequestProxy(object):\n\n def __init__(\n self, request: HTTPRequest, defaults: Optional[Dict[str, Any]]\n ) -> None:\n self.request = request\n self.defaults = defaults\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}", "has_branch": true, "total_branches": 2} {"prompt_id": 675, "project": "tornado", "module": "tornado.httpclient", "class": "HTTPResponse", "method": "rethrow", "focal_method_txt": " def rethrow(self) -> None:\n \"\"\"If there was an error on the request, raise an `HTTPError`.\"\"\"\n if self.error:\n raise self.error", "focal_method_lines": [679, 682], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass HTTPResponse(object):\n\n error = None\n\n _error_is_response_code = False\n\n request = None\n\n def __init__(\n self,\n request: HTTPRequest,\n code: int,\n headers: Optional[httputil.HTTPHeaders] = None,\n buffer: Optional[BytesIO] = None,\n effective_url: Optional[str] = None,\n error: Optional[BaseException] = None,\n request_time: Optional[float] = None,\n time_info: Optional[Dict[str, float]] = None,\n reason: Optional[str] = None,\n start_time: Optional[float] = None,\n ) -> None:\n if isinstance(request, _RequestProxy):\n self.request = request.request\n else:\n self.request = request\n self.code = code\n self.reason = reason or httputil.responses.get(code, \"Unknown\")\n if headers is not None:\n self.headers = headers\n else:\n self.headers = httputil.HTTPHeaders()\n self.buffer = buffer\n self._body = None # type: Optional[bytes]\n if effective_url is None:\n self.effective_url = request.url\n else:\n self.effective_url = effective_url\n self._error_is_response_code = False\n if error is None:\n if self.code < 200 or self.code >= 300:\n self._error_is_response_code = True\n self.error = HTTPError(self.code, message=self.reason, response=self)\n else:\n self.error = None\n else:\n self.error = error\n self.start_time = start_time\n self.request_time = request_time\n self.time_info = time_info or {}\n\n def rethrow(self) -> None:\n \"\"\"If there was an error on the request, raise an `HTTPError`.\"\"\"\n if self.error:\n raise self.error", "has_branch": true, "total_branches": 2} {"prompt_id": 676, "project": "tornado", "module": "tornado.httpclient", "class": "_RequestProxy", "method": "__getattr__", "focal_method_txt": " def __getattr__(self, name: str) -> Any:\n request_attr = getattr(self.request, name)\n if request_attr is not None:\n return request_attr\n elif self.defaults is not None:\n return self.defaults.get(name, None)\n else:\n return None", "focal_method_lines": [746, 753], "in_stack": false, "globals": ["HTTPError"], "type_context": "import datetime\nimport functools\nfrom io import BytesIO\nimport ssl\nimport time\nimport weakref\nfrom tornado.concurrent import (\n Future,\n future_set_result_unless_cancelled,\n future_set_exception_unless_cancelled,\n)\nfrom tornado.escape import utf8, native_str\nfrom tornado import gen, httputil\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable\nfrom typing import Type, Any, Union, Dict, Callable, Optional, cast\n\nHTTPError = HTTPClientError\n\nclass _RequestProxy(object):\n\n def __init__(\n self, request: HTTPRequest, defaults: Optional[Dict[str, Any]]\n ) -> None:\n self.request = request\n self.defaults = defaults\n\n def __getattr__(self, name: str) -> Any:\n request_attr = getattr(self.request, name)\n if request_attr is not None:\n return request_attr\n elif self.defaults is not None:\n return self.defaults.get(name, None)\n else:\n return None", "has_branch": true, "total_branches": 2} {"prompt_id": 677, "project": "tornado", "module": "tornado.locale", "class": "", "method": "load_translations", "focal_method_txt": "def load_translations(directory: str, encoding: Optional[str] = None) -> None:\n \"\"\"Loads translations from CSV files in a directory.\n\n Translations are strings with optional Python-style named placeholders\n (e.g., ``My name is %(name)s``) and their associated translations.\n\n The directory should have translation files of the form ``LOCALE.csv``,\n e.g. ``es_GT.csv``. The CSV files should have two or three columns: string,\n translation, and an optional plural indicator. Plural indicators should\n be one of \"plural\" or \"singular\". A given string can have both singular\n and plural forms. For example ``%(name)s liked this`` may have a\n different verb conjugation depending on whether %(name)s is one\n name or a list of names. There should be two rows in the CSV file for\n that string, one with plural indicator \"singular\", and one \"plural\".\n For strings with no verbs that would change on translation, simply\n use \"unknown\" or the empty string (or don't include the column at all).\n\n The file is read using the `csv` module in the default \"excel\" dialect.\n In this format there should not be spaces after the commas.\n\n If no ``encoding`` parameter is given, the encoding will be\n detected automatically (among UTF-8 and UTF-16) if the file\n contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM\n is present.\n\n Example translation ``es_LA.csv``::\n\n \"I love you\",\"Te amo\"\n \"%(name)s liked this\",\"A %(name)s les gustó esto\",\"plural\"\n \"%(name)s liked this\",\"A %(name)s le gustó esto\",\"singular\"\n\n .. versionchanged:: 4.3\n Added ``encoding`` parameter. Added support for BOM-based encoding\n detection, UTF-16, and UTF-8-with-BOM.\n \"\"\"\n global _translations\n global _supported_locales\n _translations = {}\n for path in os.listdir(directory):\n if not path.endswith(\".csv\"):\n continue\n locale, extension = path.split(\".\")\n if not re.match(\"[a-z]+(_[A-Z]+)?$\", locale):\n gen_log.error(\n \"Unrecognized locale %r (path: %s)\",\n locale,\n os.path.join(directory, path),\n )\n continue\n full_path = os.path.join(directory, path)\n if encoding is None:\n # Try to autodetect encoding based on the BOM.\n with open(full_path, \"rb\") as bf:\n data = bf.read(len(codecs.BOM_UTF16_LE))\n if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n encoding = \"utf-16\"\n else:\n # utf-8-sig is \"utf-8 with optional BOM\". It's discouraged\n # in most cases but is common with CSV files because Excel\n # cannot read utf-8 files without a BOM.\n encoding = \"utf-8-sig\"\n # python 3: csv.reader requires a file open in text mode.\n # Specify an encoding to avoid dependence on $LANG environment variable.\n with open(full_path, encoding=encoding) as f:\n _translations[locale] = {}\n for i, row in enumerate(csv.reader(f)):\n if not row or len(row) < 2:\n continue\n row = [escape.to_unicode(c).strip() for c in row]\n english, translation = row[:2]\n if len(row) > 2:\n plural = row[2] or \"unknown\"\n else:\n plural = \"unknown\"\n if plural not in (\"plural\", \"singular\", \"unknown\"):\n gen_log.error(\n \"Unrecognized plural indicator %r in %s line %d\",\n plural,\n path,\n i + 1,\n )\n continue\n _translations[locale].setdefault(plural, {})[english] = translation\n _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])\n gen_log.debug(\"Supported locales: %s\", sorted(_supported_locales))", "focal_method_lines": [88, 172], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\ndef load_translations(directory: str, encoding: Optional[str] = None) -> None:\n \"\"\"Loads translations from CSV files in a directory.\n\n Translations are strings with optional Python-style named placeholders\n (e.g., ``My name is %(name)s``) and their associated translations.\n\n The directory should have translation files of the form ``LOCALE.csv``,\n e.g. ``es_GT.csv``. The CSV files should have two or three columns: string,\n translation, and an optional plural indicator. Plural indicators should\n be one of \"plural\" or \"singular\". A given string can have both singular\n and plural forms. For example ``%(name)s liked this`` may have a\n different verb conjugation depending on whether %(name)s is one\n name or a list of names. There should be two rows in the CSV file for\n that string, one with plural indicator \"singular\", and one \"plural\".\n For strings with no verbs that would change on translation, simply\n use \"unknown\" or the empty string (or don't include the column at all).\n\n The file is read using the `csv` module in the default \"excel\" dialect.\n In this format there should not be spaces after the commas.\n\n If no ``encoding`` parameter is given, the encoding will be\n detected automatically (among UTF-8 and UTF-16) if the file\n contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM\n is present.\n\n Example translation ``es_LA.csv``::\n\n \"I love you\",\"Te amo\"\n \"%(name)s liked this\",\"A %(name)s les gustó esto\",\"plural\"\n \"%(name)s liked this\",\"A %(name)s le gustó esto\",\"singular\"\n\n .. versionchanged:: 4.3\n Added ``encoding`` parameter. Added support for BOM-based encoding\n detection, UTF-16, and UTF-8-with-BOM.\n \"\"\"\n global _translations\n global _supported_locales\n _translations = {}\n for path in os.listdir(directory):\n if not path.endswith(\".csv\"):\n continue\n locale, extension = path.split(\".\")\n if not re.match(\"[a-z]+(_[A-Z]+)?$\", locale):\n gen_log.error(\n \"Unrecognized locale %r (path: %s)\",\n locale,\n os.path.join(directory, path),\n )\n continue\n full_path = os.path.join(directory, path)\n if encoding is None:\n # Try to autodetect encoding based on the BOM.\n with open(full_path, \"rb\") as bf:\n data = bf.read(len(codecs.BOM_UTF16_LE))\n if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n encoding = \"utf-16\"\n else:\n # utf-8-sig is \"utf-8 with optional BOM\". It's discouraged\n # in most cases but is common with CSV files because Excel\n # cannot read utf-8 files without a BOM.\n encoding = \"utf-8-sig\"\n # python 3: csv.reader requires a file open in text mode.\n # Specify an encoding to avoid dependence on $LANG environment variable.\n with open(full_path, encoding=encoding) as f:\n _translations[locale] = {}\n for i, row in enumerate(csv.reader(f)):\n if not row or len(row) < 2:\n continue\n row = [escape.to_unicode(c).strip() for c in row]\n english, translation = row[:2]\n if len(row) > 2:\n plural = row[2] or \"unknown\"\n else:\n plural = \"unknown\"\n if plural not in (\"plural\", \"singular\", \"unknown\"):\n gen_log.error(\n \"Unrecognized plural indicator %r in %s line %d\",\n plural,\n path,\n i + 1,\n )\n continue\n _translations[locale].setdefault(plural, {})[english] = translation\n _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])\n gen_log.debug(\"Supported locales: %s\", sorted(_supported_locales))", "has_branch": true, "total_branches": 2} {"prompt_id": 678, "project": "tornado", "module": "tornado.locale", "class": "", "method": "load_gettext_translations", "focal_method_txt": "def load_gettext_translations(directory: str, domain: str) -> None:\n \"\"\"Loads translations from `gettext`'s locale tree\n\n Locale tree is similar to system's ``/usr/share/locale``, like::\n\n {directory}/{lang}/LC_MESSAGES/{domain}.mo\n\n Three steps are required to have your app translated:\n\n 1. Generate POT translation file::\n\n xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc\n\n 2. Merge against existing POT file::\n\n msgmerge old.po mydomain.po > new.po\n\n 3. Compile::\n\n msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo\n \"\"\"\n global _translations\n global _supported_locales\n global _use_gettext\n _translations = {}\n for lang in os.listdir(directory):\n if lang.startswith(\".\"):\n continue # skip .svn, etc\n if os.path.isfile(os.path.join(directory, lang)):\n continue\n try:\n os.stat(os.path.join(directory, lang, \"LC_MESSAGES\", domain + \".mo\"))\n _translations[lang] = gettext.translation(\n domain, directory, languages=[lang]\n )\n except Exception as e:\n gen_log.error(\"Cannot load translation for '%s': %s\", lang, str(e))\n continue\n _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])\n _use_gettext = True\n gen_log.debug(\"Supported locales: %s\", sorted(_supported_locales))", "focal_method_lines": [175, 215], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\ndef load_gettext_translations(directory: str, domain: str) -> None:\n \"\"\"Loads translations from `gettext`'s locale tree\n\n Locale tree is similar to system's ``/usr/share/locale``, like::\n\n {directory}/{lang}/LC_MESSAGES/{domain}.mo\n\n Three steps are required to have your app translated:\n\n 1. Generate POT translation file::\n\n xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc\n\n 2. Merge against existing POT file::\n\n msgmerge old.po mydomain.po > new.po\n\n 3. Compile::\n\n msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo\n \"\"\"\n global _translations\n global _supported_locales\n global _use_gettext\n _translations = {}\n for lang in os.listdir(directory):\n if lang.startswith(\".\"):\n continue # skip .svn, etc\n if os.path.isfile(os.path.join(directory, lang)):\n continue\n try:\n os.stat(os.path.join(directory, lang, \"LC_MESSAGES\", domain + \".mo\"))\n _translations[lang] = gettext.translation(\n domain, directory, languages=[lang]\n )\n except Exception as e:\n gen_log.error(\"Cannot load translation for '%s': %s\", lang, str(e))\n continue\n _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])\n _use_gettext = True\n gen_log.debug(\"Supported locales: %s\", sorted(_supported_locales))", "has_branch": true, "total_branches": 2} {"prompt_id": 679, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "__init__", "focal_method_txt": " def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]", "focal_method_lines": [268, 293], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]", "has_branch": true, "total_branches": 2} {"prompt_id": 680, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "pgettext", "focal_method_txt": " def pgettext(\n self,\n context: str,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n raise NotImplementedError()", "focal_method_lines": [318, 325], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\n def pgettext(\n self,\n context: str,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n raise NotImplementedError()", "has_branch": false, "total_branches": 0} {"prompt_id": 681, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "format_date", "focal_method_txt": " def format_date(\n self,\n date: Union[int, float, datetime.datetime],\n gmt_offset: int = 0,\n relative: bool = True,\n shorter: bool = False,\n full_format: bool = False,\n ) -> str:\n \"\"\"Formats the given date (which should be GMT).\n\n By default, we return a relative time (e.g., \"2 minutes ago\"). You\n can return an absolute date string with ``relative=False``.\n\n You can force a full format date (\"July 10, 1980\") with\n ``full_format=True``.\n\n This method is primarily intended for dates in the past.\n For dates in the future, we fall back to full format.\n \"\"\"\n if isinstance(date, (int, float)):\n date = datetime.datetime.utcfromtimestamp(date)\n now = datetime.datetime.utcnow()\n if date > now:\n if relative and (date - now).seconds < 60:\n # Due to click skew, things are some things slightly\n # in the future. Round timestamps in the immediate\n # future down to now in relative mode.\n date = now\n else:\n # Otherwise, future dates always use the full format.\n full_format = True\n local_date = date - datetime.timedelta(minutes=gmt_offset)\n local_now = now - datetime.timedelta(minutes=gmt_offset)\n local_yesterday = local_now - datetime.timedelta(hours=24)\n difference = now - date\n seconds = difference.seconds\n days = difference.days\n\n _ = self.translate\n format = None\n if not full_format:\n if relative and days == 0:\n if seconds < 50:\n return _(\"1 second ago\", \"%(seconds)d seconds ago\", seconds) % {\n \"seconds\": seconds\n }\n\n if seconds < 50 * 60:\n minutes = round(seconds / 60.0)\n return _(\"1 minute ago\", \"%(minutes)d minutes ago\", minutes) % {\n \"minutes\": minutes\n }\n\n hours = round(seconds / (60.0 * 60))\n return _(\"1 hour ago\", \"%(hours)d hours ago\", hours) % {\"hours\": hours}\n\n if days == 0:\n format = _(\"%(time)s\")\n elif days == 1 and local_date.day == local_yesterday.day and relative:\n format = _(\"yesterday\") if shorter else _(\"yesterday at %(time)s\")\n elif days < 5:\n format = _(\"%(weekday)s\") if shorter else _(\"%(weekday)s at %(time)s\")\n elif days < 334: # 11mo, since confusing for same month last year\n format = (\n _(\"%(month_name)s %(day)s\")\n if shorter\n else _(\"%(month_name)s %(day)s at %(time)s\")\n )\n\n if format is None:\n format = (\n _(\"%(month_name)s %(day)s, %(year)s\")\n if shorter\n else _(\"%(month_name)s %(day)s, %(year)s at %(time)s\")\n )\n\n tfhour_clock = self.code not in (\"en\", \"en_US\", \"zh_CN\")\n if tfhour_clock:\n str_time = \"%d:%02d\" % (local_date.hour, local_date.minute)\n elif self.code == \"zh_CN\":\n str_time = \"%s%d:%02d\" % (\n (u\"\\u4e0a\\u5348\", u\"\\u4e0b\\u5348\")[local_date.hour >= 12],\n local_date.hour % 12 or 12,\n local_date.minute,\n )\n else:\n str_time = \"%d:%02d %s\" % (\n local_date.hour % 12 or 12,\n local_date.minute,\n (\"am\", \"pm\")[local_date.hour >= 12],\n )\n\n return format % {\n \"month_name\": self._months[local_date.month - 1],\n \"weekday\": self._weekdays[local_date.weekday()],\n \"day\": str(local_date.day),\n \"year\": str(local_date.year),\n \"time\": str_time,\n }", "focal_method_lines": [327, 419], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\n def format_date(\n self,\n date: Union[int, float, datetime.datetime],\n gmt_offset: int = 0,\n relative: bool = True,\n shorter: bool = False,\n full_format: bool = False,\n ) -> str:\n \"\"\"Formats the given date (which should be GMT).\n\n By default, we return a relative time (e.g., \"2 minutes ago\"). You\n can return an absolute date string with ``relative=False``.\n\n You can force a full format date (\"July 10, 1980\") with\n ``full_format=True``.\n\n This method is primarily intended for dates in the past.\n For dates in the future, we fall back to full format.\n \"\"\"\n if isinstance(date, (int, float)):\n date = datetime.datetime.utcfromtimestamp(date)\n now = datetime.datetime.utcnow()\n if date > now:\n if relative and (date - now).seconds < 60:\n # Due to click skew, things are some things slightly\n # in the future. Round timestamps in the immediate\n # future down to now in relative mode.\n date = now\n else:\n # Otherwise, future dates always use the full format.\n full_format = True\n local_date = date - datetime.timedelta(minutes=gmt_offset)\n local_now = now - datetime.timedelta(minutes=gmt_offset)\n local_yesterday = local_now - datetime.timedelta(hours=24)\n difference = now - date\n seconds = difference.seconds\n days = difference.days\n\n _ = self.translate\n format = None\n if not full_format:\n if relative and days == 0:\n if seconds < 50:\n return _(\"1 second ago\", \"%(seconds)d seconds ago\", seconds) % {\n \"seconds\": seconds\n }\n\n if seconds < 50 * 60:\n minutes = round(seconds / 60.0)\n return _(\"1 minute ago\", \"%(minutes)d minutes ago\", minutes) % {\n \"minutes\": minutes\n }\n\n hours = round(seconds / (60.0 * 60))\n return _(\"1 hour ago\", \"%(hours)d hours ago\", hours) % {\"hours\": hours}\n\n if days == 0:\n format = _(\"%(time)s\")\n elif days == 1 and local_date.day == local_yesterday.day and relative:\n format = _(\"yesterday\") if shorter else _(\"yesterday at %(time)s\")\n elif days < 5:\n format = _(\"%(weekday)s\") if shorter else _(\"%(weekday)s at %(time)s\")\n elif days < 334: # 11mo, since confusing for same month last year\n format = (\n _(\"%(month_name)s %(day)s\")\n if shorter\n else _(\"%(month_name)s %(day)s at %(time)s\")\n )\n\n if format is None:\n format = (\n _(\"%(month_name)s %(day)s, %(year)s\")\n if shorter\n else _(\"%(month_name)s %(day)s, %(year)s at %(time)s\")\n )\n\n tfhour_clock = self.code not in (\"en\", \"en_US\", \"zh_CN\")\n if tfhour_clock:\n str_time = \"%d:%02d\" % (local_date.hour, local_date.minute)\n elif self.code == \"zh_CN\":\n str_time = \"%s%d:%02d\" % (\n (u\"\\u4e0a\\u5348\", u\"\\u4e0b\\u5348\")[local_date.hour >= 12],\n local_date.hour % 12 or 12,\n local_date.minute,\n )\n else:\n str_time = \"%d:%02d %s\" % (\n local_date.hour % 12 or 12,\n local_date.minute,\n (\"am\", \"pm\")[local_date.hour >= 12],\n )\n\n return format % {\n \"month_name\": self._months[local_date.month - 1],\n \"weekday\": self._weekdays[local_date.weekday()],\n \"day\": str(local_date.day),\n \"year\": str(local_date.year),\n \"time\": str_time,\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 682, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "format_day", "focal_method_txt": " def format_day(\n self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True\n ) -> bool:\n \"\"\"Formats the given date as a day of week.\n\n Example: \"Monday, January 22\". You can remove the day of week with\n ``dow=False``.\n \"\"\"\n local_date = date - datetime.timedelta(minutes=gmt_offset)\n _ = self.translate\n if dow:\n return _(\"%(weekday)s, %(month_name)s %(day)s\") % {\n \"month_name\": self._months[local_date.month - 1],\n \"weekday\": self._weekdays[local_date.weekday()],\n \"day\": str(local_date.day),\n }\n else:\n return _(\"%(month_name)s %(day)s\") % {\n \"month_name\": self._months[local_date.month - 1],\n \"day\": str(local_date.day),\n }", "focal_method_lines": [427, 444], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\n def format_day(\n self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True\n ) -> bool:\n \"\"\"Formats the given date as a day of week.\n\n Example: \"Monday, January 22\". You can remove the day of week with\n ``dow=False``.\n \"\"\"\n local_date = date - datetime.timedelta(minutes=gmt_offset)\n _ = self.translate\n if dow:\n return _(\"%(weekday)s, %(month_name)s %(day)s\") % {\n \"month_name\": self._months[local_date.month - 1],\n \"weekday\": self._weekdays[local_date.weekday()],\n \"day\": str(local_date.day),\n }\n else:\n return _(\"%(month_name)s %(day)s\") % {\n \"month_name\": self._months[local_date.month - 1],\n \"day\": str(local_date.day),\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 683, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "list", "focal_method_txt": " def list(self, parts: Any) -> str:\n \"\"\"Returns a comma-separated list for the given list of parts.\n\n The format is, e.g., \"A, B and C\", \"A and B\" or just \"A\" for lists\n of size 1.\n \"\"\"\n _ = self.translate\n if len(parts) == 0:\n return \"\"\n if len(parts) == 1:\n return parts[0]\n comma = u\" \\u0648 \" if self.code.startswith(\"fa\") else u\", \"\n return _(\"%(commas)s and %(last)s\") % {\n \"commas\": comma.join(parts[:-1]),\n \"last\": parts[len(parts) - 1],\n }", "focal_method_lines": [449, 461], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\n def list(self, parts: Any) -> str:\n \"\"\"Returns a comma-separated list for the given list of parts.\n\n The format is, e.g., \"A, B and C\", \"A and B\" or just \"A\" for lists\n of size 1.\n \"\"\"\n _ = self.translate\n if len(parts) == 0:\n return \"\"\n if len(parts) == 1:\n return parts[0]\n comma = u\" \\u0648 \" if self.code.startswith(\"fa\") else u\", \"\n return _(\"%(commas)s and %(last)s\") % {\n \"commas\": comma.join(parts[:-1]),\n \"last\": parts[len(parts) - 1],\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 684, "project": "tornado", "module": "tornado.locale", "class": "Locale", "method": "friendly_number", "focal_method_txt": " def friendly_number(self, value: int) -> str:\n \"\"\"Returns a comma-separated number for the given integer.\"\"\"\n if self.code not in (\"en\", \"en_US\"):\n return str(value)\n s = str(value)\n parts = []\n while s:\n parts.append(s[-3:])\n s = s[:-3]\n return \",\".join(reversed(parts))", "focal_method_lines": [466, 475], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass Locale(object):\n\n _cache = {}\n\n def __init__(self, code: str) -> None:\n self.code = code\n self.name = LOCALE_NAMES.get(code, {}).get(\"name\", u\"Unknown\")\n self.rtl = False\n for prefix in [\"fa\", \"ar\", \"he\"]:\n if self.code.startswith(prefix):\n self.rtl = True\n break\n\n # Initialize strings for date formatting\n _ = self.translate\n self._months = [\n _(\"January\"),\n _(\"February\"),\n _(\"March\"),\n _(\"April\"),\n _(\"May\"),\n _(\"June\"),\n _(\"July\"),\n _(\"August\"),\n _(\"September\"),\n _(\"October\"),\n _(\"November\"),\n _(\"December\"),\n ]\n self._weekdays = [\n _(\"Monday\"),\n _(\"Tuesday\"),\n _(\"Wednesday\"),\n _(\"Thursday\"),\n _(\"Friday\"),\n _(\"Saturday\"),\n _(\"Sunday\"),\n ]\n\n def friendly_number(self, value: int) -> str:\n \"\"\"Returns a comma-separated number for the given integer.\"\"\"\n if self.code not in (\"en\", \"en_US\"):\n return str(value)\n s = str(value)\n parts = []\n while s:\n parts.append(s[-3:])\n s = s[:-3]\n return \",\".join(reversed(parts))", "has_branch": true, "total_branches": 2} {"prompt_id": 685, "project": "tornado", "module": "tornado.locale", "class": "CSVLocale", "method": "translate", "focal_method_txt": " def translate(\n self,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n if plural_message is not None:\n assert count is not None\n if count != 1:\n message = plural_message\n message_dict = self.translations.get(\"plural\", {})\n else:\n message_dict = self.translations.get(\"singular\", {})\n else:\n message_dict = self.translations.get(\"unknown\", {})\n return message_dict.get(message, message)", "focal_method_lines": [485, 500], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass CSVLocale(Locale):\n\n def __init__(self, code: str, translations: Dict[str, Dict[str, str]]) -> None:\n self.translations = translations\n super().__init__(code)\n\n def translate(\n self,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n if plural_message is not None:\n assert count is not None\n if count != 1:\n message = plural_message\n message_dict = self.translations.get(\"plural\", {})\n else:\n message_dict = self.translations.get(\"singular\", {})\n else:\n message_dict = self.translations.get(\"unknown\", {})\n return message_dict.get(message, message)", "has_branch": true, "total_branches": 2} {"prompt_id": 686, "project": "tornado", "module": "tornado.locale", "class": "GettextLocale", "method": "translate", "focal_method_txt": " def translate(\n self,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n if plural_message is not None:\n assert count is not None\n return self.ngettext(message, plural_message, count)\n else:\n return self.gettext(message)", "focal_method_lines": [524, 534], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass GettextLocale(Locale):\n\n def __init__(self, code: str, translations: gettext.NullTranslations) -> None:\n self.ngettext = translations.ngettext\n self.gettext = translations.gettext\n # self.gettext must exist before __init__ is called, since it\n # calls into self.translate\n super().__init__(code)\n\n def translate(\n self,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n if plural_message is not None:\n assert count is not None\n return self.ngettext(message, plural_message, count)\n else:\n return self.gettext(message)", "has_branch": true, "total_branches": 2} {"prompt_id": 687, "project": "tornado", "module": "tornado.locale", "class": "GettextLocale", "method": "pgettext", "focal_method_txt": " def pgettext(\n self,\n context: str,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n \"\"\"Allows to set context for translation, accepts plural forms.\n\n Usage example::\n\n pgettext(\"law\", \"right\")\n pgettext(\"good\", \"right\")\n\n Plural message example::\n\n pgettext(\"organization\", \"club\", \"clubs\", len(clubs))\n pgettext(\"stick\", \"club\", \"clubs\", len(clubs))\n\n To generate POT file with context, add following options to step 1\n of `load_gettext_translations` sequence::\n\n xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3\n\n .. versionadded:: 4.2\n \"\"\"\n if plural_message is not None:\n assert count is not None\n msgs_with_ctxt = (\n \"%s%s%s\" % (context, CONTEXT_SEPARATOR, message),\n \"%s%s%s\" % (context, CONTEXT_SEPARATOR, plural_message),\n count,\n )\n result = self.ngettext(*msgs_with_ctxt)\n if CONTEXT_SEPARATOR in result:\n # Translation not found\n result = self.ngettext(message, plural_message, count)\n return result\n else:\n msg_with_ctxt = \"%s%s%s\" % (context, CONTEXT_SEPARATOR, message)\n result = self.gettext(msg_with_ctxt)\n if CONTEXT_SEPARATOR in result:\n # Translation not found\n result = message\n return result", "focal_method_lines": [536, 580], "in_stack": false, "globals": ["_default_locale", "_translations", "_supported_locales", "_use_gettext", "CONTEXT_SEPARATOR"], "type_context": "import codecs\nimport csv\nimport datetime\nimport gettext\nimport os\nimport re\nfrom tornado import escape\nfrom tornado.log import gen_log\nfrom tornado._locale_data import LOCALE_NAMES\nfrom typing import Iterable, Any, Union, Dict, Optional\n\n_default_locale = \"en_US\"\n_translations = {}\n_supported_locales = frozenset([_default_locale])\n_use_gettext = False\nCONTEXT_SEPARATOR = \"\\x04\"\n\nclass GettextLocale(Locale):\n\n def __init__(self, code: str, translations: gettext.NullTranslations) -> None:\n self.ngettext = translations.ngettext\n self.gettext = translations.gettext\n # self.gettext must exist before __init__ is called, since it\n # calls into self.translate\n super().__init__(code)\n\n def pgettext(\n self,\n context: str,\n message: str,\n plural_message: Optional[str] = None,\n count: Optional[int] = None,\n ) -> str:\n \"\"\"Allows to set context for translation, accepts plural forms.\n\n Usage example::\n\n pgettext(\"law\", \"right\")\n pgettext(\"good\", \"right\")\n\n Plural message example::\n\n pgettext(\"organization\", \"club\", \"clubs\", len(clubs))\n pgettext(\"stick\", \"club\", \"clubs\", len(clubs))\n\n To generate POT file with context, add following options to step 1\n of `load_gettext_translations` sequence::\n\n xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3\n\n .. versionadded:: 4.2\n \"\"\"\n if plural_message is not None:\n assert count is not None\n msgs_with_ctxt = (\n \"%s%s%s\" % (context, CONTEXT_SEPARATOR, message),\n \"%s%s%s\" % (context, CONTEXT_SEPARATOR, plural_message),\n count,\n )\n result = self.ngettext(*msgs_with_ctxt)\n if CONTEXT_SEPARATOR in result:\n # Translation not found\n result = self.ngettext(message, plural_message, count)\n return result\n else:\n msg_with_ctxt = \"%s%s%s\" % (context, CONTEXT_SEPARATOR, message)\n result = self.gettext(msg_with_ctxt)\n if CONTEXT_SEPARATOR in result:\n # Translation not found\n result = message\n return result", "has_branch": true, "total_branches": 2} {"prompt_id": 688, "project": "tornado", "module": "tornado.locks", "class": "Condition", "method": "__repr__", "focal_method_txt": " def __repr__(self) -> str:\n result = \"<%s\" % (self.__class__.__name__,)\n if self._waiters:\n result += \" waiters[%s]\" % len(self._waiters)\n return result + \">\"", "focal_method_lines": [116, 120], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Condition(_TimeoutGarbageCollector):\n\n def __init__(self) -> None:\n super().__init__()\n self.io_loop = ioloop.IOLoop.current()\n\n def __repr__(self) -> str:\n result = \"<%s\" % (self.__class__.__name__,)\n if self._waiters:\n result += \" waiters[%s]\" % len(self._waiters)\n return result + \">\"", "has_branch": true, "total_branches": 2} {"prompt_id": 689, "project": "tornado", "module": "tornado.locks", "class": "Condition", "method": "wait", "focal_method_txt": " def wait(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[bool]:\n \"\"\"Wait for `.notify`.\n\n Returns a `.Future` that resolves ``True`` if the condition is notified,\n or ``False`` after a timeout.\n \"\"\"\n waiter = Future() # type: Future[bool]\n self._waiters.append(waiter)\n if timeout:\n\n def on_timeout() -> None:\n if not waiter.done():\n future_set_result_unless_cancelled(waiter, False)\n self._garbage_collect()\n\n io_loop = ioloop.IOLoop.current()\n timeout_handle = io_loop.add_timeout(timeout, on_timeout)\n waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle))\n return waiter", "focal_method_lines": [122, 142], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Condition(_TimeoutGarbageCollector):\n\n def __init__(self) -> None:\n super().__init__()\n self.io_loop = ioloop.IOLoop.current()\n\n def wait(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[bool]:\n \"\"\"Wait for `.notify`.\n\n Returns a `.Future` that resolves ``True`` if the condition is notified,\n or ``False`` after a timeout.\n \"\"\"\n waiter = Future() # type: Future[bool]\n self._waiters.append(waiter)\n if timeout:\n\n def on_timeout() -> None:\n if not waiter.done():\n future_set_result_unless_cancelled(waiter, False)\n self._garbage_collect()\n\n io_loop = ioloop.IOLoop.current()\n timeout_handle = io_loop.add_timeout(timeout, on_timeout)\n waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle))\n return waiter", "has_branch": true, "total_branches": 2} {"prompt_id": 690, "project": "tornado", "module": "tornado.locks", "class": "Condition", "method": "notify", "focal_method_txt": " def notify(self, n: int = 1) -> None:\n \"\"\"Wake ``n`` waiters.\"\"\"\n waiters = [] # Waiters we plan to run right now.\n while n and self._waiters:\n waiter = self._waiters.popleft()\n if not waiter.done(): # Might have timed out.\n n -= 1\n waiters.append(waiter)\n\n for waiter in waiters:\n future_set_result_unless_cancelled(waiter, True)", "focal_method_lines": [144, 154], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Condition(_TimeoutGarbageCollector):\n\n def __init__(self) -> None:\n super().__init__()\n self.io_loop = ioloop.IOLoop.current()\n\n def notify(self, n: int = 1) -> None:\n \"\"\"Wake ``n`` waiters.\"\"\"\n waiters = [] # Waiters we plan to run right now.\n while n and self._waiters:\n waiter = self._waiters.popleft()\n if not waiter.done(): # Might have timed out.\n n -= 1\n waiters.append(waiter)\n\n for waiter in waiters:\n future_set_result_unless_cancelled(waiter, True)", "has_branch": true, "total_branches": 2} {"prompt_id": 691, "project": "tornado", "module": "tornado.locks", "class": "Condition", "method": "notify_all", "focal_method_txt": " def notify_all(self) -> None:\n \"\"\"Wake all waiters.\"\"\"\n self.notify(len(self._waiters))", "focal_method_lines": [156, 158], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Condition(_TimeoutGarbageCollector):\n\n def __init__(self) -> None:\n super().__init__()\n self.io_loop = ioloop.IOLoop.current()\n\n def notify_all(self) -> None:\n \"\"\"Wake all waiters.\"\"\"\n self.notify(len(self._waiters))", "has_branch": false, "total_branches": 0} {"prompt_id": 692, "project": "tornado", "module": "tornado.locks", "class": "Event", "method": "set", "focal_method_txt": " def set(self) -> None:\n \"\"\"Set the internal flag to ``True``. All waiters are awakened.\n\n Calling `.wait` once the flag is set will not block.\n \"\"\"\n if not self._value:\n self._value = True\n\n for fut in self._waiters:\n if not fut.done():\n fut.set_result(None)", "focal_method_lines": [215, 225], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Event(object):\n\n def __init__(self) -> None:\n self._value = False\n self._waiters = set()\n\n def set(self) -> None:\n \"\"\"Set the internal flag to ``True``. All waiters are awakened.\n\n Calling `.wait` once the flag is set will not block.\n \"\"\"\n if not self._value:\n self._value = True\n\n for fut in self._waiters:\n if not fut.done():\n fut.set_result(None)", "has_branch": true, "total_branches": 2} {"prompt_id": 693, "project": "tornado", "module": "tornado.locks", "class": "Event", "method": "wait", "focal_method_txt": " def wait(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[None]:\n \"\"\"Block until the internal flag is true.\n\n Returns an awaitable, which raises `tornado.util.TimeoutError` after a\n timeout.\n \"\"\"\n fut = Future() # type: Future[None]\n if self._value:\n fut.set_result(None)\n return fut\n self._waiters.add(fut)\n fut.add_done_callback(lambda fut: self._waiters.remove(fut))\n if timeout is None:\n return fut\n else:\n timeout_fut = gen.with_timeout(timeout, fut)\n # This is a slightly clumsy workaround for the fact that\n # gen.with_timeout doesn't cancel its futures. Cancelling\n # fut will remove it from the waiters list.\n timeout_fut.add_done_callback(\n lambda tf: fut.cancel() if not fut.done() else None\n )\n return timeout_fut", "focal_method_lines": [234, 258], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Event(object):\n\n def __init__(self) -> None:\n self._value = False\n self._waiters = set()\n\n def wait(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[None]:\n \"\"\"Block until the internal flag is true.\n\n Returns an awaitable, which raises `tornado.util.TimeoutError` after a\n timeout.\n \"\"\"\n fut = Future() # type: Future[None]\n if self._value:\n fut.set_result(None)\n return fut\n self._waiters.add(fut)\n fut.add_done_callback(lambda fut: self._waiters.remove(fut))\n if timeout is None:\n return fut\n else:\n timeout_fut = gen.with_timeout(timeout, fut)\n # This is a slightly clumsy workaround for the fact that\n # gen.with_timeout doesn't cancel its futures. Cancelling\n # fut will remove it from the waiters list.\n timeout_fut.add_done_callback(\n lambda tf: fut.cancel() if not fut.done() else None\n )\n return timeout_fut", "has_branch": true, "total_branches": 2} {"prompt_id": 694, "project": "tornado", "module": "tornado.locks", "class": "_ReleasingContextManager", "method": "__exit__", "focal_method_txt": " def __exit__(\n self,\n exc_type: \"Optional[Type[BaseException]]\",\n exc_val: Optional[BaseException],\n exc_tb: Optional[types.TracebackType],\n ) -> None:\n self._obj.release()", "focal_method_lines": [276, 282], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass _ReleasingContextManager(object):\n\n def __init__(self, obj: Any) -> None:\n self._obj = obj\n\n def __exit__(\n self,\n exc_type: \"Optional[Type[BaseException]]\",\n exc_val: Optional[BaseException],\n exc_tb: Optional[types.TracebackType],\n ) -> None:\n self._obj.release()", "has_branch": false, "total_branches": 0} {"prompt_id": 695, "project": "tornado", "module": "tornado.locks", "class": "Semaphore", "method": "__repr__", "focal_method_txt": " def __repr__(self) -> str:\n res = super().__repr__()\n extra = (\n \"locked\" if self._value == 0 else \"unlocked,value:{0}\".format(self._value)\n )\n if self._waiters:\n extra = \"{0},waiters:{1}\".format(extra, len(self._waiters))\n return \"<{0} [{1}]>\".format(res[1:-1], extra)", "focal_method_lines": [388, 395], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\n def __repr__(self) -> str:\n res = super().__repr__()\n extra = (\n \"locked\" if self._value == 0 else \"unlocked,value:{0}\".format(self._value)\n )\n if self._waiters:\n extra = \"{0},waiters:{1}\".format(extra, len(self._waiters))\n return \"<{0} [{1}]>\".format(res[1:-1], extra)", "has_branch": true, "total_branches": 2} {"prompt_id": 696, "project": "tornado", "module": "tornado.locks", "class": "Semaphore", "method": "release", "focal_method_txt": " def release(self) -> None:\n \"\"\"Increment the counter and wake one waiter.\"\"\"\n self._value += 1\n while self._waiters:\n waiter = self._waiters.popleft()\n if not waiter.done():\n self._value -= 1\n\n # If the waiter is a coroutine paused at\n #\n # with (yield semaphore.acquire()):\n #\n # then the context manager's __exit__ calls release() at the end\n # of the \"with\" block.\n waiter.set_result(_ReleasingContextManager(self))\n break", "focal_method_lines": [397, 412], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass _ReleasingContextManager(object):\n\n def __init__(self, obj: Any) -> None:\n self._obj = obj\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\n def release(self) -> None:\n \"\"\"Increment the counter and wake one waiter.\"\"\"\n self._value += 1\n while self._waiters:\n waiter = self._waiters.popleft()\n if not waiter.done():\n self._value -= 1\n\n # If the waiter is a coroutine paused at\n #\n # with (yield semaphore.acquire()):\n #\n # then the context manager's __exit__ calls release() at the end\n # of the \"with\" block.\n waiter.set_result(_ReleasingContextManager(self))\n break", "has_branch": true, "total_branches": 2} {"prompt_id": 697, "project": "tornado", "module": "tornado.locks", "class": "Semaphore", "method": "acquire", "focal_method_txt": " def acquire(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[_ReleasingContextManager]:\n \"\"\"Decrement the counter. Returns an awaitable.\n\n Block if the counter is zero and wait for a `.release`. The awaitable\n raises `.TimeoutError` after the deadline.\n \"\"\"\n waiter = Future() # type: Future[_ReleasingContextManager]\n if self._value > 0:\n self._value -= 1\n waiter.set_result(_ReleasingContextManager(self))\n else:\n self._waiters.append(waiter)\n if timeout:\n\n def on_timeout() -> None:\n if not waiter.done():\n waiter.set_exception(gen.TimeoutError())\n self._garbage_collect()\n\n io_loop = ioloop.IOLoop.current()\n timeout_handle = io_loop.add_timeout(timeout, on_timeout)\n waiter.add_done_callback(\n lambda _: io_loop.remove_timeout(timeout_handle)\n )\n return waiter", "focal_method_lines": [414, 440], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass _ReleasingContextManager(object):\n\n def __init__(self, obj: Any) -> None:\n self._obj = obj\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\n def acquire(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[_ReleasingContextManager]:\n \"\"\"Decrement the counter. Returns an awaitable.\n\n Block if the counter is zero and wait for a `.release`. The awaitable\n raises `.TimeoutError` after the deadline.\n \"\"\"\n waiter = Future() # type: Future[_ReleasingContextManager]\n if self._value > 0:\n self._value -= 1\n waiter.set_result(_ReleasingContextManager(self))\n else:\n self._waiters.append(waiter)\n if timeout:\n\n def on_timeout() -> None:\n if not waiter.done():\n waiter.set_exception(gen.TimeoutError())\n self._garbage_collect()\n\n io_loop = ioloop.IOLoop.current()\n timeout_handle = io_loop.add_timeout(timeout, on_timeout)\n waiter.add_done_callback(\n lambda _: io_loop.remove_timeout(timeout_handle)\n )\n return waiter", "has_branch": true, "total_branches": 2} {"prompt_id": 698, "project": "tornado", "module": "tornado.locks", "class": "Semaphore", "method": "__aenter__", "focal_method_txt": " async def __aenter__(self) -> None:\n await self.acquire()", "focal_method_lines": [453, 454], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\n async def __aenter__(self) -> None:\n await self.acquire()", "has_branch": false, "total_branches": 0} {"prompt_id": 699, "project": "tornado", "module": "tornado.locks", "class": "Semaphore", "method": "__aexit__", "focal_method_txt": " async def __aexit__(\n self,\n typ: \"Optional[Type[BaseException]]\",\n value: Optional[BaseException],\n tb: Optional[types.TracebackType],\n ) -> None:\n self.release()", "focal_method_lines": [456, 462], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\n async def __aexit__(\n self,\n typ: \"Optional[Type[BaseException]]\",\n value: Optional[BaseException],\n tb: Optional[types.TracebackType],\n ) -> None:\n self.release()", "has_branch": false, "total_branches": 0} {"prompt_id": 700, "project": "tornado", "module": "tornado.locks", "class": "BoundedSemaphore", "method": "release", "focal_method_txt": " def release(self) -> None:\n \"\"\"Increment the counter and wake one waiter.\"\"\"\n if self._value >= self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n super().release()", "focal_method_lines": [478, 482], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Semaphore(_TimeoutGarbageCollector):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__()\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n\n self._value = value\n\nclass BoundedSemaphore(Semaphore):\n\n def __init__(self, value: int = 1) -> None:\n super().__init__(value=value)\n self._initial_value = value\n\n def release(self) -> None:\n \"\"\"Increment the counter and wake one waiter.\"\"\"\n if self._value >= self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n super().release()", "has_branch": true, "total_branches": 2} {"prompt_id": 701, "project": "tornado", "module": "tornado.locks", "class": "Lock", "method": "release", "focal_method_txt": " def release(self) -> None:\n \"\"\"Unlock.\n\n The first coroutine in line waiting for `acquire` gets the lock.\n\n If not locked, raise a `RuntimeError`.\n \"\"\"\n try:\n self._block.release()\n except ValueError:\n raise RuntimeError(\"release unlocked lock\")", "focal_method_lines": [538, 548], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Lock(object):\n\n def __init__(self) -> None:\n self._block = BoundedSemaphore(value=1)\n\n def release(self) -> None:\n \"\"\"Unlock.\n\n The first coroutine in line waiting for `acquire` gets the lock.\n\n If not locked, raise a `RuntimeError`.\n \"\"\"\n try:\n self._block.release()\n except ValueError:\n raise RuntimeError(\"release unlocked lock\")", "has_branch": false, "total_branches": 0} {"prompt_id": 702, "project": "tornado", "module": "tornado.locks", "class": "Lock", "method": "__aenter__", "focal_method_txt": " async def __aenter__(self) -> None:\n await self.acquire()", "focal_method_lines": [561, 562], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Lock(object):\n\n def __init__(self) -> None:\n self._block = BoundedSemaphore(value=1)\n\n async def __aenter__(self) -> None:\n await self.acquire()", "has_branch": false, "total_branches": 0} {"prompt_id": 703, "project": "tornado", "module": "tornado.locks", "class": "Lock", "method": "__aexit__", "focal_method_txt": " async def __aexit__(\n self,\n typ: \"Optional[Type[BaseException]]\",\n value: Optional[BaseException],\n tb: Optional[types.TracebackType],\n ) -> None:\n self.release()", "focal_method_lines": [564, 570], "in_stack": false, "globals": ["__all__"], "type_context": "import collections\nimport datetime\nimport types\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom typing import Union, Optional, Type, Any, Awaitable\nimport typing\n\n__all__ = [\"Condition\", \"Event\", \"Semaphore\", \"BoundedSemaphore\", \"Lock\"]\n\nclass Lock(object):\n\n def __init__(self) -> None:\n self._block = BoundedSemaphore(value=1)\n\n async def __aexit__(\n self,\n typ: \"Optional[Type[BaseException]]\",\n value: Optional[BaseException],\n tb: Optional[types.TracebackType],\n ) -> None:\n self.release()", "has_branch": false, "total_branches": 0} {"prompt_id": 704, "project": "tornado", "module": "tornado.log", "class": "", "method": "enable_pretty_logging", "focal_method_txt": "def enable_pretty_logging(\n options: Any = None, logger: Optional[logging.Logger] = None\n) -> None:\n \"\"\"Turns on formatted logging output as configured.\n\n This is called automatically by `tornado.options.parse_command_line`\n and `tornado.options.parse_config_file`.\n \"\"\"\n if options is None:\n import tornado.options\n\n options = tornado.options.options\n if options.logging is None or options.logging.lower() == \"none\":\n return\n if logger is None:\n logger = logging.getLogger()\n logger.setLevel(getattr(logging, options.logging.upper()))\n if options.log_file_prefix:\n rotate_mode = options.log_rotate_mode\n if rotate_mode == \"size\":\n channel = logging.handlers.RotatingFileHandler(\n filename=options.log_file_prefix,\n maxBytes=options.log_file_max_size,\n backupCount=options.log_file_num_backups,\n encoding=\"utf-8\",\n ) # type: logging.Handler\n elif rotate_mode == \"time\":\n channel = logging.handlers.TimedRotatingFileHandler(\n filename=options.log_file_prefix,\n when=options.log_rotate_when,\n interval=options.log_rotate_interval,\n backupCount=options.log_file_num_backups,\n encoding=\"utf-8\",\n )\n else:\n error_message = (\n \"The value of log_rotate_mode option should be \"\n + '\"size\" or \"time\", not \"%s\".' % rotate_mode\n )\n raise ValueError(error_message)\n channel.setFormatter(LogFormatter(color=False))\n logger.addHandler(channel)\n\n if options.log_to_stderr or (options.log_to_stderr is None and not logger.handlers):\n # Set up color if we are in a tty and curses is installed\n channel = logging.StreamHandler()\n channel.setFormatter(LogFormatter())\n logger.addHandler(channel)", "focal_method_lines": [210, 257], "in_stack": false, "globals": ["access_log", "app_log", "gen_log"], "type_context": "import logging\nimport logging.handlers\nimport sys\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\nfrom typing import Dict, Any, cast, Optional\n\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\nclass LogFormatter(logging.Formatter):\n\n DEFAULT_FORMAT = \"%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s\"\n\n DEFAULT_DATE_FORMAT = \"%y%m%d %H:%M:%S\"\n\n DEFAULT_COLORS = {\n logging.DEBUG: 4, # Blue\n logging.INFO: 2, # Green\n logging.WARNING: 3, # Yellow\n logging.ERROR: 1, # Red\n logging.CRITICAL: 5, # Magenta\n }\n\n def __init__(\n self,\n fmt: str = DEFAULT_FORMAT,\n datefmt: str = DEFAULT_DATE_FORMAT,\n style: str = \"%\",\n color: bool = True,\n colors: Dict[int, int] = DEFAULT_COLORS,\n ) -> None:\n r\"\"\"\n :arg bool color: Enables color support.\n :arg str fmt: Log message format.\n It will be applied to the attributes dict of log records. The\n text between ``%(color)s`` and ``%(end_color)s`` will be colored\n depending on the level if color support is on.\n :arg dict colors: color mappings from logging level to terminal color\n code\n :arg str datefmt: Datetime format.\n Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n .. versionchanged:: 3.2\n\n Added ``fmt`` and ``datefmt`` arguments.\n \"\"\"\n logging.Formatter.__init__(self, datefmt=datefmt)\n self._fmt = fmt\n\n self._colors = {} # type: Dict[int, str]\n if color and _stderr_supports_color():\n if curses is not None:\n fg_color = curses.tigetstr(\"setaf\") or curses.tigetstr(\"setf\") or b\"\"\n\n for levelno, code in colors.items():\n # Convert the terminal control characters from\n # bytes to unicode strings for easier use with the\n # logging module.\n self._colors[levelno] = unicode_type(\n curses.tparm(fg_color, code), \"ascii\"\n )\n self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n else:\n # If curses is not present (currently we'll only get here for\n # colorama on windows), assume hard-coded ANSI color codes.\n for levelno, code in colors.items():\n self._colors[levelno] = \"\\033[2;3%dm\" % code\n self._normal = \"\\033[0m\"\n else:\n self._normal = \"\"\n\ndef enable_pretty_logging(\n options: Any = None, logger: Optional[logging.Logger] = None\n) -> None:\n \"\"\"Turns on formatted logging output as configured.\n\n This is called automatically by `tornado.options.parse_command_line`\n and `tornado.options.parse_config_file`.\n \"\"\"\n if options is None:\n import tornado.options\n\n options = tornado.options.options\n if options.logging is None or options.logging.lower() == \"none\":\n return\n if logger is None:\n logger = logging.getLogger()\n logger.setLevel(getattr(logging, options.logging.upper()))\n if options.log_file_prefix:\n rotate_mode = options.log_rotate_mode\n if rotate_mode == \"size\":\n channel = logging.handlers.RotatingFileHandler(\n filename=options.log_file_prefix,\n maxBytes=options.log_file_max_size,\n backupCount=options.log_file_num_backups,\n encoding=\"utf-8\",\n ) # type: logging.Handler\n elif rotate_mode == \"time\":\n channel = logging.handlers.TimedRotatingFileHandler(\n filename=options.log_file_prefix,\n when=options.log_rotate_when,\n interval=options.log_rotate_interval,\n backupCount=options.log_file_num_backups,\n encoding=\"utf-8\",\n )\n else:\n error_message = (\n \"The value of log_rotate_mode option should be \"\n + '\"size\" or \"time\", not \"%s\".' % rotate_mode\n )\n raise ValueError(error_message)\n channel.setFormatter(LogFormatter(color=False))\n logger.addHandler(channel)\n\n if options.log_to_stderr or (options.log_to_stderr is None and not logger.handlers):\n # Set up color if we are in a tty and curses is installed\n channel = logging.StreamHandler()\n channel.setFormatter(LogFormatter())\n logger.addHandler(channel)", "has_branch": true, "total_branches": 2} {"prompt_id": 705, "project": "tornado", "module": "tornado.log", "class": "", "method": "define_logging_options", "focal_method_txt": "def define_logging_options(options: Any = None) -> None:\n \"\"\"Add logging-related flags to ``options``.\n\n These options are present automatically on the default options instance;\n this method is only necessary if you have created your own `.OptionParser`.\n\n .. versionadded:: 4.2\n This function existed in prior versions but was broken and undocumented until 4.2.\n \"\"\"\n if options is None:\n # late import to prevent cycle\n import tornado.options\n\n options = tornado.options.options\n options.define(\n \"logging\",\n default=\"info\",\n help=(\n \"Set the Python log level. If 'none', tornado won't touch the \"\n \"logging configuration.\"\n ),\n metavar=\"debug|info|warning|error|none\",\n )\n options.define(\n \"log_to_stderr\",\n type=bool,\n default=None,\n help=(\n \"Send log output to stderr (colorized if possible). \"\n \"By default use stderr if --log_file_prefix is not set and \"\n \"no other logging is configured.\"\n ),\n )\n options.define(\n \"log_file_prefix\",\n type=str,\n default=None,\n metavar=\"PATH\",\n help=(\n \"Path prefix for log files. \"\n \"Note that if you are running multiple tornado processes, \"\n \"log_file_prefix must be different for each of them (e.g. \"\n \"include the port number)\"\n ),\n )\n options.define(\n \"log_file_max_size\",\n type=int,\n default=100 * 1000 * 1000,\n help=\"max size of log files before rollover\",\n )\n options.define(\n \"log_file_num_backups\", type=int, default=10, help=\"number of log files to keep\"\n )\n\n options.define(\n \"log_rotate_when\",\n type=str,\n default=\"midnight\",\n help=(\n \"specify the type of TimedRotatingFileHandler interval \"\n \"other options:('S', 'M', 'H', 'D', 'W0'-'W6')\"\n ),\n )\n options.define(\n \"log_rotate_interval\",\n type=int,\n default=1,\n help=\"The interval value of timed rotating\",\n )\n\n options.define(\n \"log_rotate_mode\",\n type=str,\n default=\"size\",\n help=\"The mode of rotating files(time or size)\",\n )\n\n options.add_parse_callback(lambda: enable_pretty_logging(options))", "focal_method_lines": [260, 338], "in_stack": false, "globals": ["access_log", "app_log", "gen_log"], "type_context": "import logging\nimport logging.handlers\nimport sys\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\nfrom typing import Dict, Any, cast, Optional\n\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\ndef define_logging_options(options: Any = None) -> None:\n \"\"\"Add logging-related flags to ``options``.\n\n These options are present automatically on the default options instance;\n this method is only necessary if you have created your own `.OptionParser`.\n\n .. versionadded:: 4.2\n This function existed in prior versions but was broken and undocumented until 4.2.\n \"\"\"\n if options is None:\n # late import to prevent cycle\n import tornado.options\n\n options = tornado.options.options\n options.define(\n \"logging\",\n default=\"info\",\n help=(\n \"Set the Python log level. If 'none', tornado won't touch the \"\n \"logging configuration.\"\n ),\n metavar=\"debug|info|warning|error|none\",\n )\n options.define(\n \"log_to_stderr\",\n type=bool,\n default=None,\n help=(\n \"Send log output to stderr (colorized if possible). \"\n \"By default use stderr if --log_file_prefix is not set and \"\n \"no other logging is configured.\"\n ),\n )\n options.define(\n \"log_file_prefix\",\n type=str,\n default=None,\n metavar=\"PATH\",\n help=(\n \"Path prefix for log files. \"\n \"Note that if you are running multiple tornado processes, \"\n \"log_file_prefix must be different for each of them (e.g. \"\n \"include the port number)\"\n ),\n )\n options.define(\n \"log_file_max_size\",\n type=int,\n default=100 * 1000 * 1000,\n help=\"max size of log files before rollover\",\n )\n options.define(\n \"log_file_num_backups\", type=int, default=10, help=\"number of log files to keep\"\n )\n\n options.define(\n \"log_rotate_when\",\n type=str,\n default=\"midnight\",\n help=(\n \"specify the type of TimedRotatingFileHandler interval \"\n \"other options:('S', 'M', 'H', 'D', 'W0'-'W6')\"\n ),\n )\n options.define(\n \"log_rotate_interval\",\n type=int,\n default=1,\n help=\"The interval value of timed rotating\",\n )\n\n options.define(\n \"log_rotate_mode\",\n type=str,\n default=\"size\",\n help=\"The mode of rotating files(time or size)\",\n )\n\n options.add_parse_callback(lambda: enable_pretty_logging(options))", "has_branch": true, "total_branches": 2} {"prompt_id": 706, "project": "tornado", "module": "tornado.log", "class": "LogFormatter", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n fmt: str = DEFAULT_FORMAT,\n datefmt: str = DEFAULT_DATE_FORMAT,\n style: str = \"%\",\n color: bool = True,\n colors: Dict[int, int] = DEFAULT_COLORS,\n ) -> None:\n r\"\"\"\n :arg bool color: Enables color support.\n :arg str fmt: Log message format.\n It will be applied to the attributes dict of log records. The\n text between ``%(color)s`` and ``%(end_color)s`` will be colored\n depending on the level if color support is on.\n :arg dict colors: color mappings from logging level to terminal color\n code\n :arg str datefmt: Datetime format.\n Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n .. versionchanged:: 3.2\n\n Added ``fmt`` and ``datefmt`` arguments.\n \"\"\"\n logging.Formatter.__init__(self, datefmt=datefmt)\n self._fmt = fmt\n\n self._colors = {} # type: Dict[int, str]\n if color and _stderr_supports_color():\n if curses is not None:\n fg_color = curses.tigetstr(\"setaf\") or curses.tigetstr(\"setf\") or b\"\"\n\n for levelno, code in colors.items():\n # Convert the terminal control characters from\n # bytes to unicode strings for easier use with the\n # logging module.\n self._colors[levelno] = unicode_type(\n curses.tparm(fg_color, code), \"ascii\"\n )\n self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n else:\n # If curses is not present (currently we'll only get here for\n # colorama on windows), assume hard-coded ANSI color codes.\n for levelno, code in colors.items():\n self._colors[levelno] = \"\\033[2;3%dm\" % code\n self._normal = \"\\033[0m\"\n else:\n self._normal = \"\"", "focal_method_lines": [115, 161], "in_stack": false, "globals": ["access_log", "app_log", "gen_log"], "type_context": "import logging\nimport logging.handlers\nimport sys\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\nfrom typing import Dict, Any, cast, Optional\n\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\nclass LogFormatter(logging.Formatter):\n\n DEFAULT_FORMAT = \"%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s\"\n\n DEFAULT_DATE_FORMAT = \"%y%m%d %H:%M:%S\"\n\n DEFAULT_COLORS = {\n logging.DEBUG: 4, # Blue\n logging.INFO: 2, # Green\n logging.WARNING: 3, # Yellow\n logging.ERROR: 1, # Red\n logging.CRITICAL: 5, # Magenta\n }\n\n def __init__(\n self,\n fmt: str = DEFAULT_FORMAT,\n datefmt: str = DEFAULT_DATE_FORMAT,\n style: str = \"%\",\n color: bool = True,\n colors: Dict[int, int] = DEFAULT_COLORS,\n ) -> None:\n r\"\"\"\n :arg bool color: Enables color support.\n :arg str fmt: Log message format.\n It will be applied to the attributes dict of log records. The\n text between ``%(color)s`` and ``%(end_color)s`` will be colored\n depending on the level if color support is on.\n :arg dict colors: color mappings from logging level to terminal color\n code\n :arg str datefmt: Datetime format.\n Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n .. versionchanged:: 3.2\n\n Added ``fmt`` and ``datefmt`` arguments.\n \"\"\"\n logging.Formatter.__init__(self, datefmt=datefmt)\n self._fmt = fmt\n\n self._colors = {} # type: Dict[int, str]\n if color and _stderr_supports_color():\n if curses is not None:\n fg_color = curses.tigetstr(\"setaf\") or curses.tigetstr(\"setf\") or b\"\"\n\n for levelno, code in colors.items():\n # Convert the terminal control characters from\n # bytes to unicode strings for easier use with the\n # logging module.\n self._colors[levelno] = unicode_type(\n curses.tparm(fg_color, code), \"ascii\"\n )\n self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n else:\n # If curses is not present (currently we'll only get here for\n # colorama on windows), assume hard-coded ANSI color codes.\n for levelno, code in colors.items():\n self._colors[levelno] = \"\\033[2;3%dm\" % code\n self._normal = \"\\033[0m\"\n else:\n self._normal = \"\"", "has_branch": true, "total_branches": 2} {"prompt_id": 707, "project": "tornado", "module": "tornado.log", "class": "LogFormatter", "method": "format", "focal_method_txt": " def format(self, record: Any) -> str:\n try:\n message = record.getMessage()\n assert isinstance(message, basestring_type) # guaranteed by logging\n # Encoding notes: The logging module prefers to work with character\n # strings, but only enforces that log messages are instances of\n # basestring. In python 2, non-ascii bytestrings will make\n # their way through the logging framework until they blow up with\n # an unhelpful decoding error (with this formatter it happens\n # when we attach the prefix, but there are other opportunities for\n # exceptions further along in the framework).\n #\n # If a byte string makes it this far, convert it to unicode to\n # ensure it will make it out to the logs. Use repr() as a fallback\n # to ensure that all byte strings can be converted successfully,\n # but don't do it by default so we don't add extra quotes to ascii\n # bytestrings. This is a bit of a hacky place to do this, but\n # it's worth it since the encoding errors that would otherwise\n # result are so useless (and tornado is fond of using utf8-encoded\n # byte strings wherever possible).\n record.message = _safe_unicode(message)\n except Exception as e:\n record.message = \"Bad message (%r): %r\" % (e, record.__dict__)\n\n record.asctime = self.formatTime(record, cast(str, self.datefmt))\n\n if record.levelno in self._colors:\n record.color = self._colors[record.levelno]\n record.end_color = self._normal\n else:\n record.color = record.end_color = \"\"\n\n formatted = self._fmt % record.__dict__\n\n if record.exc_info:\n if not record.exc_text:\n record.exc_text = self.formatException(record.exc_info)\n if record.exc_text:\n # exc_text contains multiple lines. We need to _safe_unicode\n # each line separately so that non-utf8 bytes don't cause\n # all the newlines to turn into '\\n'.\n lines = [formatted.rstrip()]\n lines.extend(_safe_unicode(ln) for ln in record.exc_text.split(\"\\n\"))\n formatted = \"\\n\".join(lines)\n return formatted.replace(\"\\n\", \"\\n \")", "focal_method_lines": [163, 207], "in_stack": false, "globals": ["access_log", "app_log", "gen_log"], "type_context": "import logging\nimport logging.handlers\nimport sys\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\nfrom typing import Dict, Any, cast, Optional\n\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\nclass LogFormatter(logging.Formatter):\n\n DEFAULT_FORMAT = \"%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s\"\n\n DEFAULT_DATE_FORMAT = \"%y%m%d %H:%M:%S\"\n\n DEFAULT_COLORS = {\n logging.DEBUG: 4, # Blue\n logging.INFO: 2, # Green\n logging.WARNING: 3, # Yellow\n logging.ERROR: 1, # Red\n logging.CRITICAL: 5, # Magenta\n }\n\n def __init__(\n self,\n fmt: str = DEFAULT_FORMAT,\n datefmt: str = DEFAULT_DATE_FORMAT,\n style: str = \"%\",\n color: bool = True,\n colors: Dict[int, int] = DEFAULT_COLORS,\n ) -> None:\n r\"\"\"\n :arg bool color: Enables color support.\n :arg str fmt: Log message format.\n It will be applied to the attributes dict of log records. The\n text between ``%(color)s`` and ``%(end_color)s`` will be colored\n depending on the level if color support is on.\n :arg dict colors: color mappings from logging level to terminal color\n code\n :arg str datefmt: Datetime format.\n Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n .. versionchanged:: 3.2\n\n Added ``fmt`` and ``datefmt`` arguments.\n \"\"\"\n logging.Formatter.__init__(self, datefmt=datefmt)\n self._fmt = fmt\n\n self._colors = {} # type: Dict[int, str]\n if color and _stderr_supports_color():\n if curses is not None:\n fg_color = curses.tigetstr(\"setaf\") or curses.tigetstr(\"setf\") or b\"\"\n\n for levelno, code in colors.items():\n # Convert the terminal control characters from\n # bytes to unicode strings for easier use with the\n # logging module.\n self._colors[levelno] = unicode_type(\n curses.tparm(fg_color, code), \"ascii\"\n )\n self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n else:\n # If curses is not present (currently we'll only get here for\n # colorama on windows), assume hard-coded ANSI color codes.\n for levelno, code in colors.items():\n self._colors[levelno] = \"\\033[2;3%dm\" % code\n self._normal = \"\\033[0m\"\n else:\n self._normal = \"\"\n\n def format(self, record: Any) -> str:\n try:\n message = record.getMessage()\n assert isinstance(message, basestring_type) # guaranteed by logging\n # Encoding notes: The logging module prefers to work with character\n # strings, but only enforces that log messages are instances of\n # basestring. In python 2, non-ascii bytestrings will make\n # their way through the logging framework until they blow up with\n # an unhelpful decoding error (with this formatter it happens\n # when we attach the prefix, but there are other opportunities for\n # exceptions further along in the framework).\n #\n # If a byte string makes it this far, convert it to unicode to\n # ensure it will make it out to the logs. Use repr() as a fallback\n # to ensure that all byte strings can be converted successfully,\n # but don't do it by default so we don't add extra quotes to ascii\n # bytestrings. This is a bit of a hacky place to do this, but\n # it's worth it since the encoding errors that would otherwise\n # result are so useless (and tornado is fond of using utf8-encoded\n # byte strings wherever possible).\n record.message = _safe_unicode(message)\n except Exception as e:\n record.message = \"Bad message (%r): %r\" % (e, record.__dict__)\n\n record.asctime = self.formatTime(record, cast(str, self.datefmt))\n\n if record.levelno in self._colors:\n record.color = self._colors[record.levelno]\n record.end_color = self._normal\n else:\n record.color = record.end_color = \"\"\n\n formatted = self._fmt % record.__dict__\n\n if record.exc_info:\n if not record.exc_text:\n record.exc_text = self.formatException(record.exc_info)\n if record.exc_text:\n # exc_text contains multiple lines. We need to _safe_unicode\n # each line separately so that non-utf8 bytes don't cause\n # all the newlines to turn into '\\n'.\n lines = [formatted.rstrip()]\n lines.extend(_safe_unicode(ln) for ln in record.exc_text.split(\"\\n\"))\n formatted = \"\\n\".join(lines)\n return formatted.replace(\"\\n\", \"\\n \")", "has_branch": true, "total_branches": 2} {"prompt_id": 708, "project": "tornado", "module": "tornado.netutil", "class": "", "method": "bind_sockets", "focal_method_txt": "def bind_sockets(\n port: int,\n address: Optional[str] = None,\n family: socket.AddressFamily = socket.AF_UNSPEC,\n backlog: int = _DEFAULT_BACKLOG,\n flags: Optional[int] = None,\n reuse_port: bool = False,\n) -> List[socket.socket]:\n \"\"\"Creates listening sockets bound to the given port and address.\n\n Returns a list of socket objects (multiple sockets are returned if\n the given address maps to multiple IP addresses, which is most common\n for mixed IPv4 and IPv6 use).\n\n Address may be either an IP address or hostname. If it's a hostname,\n the server will listen on all IP addresses associated with the\n name. Address may be an empty string or None to listen on all\n available interfaces. Family may be set to either `socket.AF_INET`\n or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n both will be used if available.\n\n The ``backlog`` argument has the same meaning as for\n `socket.listen() `.\n\n ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like\n ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.\n\n ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket\n in the list. If your platform doesn't support this option ValueError will\n be raised.\n \"\"\"\n if reuse_port and not hasattr(socket, \"SO_REUSEPORT\"):\n raise ValueError(\"the platform doesn't support SO_REUSEPORT\")\n\n sockets = []\n if address == \"\":\n address = None\n if not socket.has_ipv6 and family == socket.AF_UNSPEC:\n # Python can be compiled with --disable-ipv6, which causes\n # operations on AF_INET6 sockets to fail, but does not\n # automatically exclude those results from getaddrinfo\n # results.\n # http://bugs.python.org/issue16208\n family = socket.AF_INET\n if flags is None:\n flags = socket.AI_PASSIVE\n bound_port = None\n unique_addresses = set() # type: set\n for res in sorted(\n socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),\n key=lambda x: x[0],\n ):\n if res in unique_addresses:\n continue\n\n unique_addresses.add(res)\n\n af, socktype, proto, canonname, sockaddr = res\n if (\n sys.platform == \"darwin\"\n and address == \"localhost\"\n and af == socket.AF_INET6\n and sockaddr[3] != 0\n ):\n # Mac OS X includes a link-local address fe80::1%lo0 in the\n # getaddrinfo results for 'localhost'. However, the firewall\n # doesn't understand that this is a local address and will\n # prompt for access (often repeatedly, due to an apparent\n # bug in its ability to remember granting access to an\n # application). Skip these addresses.\n continue\n try:\n sock = socket.socket(af, socktype, proto)\n except socket.error as e:\n if errno_from_exception(e) == errno.EAFNOSUPPORT:\n continue\n raise\n if os.name != \"nt\":\n try:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n except socket.error as e:\n if errno_from_exception(e) != errno.ENOPROTOOPT:\n # Hurd doesn't support SO_REUSEADDR.\n raise\n if reuse_port:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n if af == socket.AF_INET6:\n # On linux, ipv6 sockets accept ipv4 too by default,\n # but this makes it impossible to bind to both\n # 0.0.0.0 in ipv4 and :: in ipv6. On other systems,\n # separate sockets *must* be used to listen for both ipv4\n # and ipv6. For consistency, always disable ipv4 on our\n # ipv6 sockets and use a separate ipv4 socket when needed.\n #\n # Python 2.x on windows doesn't have IPPROTO_IPV6.\n if hasattr(socket, \"IPPROTO_IPV6\"):\n sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)\n\n # automatic port allocation with port=None\n # should bind on the same port on IPv4 and IPv6\n host, requested_port = sockaddr[:2]\n if requested_port == 0 and bound_port is not None:\n sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))\n\n sock.setblocking(False)\n try:\n sock.bind(sockaddr)\n except OSError as e:\n if (\n errno_from_exception(e) == errno.EADDRNOTAVAIL\n and address == \"localhost\"\n and sockaddr[0] == \"::1\"\n ):\n # On some systems (most notably docker with default\n # configurations), ipv6 is partially disabled:\n # socket.has_ipv6 is true, we can create AF_INET6\n # sockets, and getaddrinfo(\"localhost\", ...,\n # AF_PASSIVE) resolves to ::1, but we get an error\n # when binding.\n #\n # Swallow the error, but only for this specific case.\n # If EADDRNOTAVAIL occurs in other situations, it\n # might be a real problem like a typo in a\n # configuration.\n sock.close()\n continue\n else:\n raise\n bound_port = sock.getsockname()[1]\n sock.listen(backlog)\n sockets.append(sock)\n return sockets", "focal_method_lines": [54, 185], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\ndef bind_sockets(\n port: int,\n address: Optional[str] = None,\n family: socket.AddressFamily = socket.AF_UNSPEC,\n backlog: int = _DEFAULT_BACKLOG,\n flags: Optional[int] = None,\n reuse_port: bool = False,\n) -> List[socket.socket]:\n \"\"\"Creates listening sockets bound to the given port and address.\n\n Returns a list of socket objects (multiple sockets are returned if\n the given address maps to multiple IP addresses, which is most common\n for mixed IPv4 and IPv6 use).\n\n Address may be either an IP address or hostname. If it's a hostname,\n the server will listen on all IP addresses associated with the\n name. Address may be an empty string or None to listen on all\n available interfaces. Family may be set to either `socket.AF_INET`\n or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n both will be used if available.\n\n The ``backlog`` argument has the same meaning as for\n `socket.listen() `.\n\n ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like\n ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.\n\n ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket\n in the list. If your platform doesn't support this option ValueError will\n be raised.\n \"\"\"\n if reuse_port and not hasattr(socket, \"SO_REUSEPORT\"):\n raise ValueError(\"the platform doesn't support SO_REUSEPORT\")\n\n sockets = []\n if address == \"\":\n address = None\n if not socket.has_ipv6 and family == socket.AF_UNSPEC:\n # Python can be compiled with --disable-ipv6, which causes\n # operations on AF_INET6 sockets to fail, but does not\n # automatically exclude those results from getaddrinfo\n # results.\n # http://bugs.python.org/issue16208\n family = socket.AF_INET\n if flags is None:\n flags = socket.AI_PASSIVE\n bound_port = None\n unique_addresses = set() # type: set\n for res in sorted(\n socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),\n key=lambda x: x[0],\n ):\n if res in unique_addresses:\n continue\n\n unique_addresses.add(res)\n\n af, socktype, proto, canonname, sockaddr = res\n if (\n sys.platform == \"darwin\"\n and address == \"localhost\"\n and af == socket.AF_INET6\n and sockaddr[3] != 0\n ):\n # Mac OS X includes a link-local address fe80::1%lo0 in the\n # getaddrinfo results for 'localhost'. However, the firewall\n # doesn't understand that this is a local address and will\n # prompt for access (often repeatedly, due to an apparent\n # bug in its ability to remember granting access to an\n # application). Skip these addresses.\n continue\n try:\n sock = socket.socket(af, socktype, proto)\n except socket.error as e:\n if errno_from_exception(e) == errno.EAFNOSUPPORT:\n continue\n raise\n if os.name != \"nt\":\n try:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n except socket.error as e:\n if errno_from_exception(e) != errno.ENOPROTOOPT:\n # Hurd doesn't support SO_REUSEADDR.\n raise\n if reuse_port:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n if af == socket.AF_INET6:\n # On linux, ipv6 sockets accept ipv4 too by default,\n # but this makes it impossible to bind to both\n # 0.0.0.0 in ipv4 and :: in ipv6. On other systems,\n # separate sockets *must* be used to listen for both ipv4\n # and ipv6. For consistency, always disable ipv4 on our\n # ipv6 sockets and use a separate ipv4 socket when needed.\n #\n # Python 2.x on windows doesn't have IPPROTO_IPV6.\n if hasattr(socket, \"IPPROTO_IPV6\"):\n sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)\n\n # automatic port allocation with port=None\n # should bind on the same port on IPv4 and IPv6\n host, requested_port = sockaddr[:2]\n if requested_port == 0 and bound_port is not None:\n sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))\n\n sock.setblocking(False)\n try:\n sock.bind(sockaddr)\n except OSError as e:\n if (\n errno_from_exception(e) == errno.EADDRNOTAVAIL\n and address == \"localhost\"\n and sockaddr[0] == \"::1\"\n ):\n # On some systems (most notably docker with default\n # configurations), ipv6 is partially disabled:\n # socket.has_ipv6 is true, we can create AF_INET6\n # sockets, and getaddrinfo(\"localhost\", ...,\n # AF_PASSIVE) resolves to ::1, but we get an error\n # when binding.\n #\n # Swallow the error, but only for this specific case.\n # If EADDRNOTAVAIL occurs in other situations, it\n # might be a real problem like a typo in a\n # configuration.\n sock.close()\n continue\n else:\n raise\n bound_port = sock.getsockname()[1]\n sock.listen(backlog)\n sockets.append(sock)\n return sockets", "has_branch": true, "total_branches": 2} {"prompt_id": 709, "project": "tornado", "module": "tornado.netutil", "class": "", "method": "add_accept_handler", "focal_method_txt": "def add_accept_handler(\n sock: socket.socket, callback: Callable[[socket.socket, Any], None]\n) -> Callable[[], None]:\n \"\"\"Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n When a connection is accepted, ``callback(connection, address)`` will\n be run (``connection`` is a socket object, and ``address`` is the\n address of the other end of the connection). Note that this signature\n is different from the ``callback(fd, events)`` signature used for\n `.IOLoop` handlers.\n\n A callable is returned which, when called, will remove the `.IOLoop`\n event handler and stop processing further incoming connections.\n\n .. versionchanged:: 5.0\n The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n .. versionchanged:: 5.0\n A callable is returned (``None`` was returned before).\n \"\"\"\n io_loop = IOLoop.current()\n removed = [False]\n\n def accept_handler(fd: socket.socket, events: int) -> None:\n # More connections may come in while we're handling callbacks;\n # to prevent starvation of other tasks we must limit the number\n # of connections we accept at a time. Ideally we would accept\n # up to the number of connections that were waiting when we\n # entered this method, but this information is not available\n # (and rearranging this method to call accept() as many times\n # as possible before running any callbacks would have adverse\n # effects on load balancing in multiprocess configurations).\n # Instead, we use the (default) listen backlog as a rough\n # heuristic for the number of connections we can reasonably\n # accept at once.\n for i in range(_DEFAULT_BACKLOG):\n if removed[0]:\n # The socket was probably closed\n return\n try:\n connection, address = sock.accept()\n except BlockingIOError:\n # EWOULDBLOCK indicates we have accepted every\n # connection that is available.\n return\n except ConnectionAbortedError:\n # ECONNABORTED indicates that there was a connection\n # but it was closed while still in the accept queue.\n # (observed on FreeBSD).\n continue\n callback(connection, address)\n\n def remove_handler() -> None:\n io_loop.remove_handler(sock)\n removed[0] = True\n\n io_loop.add_handler(sock, accept_handler, IOLoop.READ)\n return remove_handler", "focal_method_lines": [225, 282], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\ndef add_accept_handler(\n sock: socket.socket, callback: Callable[[socket.socket, Any], None]\n) -> Callable[[], None]:\n \"\"\"Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n When a connection is accepted, ``callback(connection, address)`` will\n be run (``connection`` is a socket object, and ``address`` is the\n address of the other end of the connection). Note that this signature\n is different from the ``callback(fd, events)`` signature used for\n `.IOLoop` handlers.\n\n A callable is returned which, when called, will remove the `.IOLoop`\n event handler and stop processing further incoming connections.\n\n .. versionchanged:: 5.0\n The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n .. versionchanged:: 5.0\n A callable is returned (``None`` was returned before).\n \"\"\"\n io_loop = IOLoop.current()\n removed = [False]\n\n def accept_handler(fd: socket.socket, events: int) -> None:\n # More connections may come in while we're handling callbacks;\n # to prevent starvation of other tasks we must limit the number\n # of connections we accept at a time. Ideally we would accept\n # up to the number of connections that were waiting when we\n # entered this method, but this information is not available\n # (and rearranging this method to call accept() as many times\n # as possible before running any callbacks would have adverse\n # effects on load balancing in multiprocess configurations).\n # Instead, we use the (default) listen backlog as a rough\n # heuristic for the number of connections we can reasonably\n # accept at once.\n for i in range(_DEFAULT_BACKLOG):\n if removed[0]:\n # The socket was probably closed\n return\n try:\n connection, address = sock.accept()\n except BlockingIOError:\n # EWOULDBLOCK indicates we have accepted every\n # connection that is available.\n return\n except ConnectionAbortedError:\n # ECONNABORTED indicates that there was a connection\n # but it was closed while still in the accept queue.\n # (observed on FreeBSD).\n continue\n callback(connection, address)\n\n def remove_handler() -> None:\n io_loop.remove_handler(sock)\n removed[0] = True\n\n io_loop.add_handler(sock, accept_handler, IOLoop.READ)\n return remove_handler", "has_branch": true, "total_branches": 2} {"prompt_id": 710, "project": "tornado", "module": "tornado.netutil", "class": "", "method": "is_valid_ip", "focal_method_txt": "def is_valid_ip(ip: str) -> bool:\n \"\"\"Returns ``True`` if the given string is a well-formed IP address.\n\n Supports IPv4 and IPv6.\n \"\"\"\n if not ip or \"\\x00\" in ip:\n # getaddrinfo resolves empty strings to localhost, and truncates\n # on zero bytes.\n return False\n try:\n res = socket.getaddrinfo(\n ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n )\n return bool(res)\n except socket.gaierror as e:\n if e.args[0] == socket.EAI_NONAME:\n return False\n raise\n return True", "focal_method_lines": [285, 303], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\ndef is_valid_ip(ip: str) -> bool:\n \"\"\"Returns ``True`` if the given string is a well-formed IP address.\n\n Supports IPv4 and IPv6.\n \"\"\"\n if not ip or \"\\x00\" in ip:\n # getaddrinfo resolves empty strings to localhost, and truncates\n # on zero bytes.\n return False\n try:\n res = socket.getaddrinfo(\n ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n )\n return bool(res)\n except socket.gaierror as e:\n if e.args[0] == socket.EAI_NONAME:\n return False\n raise\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 711, "project": "tornado", "module": "tornado.netutil", "class": "", "method": "ssl_options_to_context", "focal_method_txt": "def ssl_options_to_context(\n ssl_options: Union[Dict[str, Any], ssl.SSLContext]\n) -> ssl.SSLContext:\n \"\"\"Try to convert an ``ssl_options`` dictionary to an\n `~ssl.SSLContext` object.\n\n The ``ssl_options`` dictionary contains keywords to be passed to\n `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can\n be used instead. This function converts the dict form to its\n `~ssl.SSLContext` equivalent, and may be used when a component which\n accepts both forms needs to upgrade to the `~ssl.SSLContext` version\n to use features like SNI or NPN.\n \"\"\"\n if isinstance(ssl_options, ssl.SSLContext):\n return ssl_options\n assert isinstance(ssl_options, dict)\n assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options\n # Can't use create_default_context since this interface doesn't\n # tell us client vs server.\n context = ssl.SSLContext(ssl_options.get(\"ssl_version\", ssl.PROTOCOL_SSLv23))\n if \"certfile\" in ssl_options:\n context.load_cert_chain(\n ssl_options[\"certfile\"], ssl_options.get(\"keyfile\", None)\n )\n if \"cert_reqs\" in ssl_options:\n context.verify_mode = ssl_options[\"cert_reqs\"]\n if \"ca_certs\" in ssl_options:\n context.load_verify_locations(ssl_options[\"ca_certs\"])\n if \"ciphers\" in ssl_options:\n context.set_ciphers(ssl_options[\"ciphers\"])\n if hasattr(ssl, \"OP_NO_COMPRESSION\"):\n # Disable TLS compression to avoid CRIME and related attacks.\n # This constant depends on openssl version 1.0.\n # TODO: Do we need to do this ourselves or can we trust\n # the defaults?\n context.options |= ssl.OP_NO_COMPRESSION\n return context", "focal_method_lines": [554, 590], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\ndef ssl_options_to_context(\n ssl_options: Union[Dict[str, Any], ssl.SSLContext]\n) -> ssl.SSLContext:\n \"\"\"Try to convert an ``ssl_options`` dictionary to an\n `~ssl.SSLContext` object.\n\n The ``ssl_options`` dictionary contains keywords to be passed to\n `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can\n be used instead. This function converts the dict form to its\n `~ssl.SSLContext` equivalent, and may be used when a component which\n accepts both forms needs to upgrade to the `~ssl.SSLContext` version\n to use features like SNI or NPN.\n \"\"\"\n if isinstance(ssl_options, ssl.SSLContext):\n return ssl_options\n assert isinstance(ssl_options, dict)\n assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options\n # Can't use create_default_context since this interface doesn't\n # tell us client vs server.\n context = ssl.SSLContext(ssl_options.get(\"ssl_version\", ssl.PROTOCOL_SSLv23))\n if \"certfile\" in ssl_options:\n context.load_cert_chain(\n ssl_options[\"certfile\"], ssl_options.get(\"keyfile\", None)\n )\n if \"cert_reqs\" in ssl_options:\n context.verify_mode = ssl_options[\"cert_reqs\"]\n if \"ca_certs\" in ssl_options:\n context.load_verify_locations(ssl_options[\"ca_certs\"])\n if \"ciphers\" in ssl_options:\n context.set_ciphers(ssl_options[\"ciphers\"])\n if hasattr(ssl, \"OP_NO_COMPRESSION\"):\n # Disable TLS compression to avoid CRIME and related attacks.\n # This constant depends on openssl version 1.0.\n # TODO: Do we need to do this ourselves or can we trust\n # the defaults?\n context.options |= ssl.OP_NO_COMPRESSION\n return context", "has_branch": true, "total_branches": 2} {"prompt_id": 712, "project": "tornado", "module": "tornado.netutil", "class": "", "method": "ssl_wrap_socket", "focal_method_txt": "def ssl_wrap_socket(\n socket: socket.socket,\n ssl_options: Union[Dict[str, Any], ssl.SSLContext],\n server_hostname: Optional[str] = None,\n **kwargs: Any\n) -> ssl.SSLSocket:\n \"\"\"Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n ``ssl_options`` may be either an `ssl.SSLContext` object or a\n dictionary (as accepted by `ssl_options_to_context`). Additional\n keyword arguments are passed to ``wrap_socket`` (either the\n `~ssl.SSLContext` method or the `ssl` module function as\n appropriate).\n \"\"\"\n context = ssl_options_to_context(ssl_options)\n if ssl.HAS_SNI:\n # In python 3.4, wrap_socket only accepts the server_hostname\n # argument if HAS_SNI is true.\n # TODO: add a unittest (python added server-side SNI support in 3.4)\n # In the meantime it can be manually tested with\n # python3 -m tornado.httpclient https://sni.velox.ch\n return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs)\n else:\n return context.wrap_socket(socket, **kwargs)", "focal_method_lines": [593, 616], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\ndef ssl_wrap_socket(\n socket: socket.socket,\n ssl_options: Union[Dict[str, Any], ssl.SSLContext],\n server_hostname: Optional[str] = None,\n **kwargs: Any\n) -> ssl.SSLSocket:\n \"\"\"Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n ``ssl_options`` may be either an `ssl.SSLContext` object or a\n dictionary (as accepted by `ssl_options_to_context`). Additional\n keyword arguments are passed to ``wrap_socket`` (either the\n `~ssl.SSLContext` method or the `ssl` module function as\n appropriate).\n \"\"\"\n context = ssl_options_to_context(ssl_options)\n if ssl.HAS_SNI:\n # In python 3.4, wrap_socket only accepts the server_hostname\n # argument if HAS_SNI is true.\n # TODO: add a unittest (python added server-side SNI support in 3.4)\n # In the meantime it can be manually tested with\n # python3 -m tornado.httpclient https://sni.velox.ch\n return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs)\n else:\n return context.wrap_socket(socket, **kwargs)", "has_branch": true, "total_branches": 2} {"prompt_id": 713, "project": "tornado", "module": "tornado.netutil", "class": "Resolver", "method": "resolve", "focal_method_txt": " def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> Awaitable[List[Tuple[int, Any]]]:\n \"\"\"Resolves an address.\n\n The ``host`` argument is a string which may be a hostname or a\n literal IP address.\n\n Returns a `.Future` whose result is a list of (family,\n address) pairs, where address is a tuple suitable to pass to\n `socket.connect ` (i.e. a ``(host,\n port)`` pair for IPv4; additional fields may be present for\n IPv6). If a ``callback`` is passed, it will be run with the\n result as an argument when it is complete.\n\n :raises IOError: if the address cannot be resolved.\n\n .. versionchanged:: 4.4\n Standardized all implementations to raise `IOError`.\n\n .. versionchanged:: 6.0 The ``callback`` argument was removed.\n Use the returned awaitable object instead.\n\n \"\"\"\n raise NotImplementedError()", "focal_method_lines": [338, 362], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass Resolver(Configurable):\n\n def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> Awaitable[List[Tuple[int, Any]]]:\n \"\"\"Resolves an address.\n\n The ``host`` argument is a string which may be a hostname or a\n literal IP address.\n\n Returns a `.Future` whose result is a list of (family,\n address) pairs, where address is a tuple suitable to pass to\n `socket.connect ` (i.e. a ``(host,\n port)`` pair for IPv4; additional fields may be present for\n IPv6). If a ``callback`` is passed, it will be run with the\n result as an argument when it is complete.\n\n :raises IOError: if the address cannot be resolved.\n\n .. versionchanged:: 4.4\n Standardized all implementations to raise `IOError`.\n\n .. versionchanged:: 6.0 The ``callback`` argument was removed.\n Use the returned awaitable object instead.\n\n \"\"\"\n raise NotImplementedError()", "has_branch": false, "total_branches": 0} {"prompt_id": 714, "project": "tornado", "module": "tornado.netutil", "class": "DefaultExecutorResolver", "method": "resolve", "focal_method_txt": " async def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> List[Tuple[int, Any]]:\n result = await IOLoop.current().run_in_executor(\n None, _resolve_addr, host, port, family\n )\n return result", "focal_method_lines": [394, 400], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass DefaultExecutorResolver(Resolver):\n\n async def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> List[Tuple[int, Any]]:\n result = await IOLoop.current().run_in_executor(\n None, _resolve_addr, host, port, family\n )\n return result", "has_branch": false, "total_branches": 0} {"prompt_id": 715, "project": "tornado", "module": "tornado.netutil", "class": "ExecutorResolver", "method": "initialize", "focal_method_txt": " def initialize(\n self,\n executor: Optional[concurrent.futures.Executor] = None,\n close_executor: bool = True,\n ) -> None:\n self.io_loop = IOLoop.current()\n if executor is not None:\n self.executor = executor\n self.close_executor = close_executor\n else:\n self.executor = dummy_executor\n self.close_executor = False", "focal_method_lines": [421, 432], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass ExecutorResolver(Resolver):\n\n def initialize(\n self,\n executor: Optional[concurrent.futures.Executor] = None,\n close_executor: bool = True,\n ) -> None:\n self.io_loop = IOLoop.current()\n if executor is not None:\n self.executor = executor\n self.close_executor = close_executor\n else:\n self.executor = dummy_executor\n self.close_executor = False", "has_branch": true, "total_branches": 2} {"prompt_id": 716, "project": "tornado", "module": "tornado.netutil", "class": "ExecutorResolver", "method": "close", "focal_method_txt": " def close(self) -> None:\n if self.close_executor:\n self.executor.shutdown()\n self.executor = None", "focal_method_lines": [434, 437], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass ExecutorResolver(Resolver):\n\n def close(self) -> None:\n if self.close_executor:\n self.executor.shutdown()\n self.executor = None", "has_branch": true, "total_branches": 2} {"prompt_id": 717, "project": "tornado", "module": "tornado.netutil", "class": "ExecutorResolver", "method": "resolve", "focal_method_txt": " @run_on_executor\n def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> List[Tuple[int, Any]]:\n return _resolve_addr(host, port, family)", "focal_method_lines": [440, 443], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass ExecutorResolver(Resolver):\n\n @run_on_executor\n def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> List[Tuple[int, Any]]:\n return _resolve_addr(host, port, family)", "has_branch": false, "total_branches": 0} {"prompt_id": 718, "project": "tornado", "module": "tornado.netutil", "class": "OverrideResolver", "method": "initialize", "focal_method_txt": " def initialize(self, resolver: Resolver, mapping: dict) -> None:\n self.resolver = resolver\n self.mapping = mapping", "focal_method_lines": [527, 529], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass OverrideResolver(Resolver):\n\n def initialize(self, resolver: Resolver, mapping: dict) -> None:\n self.resolver = resolver\n self.mapping = mapping", "has_branch": false, "total_branches": 0} {"prompt_id": 719, "project": "tornado", "module": "tornado.netutil", "class": "OverrideResolver", "method": "close", "focal_method_txt": " def close(self) -> None:\n self.resolver.close()", "focal_method_lines": [531, 532], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass OverrideResolver(Resolver):\n\n def close(self) -> None:\n self.resolver.close()", "has_branch": false, "total_branches": 0} {"prompt_id": 720, "project": "tornado", "module": "tornado.netutil", "class": "OverrideResolver", "method": "resolve", "focal_method_txt": " def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> Awaitable[List[Tuple[int, Any]]]:\n if (host, port, family) in self.mapping:\n host, port = self.mapping[(host, port, family)]\n elif (host, port) in self.mapping:\n host, port = self.mapping[(host, port)]\n elif host in self.mapping:\n host = self.mapping[host]\n return self.resolver.resolve(host, port, family)", "focal_method_lines": [534, 543], "in_stack": false, "globals": ["_client_ssl_defaults", "_server_ssl_defaults", "_DEFAULT_BACKLOG", "_SSL_CONTEXT_KEYWORDS"], "type_context": "import concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n_DEFAULT_BACKLOG = 128\n_SSL_CONTEXT_KEYWORDS = frozenset(\n [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\nclass OverrideResolver(Resolver):\n\n def resolve(\n self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n ) -> Awaitable[List[Tuple[int, Any]]]:\n if (host, port, family) in self.mapping:\n host, port = self.mapping[(host, port, family)]\n elif (host, port) in self.mapping:\n host, port = self.mapping[(host, port)]\n elif host in self.mapping:\n host = self.mapping[host]\n return self.resolver.resolve(host, port, family)", "has_branch": true, "total_branches": 2} {"prompt_id": 721, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "__setattr__", "focal_method_txt": " def __setattr__(self, name: str, value: Any) -> None:\n name = self._normalize_name(name)\n if isinstance(self._options.get(name), _Option):\n return self._options[name].set(value)\n raise AttributeError(\"Unrecognized option %r\" % name)", "focal_method_lines": [153, 157], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def __setattr__(self, name: str, value: Any) -> None:\n name = self._normalize_name(name)\n if isinstance(self._options.get(name), _Option):\n return self._options[name].set(value)\n raise AttributeError(\"Unrecognized option %r\" % name)", "has_branch": true, "total_branches": 2} {"prompt_id": 722, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> Iterator:\n return (opt.name for opt in self._options.values())", "focal_method_lines": [159, 160], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def __iter__(self) -> Iterator:\n return (opt.name for opt in self._options.values())", "has_branch": false, "total_branches": 0} {"prompt_id": 723, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "group_dict", "focal_method_txt": " def group_dict(self, group: str) -> Dict[str, Any]:\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 .. versionadded:: 3.1\n \"\"\"\n return dict(\n (opt.name, opt.value())\n for name, opt in self._options.items()\n if not group or group == opt.group_name\n )", "focal_method_lines": [186, 203], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def group_dict(self, group: str) -> Dict[str, Any]:\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 .. versionadded:: 3.1\n \"\"\"\n return dict(\n (opt.name, opt.value())\n for name, opt in self._options.items()\n if not group or group == opt.group_name\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 724, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "define", "focal_method_txt": " def define(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n group: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n \"\"\"Defines a new command line option.\n\n ``type`` can be any of `str`, `int`, `float`, `bool`,\n `~datetime.datetime`, or `~datetime.timedelta`. If no ``type``\n is given but a ``default`` is, ``type`` is the type of\n ``default``. Otherwise, ``type`` defaults to `str`.\n\n If ``multiple`` is True, the option value is a list of ``type``\n instead of an instance of ``type``.\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.\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 \"\"\"\n normalized = self._normalize_name(name)\n if normalized in self._options:\n raise Error(\n \"Option %r already defined in %s\"\n % (normalized, self._options[normalized].file_name)\n )\n frame = sys._getframe(0)\n options_file = frame.f_code.co_filename\n\n # Can be called directly, or through top level define() fn, in which\n # case, step up above that frame to look for real caller.\n if (\n frame.f_back.f_code.co_filename == options_file\n and frame.f_back.f_code.co_name == \"define\"\n ):\n frame = frame.f_back\n\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 # type: Optional[str]\n else:\n group_name = file_name\n option = _Option(\n name,\n file_name=file_name,\n default=default,\n type=type,\n help=help,\n metavar=metavar,\n multiple=multiple,\n group_name=group_name,\n callback=callback,\n )\n self._options[normalized] = option", "focal_method_lines": [216, 301], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def define(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n group: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n \"\"\"Defines a new command line option.\n\n ``type`` can be any of `str`, `int`, `float`, `bool`,\n `~datetime.datetime`, or `~datetime.timedelta`. If no ``type``\n is given but a ``default`` is, ``type`` is the type of\n ``default``. Otherwise, ``type`` defaults to `str`.\n\n If ``multiple`` is True, the option value is a list of ``type``\n instead of an instance of ``type``.\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.\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 \"\"\"\n normalized = self._normalize_name(name)\n if normalized in self._options:\n raise Error(\n \"Option %r already defined in %s\"\n % (normalized, self._options[normalized].file_name)\n )\n frame = sys._getframe(0)\n options_file = frame.f_code.co_filename\n\n # Can be called directly, or through top level define() fn, in which\n # case, step up above that frame to look for real caller.\n if (\n frame.f_back.f_code.co_filename == options_file\n and frame.f_back.f_code.co_name == \"define\"\n ):\n frame = frame.f_back\n\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 # type: Optional[str]\n else:\n group_name = file_name\n option = _Option(\n name,\n file_name=file_name,\n default=default,\n type=type,\n help=help,\n metavar=metavar,\n multiple=multiple,\n group_name=group_name,\n callback=callback,\n )\n self._options[normalized] = option", "has_branch": true, "total_branches": 2} {"prompt_id": 725, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "parse_command_line", "focal_method_txt": " def parse_command_line(\n self, args: Optional[List[str]] = None, final: bool = True\n ) -> List[str]:\n \"\"\"Parses all options given on the command line (defaults to\n `sys.argv`).\n\n Options look like ``--option=value`` and are parsed according\n to their ``type``. For boolean options, ``--option`` is\n equivalent to ``--option=true``\n\n If the option has ``multiple=True``, comma-separated values\n are accepted. For multi-value integer options, the syntax\n ``x:y`` is also accepted and equivalent to ``range(x, y)``.\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 \"\"\"\n if args is None:\n args = sys.argv\n remaining = [] # type: List[str]\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 = self._normalize_name(name)\n if name not 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", "focal_method_lines": [303, 355], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def parse_command_line(\n self, args: Optional[List[str]] = None, final: bool = True\n ) -> List[str]:\n \"\"\"Parses all options given on the command line (defaults to\n `sys.argv`).\n\n Options look like ``--option=value`` and are parsed according\n to their ``type``. For boolean options, ``--option`` is\n equivalent to ``--option=true``\n\n If the option has ``multiple=True``, comma-separated values\n are accepted. For multi-value integer options, the syntax\n ``x:y`` is also accepted and equivalent to ``range(x, y)``.\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 \"\"\"\n if args is None:\n args = sys.argv\n remaining = [] # type: List[str]\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 = self._normalize_name(name)\n if name not 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", "has_branch": true, "total_branches": 2} {"prompt_id": 726, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "parse_config_file", "focal_method_txt": " def parse_config_file(self, path: str, final: bool = True) -> None:\n \"\"\"Parses and loads the config file at the given path.\n\n The config file contains Python code that will be executed (so\n it is **not safe** to use untrusted config files). Anything in\n the global namespace that matches a defined option will be\n used to set that option's value.\n\n Options may either be the specified type for the option or\n strings (in which case they will be parsed the same way as in\n `.parse_command_line`)\n\n Example (using the options defined in the top-level docs of\n this module)::\n\n port = 80\n mysql_host = 'mydb.example.com:3306'\n # Both lists and comma-separated strings are allowed for\n # multiple=True.\n memcache_hosts = ['cache1.example.com:11011',\n 'cache2.example.com:11011']\n memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'\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 .. note::\n\n `tornado.options` is primarily a command-line library.\n Config file support is provided for applications that wish\n to use it, but applications that prefer config files may\n wish to look at other libraries instead.\n\n .. versionchanged:: 4.1\n Config files are now always interpreted as utf-8 instead of\n the system default encoding.\n\n .. versionchanged:: 4.4\n The special variable ``__file__`` is available inside config\n files, specifying the absolute path to the config file itself.\n\n .. versionchanged:: 5.1\n Added the ability to set options via strings in config files.\n\n \"\"\"\n config = {\"__file__\": os.path.abspath(path)}\n with open(path, \"rb\") as f:\n exec_in(native_str(f.read()), config, config)\n for name in config:\n normalized = self._normalize_name(name)\n if normalized in self._options:\n option = self._options[normalized]\n if option.multiple:\n if not isinstance(config[name], (list, str)):\n raise Error(\n \"Option %r is required to be a list of %s \"\n \"or a comma-separated string\"\n % (option.name, option.type.__name__)\n )\n\n if type(config[name]) == str and option.type != str:\n option.parse(config[name])\n else:\n option.set(config[name])\n\n if final:\n self.run_parse_callbacks()", "focal_method_lines": [357, 424], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def parse_config_file(self, path: str, final: bool = True) -> None:\n \"\"\"Parses and loads the config file at the given path.\n\n The config file contains Python code that will be executed (so\n it is **not safe** to use untrusted config files). Anything in\n the global namespace that matches a defined option will be\n used to set that option's value.\n\n Options may either be the specified type for the option or\n strings (in which case they will be parsed the same way as in\n `.parse_command_line`)\n\n Example (using the options defined in the top-level docs of\n this module)::\n\n port = 80\n mysql_host = 'mydb.example.com:3306'\n # Both lists and comma-separated strings are allowed for\n # multiple=True.\n memcache_hosts = ['cache1.example.com:11011',\n 'cache2.example.com:11011']\n memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'\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 .. note::\n\n `tornado.options` is primarily a command-line library.\n Config file support is provided for applications that wish\n to use it, but applications that prefer config files may\n wish to look at other libraries instead.\n\n .. versionchanged:: 4.1\n Config files are now always interpreted as utf-8 instead of\n the system default encoding.\n\n .. versionchanged:: 4.4\n The special variable ``__file__`` is available inside config\n files, specifying the absolute path to the config file itself.\n\n .. versionchanged:: 5.1\n Added the ability to set options via strings in config files.\n\n \"\"\"\n config = {\"__file__\": os.path.abspath(path)}\n with open(path, \"rb\") as f:\n exec_in(native_str(f.read()), config, config)\n for name in config:\n normalized = self._normalize_name(name)\n if normalized in self._options:\n option = self._options[normalized]\n if option.multiple:\n if not isinstance(config[name], (list, str)):\n raise Error(\n \"Option %r is required to be a list of %s \"\n \"or a comma-separated string\"\n % (option.name, option.type.__name__)\n )\n\n if type(config[name]) == str and option.type != str:\n option.parse(config[name])\n else:\n option.set(config[name])\n\n if final:\n self.run_parse_callbacks()", "has_branch": true, "total_branches": 2} {"prompt_id": 727, "project": "tornado", "module": "tornado.options", "class": "OptionParser", "method": "print_help", "focal_method_txt": " def print_help(self, file: Optional[TextIO] = None) -> 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 = {} # type: Dict[str, List[_Option]]\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 # Always print names with dashes in a CLI context.\n prefix = self._normalize_name(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)", "focal_method_lines": [426, 454], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\nclass OptionParser(object):\n\n def __init__(self) -> None:\n # we have to use self.__dict__ because we override setattr.\n self.__dict__[\"_options\"] = {}\n self.__dict__[\"_parse_callbacks\"] = []\n self.define(\n \"help\",\n type=bool,\n help=\"show this help information\",\n callback=self._help_callback,\n )\n\n def print_help(self, file: Optional[TextIO] = None) -> 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 = {} # type: Dict[str, List[_Option]]\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 # Always print names with dashes in a CLI context.\n prefix = self._normalize_name(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)", "has_branch": true, "total_branches": 2} {"prompt_id": 728, "project": "tornado", "module": "tornado.options", "class": "_Mockable", "method": "__setattr__", "focal_method_txt": " def __setattr__(self, name: str, value: Any) -> None:\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)", "focal_method_lines": [508, 511], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Mockable(object):\n\n def __init__(self, options: OptionParser) -> None:\n # Modify __dict__ directly to bypass __setattr__\n self.__dict__[\"_options\"] = options\n self.__dict__[\"_originals\"] = {}\n\n def __setattr__(self, name: str, value: Any) -> None:\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)", "has_branch": false, "total_branches": 0} {"prompt_id": 729, "project": "tornado", "module": "tornado.options", "class": "_Option", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET", "focal_method_lines": [523, 548], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET", "has_branch": true, "total_branches": 2} {"prompt_id": 730, "project": "tornado", "module": "tornado.options", "class": "_Option", "method": "value", "focal_method_txt": " def value(self) -> Any:\n return self.default if self._value is _Option.UNSET else self._value", "focal_method_lines": [550, 551], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\n def value(self) -> Any:\n return self.default if self._value is _Option.UNSET else self._value", "has_branch": false, "total_branches": 0} {"prompt_id": 731, "project": "tornado", "module": "tornado.options", "class": "_Option", "method": "parse", "focal_method_txt": " def parse(self, value: str) -> Any:\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(\n self.type, self.type\n ) # type: Callable[[str], Any]\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_str, _, hi_str = part.partition(\":\")\n lo = _parse(lo_str)\n hi = _parse(hi_str) if hi_str 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()", "focal_method_lines": [553, 577], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\n def parse(self, value: str) -> Any:\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(\n self.type, self.type\n ) # type: Callable[[str], Any]\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_str, _, hi_str = part.partition(\":\")\n lo = _parse(lo_str)\n hi = _parse(hi_str) if hi_str 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()", "has_branch": true, "total_branches": 2} {"prompt_id": 732, "project": "tornado", "module": "tornado.options", "class": "_Option", "method": "set", "focal_method_txt": " def set(self, value: Any) -> None:\n if self.multiple:\n if not isinstance(value, list):\n raise Error(\n \"Option %r is required to be a list of %s\"\n % (self.name, self.type.__name__)\n )\n for item in value:\n if item is not None and not isinstance(item, self.type):\n raise Error(\n \"Option %r is required to be a list of %s\"\n % (self.name, self.type.__name__)\n )\n else:\n if value is not None and not isinstance(value, self.type):\n raise Error(\n \"Option %r is required to be a %s (%s given)\"\n % (self.name, self.type.__name__, type(value))\n )\n self._value = value\n if self.callback is not None:\n self.callback(self._value)", "focal_method_lines": [579, 600], "in_stack": false, "globals": ["options"], "type_context": "import datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\nfrom tornado.escape import _unicode, native_str\nfrom tornado.log import define_logging_options\nfrom tornado.util import basestring_type, exec_in\nfrom typing import (\n Any,\n Iterator,\n Iterable,\n Tuple,\n Set,\n Dict,\n Callable,\n List,\n TextIO,\n Optional,\n)\n\noptions = OptionParser()\n\nclass _Option(object):\n # This class could almost be made generic, but the way the types\n # interact with the multiple argument makes this tricky. (default\n # and the callback use List[T], but type is still Type[T]).\n\n UNSET = object()\n\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 _TIMEDELTA_ABBREV_DICT = {\n \"h\": \"hours\",\n \"m\": \"minutes\",\n \"min\": \"minutes\",\n \"s\": \"seconds\",\n \"sec\": \"seconds\",\n \"ms\": \"milliseconds\",\n \"us\": \"microseconds\",\n \"d\": \"days\",\n \"w\": \"weeks\",\n }\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\n def __init__(\n self,\n name: str,\n default: Any = None,\n type: Optional[type] = None,\n help: Optional[str] = None,\n metavar: Optional[str] = None,\n multiple: bool = False,\n file_name: Optional[str] = None,\n group_name: Optional[str] = None,\n callback: Optional[Callable[[Any], None]] = None,\n ) -> None:\n if default is None and multiple:\n default = []\n self.name = name\n if type is None:\n raise ValueError(\"type must not be None\")\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 = _Option.UNSET\n\n def set(self, value: Any) -> None:\n if self.multiple:\n if not isinstance(value, list):\n raise Error(\n \"Option %r is required to be a list of %s\"\n % (self.name, self.type.__name__)\n )\n for item in value:\n if item is not None and not isinstance(item, self.type):\n raise Error(\n \"Option %r is required to be a list of %s\"\n % (self.name, self.type.__name__)\n )\n else:\n if value is not None and not isinstance(value, self.type):\n raise Error(\n \"Option %r is required to be a %s (%s given)\"\n % (self.name, self.type.__name__, type(value))\n )\n self._value = value\n if self.callback is not None:\n self.callback(self._value)", "has_branch": true, "total_branches": 2} {"prompt_id": 733, "project": "tornado", "module": "tornado.queues", "class": "Queue", "method": "put", "focal_method_txt": " def put(\n self, item: _T, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> \"Future[None]\":\n \"\"\"Put an item into the queue, perhaps waiting until there is room.\n\n Returns a Future, which raises `tornado.util.TimeoutError` after a\n timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n `datetime.timedelta` object for a deadline relative to the\n current time.\n \"\"\"\n future = Future() # type: Future[None]\n try:\n self.put_nowait(item)\n except QueueFull:\n self._putters.append((item, future))\n _set_timeout(future, timeout)\n else:\n future.set_result(None)\n return future", "focal_method_lines": [185, 206], "in_stack": false, "globals": ["_T", "__all__"], "type_context": "import collections\nimport datetime\nimport heapq\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.locks import Event\nfrom typing import Union, TypeVar, Generic, Awaitable, Optional\nimport typing\n\n_T = TypeVar(\"_T\")\n__all__ = [\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\"]\n\nclass Queue(Generic[_T]):\n\n _queue = None\n\n def __init__(self, maxsize: int = 0) -> None:\n if maxsize is None:\n raise TypeError(\"maxsize can't be None\")\n\n if maxsize < 0:\n raise ValueError(\"maxsize can't be negative\")\n\n self._maxsize = maxsize\n self._init()\n self._getters = collections.deque([]) # type: Deque[Future[_T]]\n self._putters = collections.deque([]) # type: Deque[Tuple[_T, Future[None]]]\n self._unfinished_tasks = 0\n self._finished = Event()\n self._finished.set()\n\n def put(\n self, item: _T, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> \"Future[None]\":\n \"\"\"Put an item into the queue, perhaps waiting until there is room.\n\n Returns a Future, which raises `tornado.util.TimeoutError` after a\n timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n `datetime.timedelta` object for a deadline relative to the\n current time.\n \"\"\"\n future = Future() # type: Future[None]\n try:\n self.put_nowait(item)\n except QueueFull:\n self._putters.append((item, future))\n _set_timeout(future, timeout)\n else:\n future.set_result(None)\n return future", "has_branch": false, "total_branches": 0} {"prompt_id": 734, "project": "tornado", "module": "tornado.queues", "class": "Queue", "method": "put_nowait", "focal_method_txt": " def put_nowait(self, item: _T) -> None:\n \"\"\"Put an item into the queue without blocking.\n\n If no free slot is immediately available, raise `QueueFull`.\n \"\"\"\n self._consume_expired()\n if self._getters:\n assert self.empty(), \"queue non-empty, why are getters waiting?\"\n getter = self._getters.popleft()\n self.__put_internal(item)\n future_set_result_unless_cancelled(getter, self._get())\n elif self.full():\n raise QueueFull\n else:\n self.__put_internal(item)", "focal_method_lines": [208, 222], "in_stack": false, "globals": ["_T", "__all__"], "type_context": "import collections\nimport datetime\nimport heapq\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.locks import Event\nfrom typing import Union, TypeVar, Generic, Awaitable, Optional\nimport typing\n\n_T = TypeVar(\"_T\")\n__all__ = [\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\"]\n\nclass Queue(Generic[_T]):\n\n _queue = None\n\n def __init__(self, maxsize: int = 0) -> None:\n if maxsize is None:\n raise TypeError(\"maxsize can't be None\")\n\n if maxsize < 0:\n raise ValueError(\"maxsize can't be negative\")\n\n self._maxsize = maxsize\n self._init()\n self._getters = collections.deque([]) # type: Deque[Future[_T]]\n self._putters = collections.deque([]) # type: Deque[Tuple[_T, Future[None]]]\n self._unfinished_tasks = 0\n self._finished = Event()\n self._finished.set()\n\n def put_nowait(self, item: _T) -> None:\n \"\"\"Put an item into the queue without blocking.\n\n If no free slot is immediately available, raise `QueueFull`.\n \"\"\"\n self._consume_expired()\n if self._getters:\n assert self.empty(), \"queue non-empty, why are getters waiting?\"\n getter = self._getters.popleft()\n self.__put_internal(item)\n future_set_result_unless_cancelled(getter, self._get())\n elif self.full():\n raise QueueFull\n else:\n self.__put_internal(item)", "has_branch": true, "total_branches": 2} {"prompt_id": 735, "project": "tornado", "module": "tornado.queues", "class": "Queue", "method": "get", "focal_method_txt": " def get(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[_T]:\n \"\"\"Remove and return an item from the queue.\n\n Returns an awaitable which resolves once an item is available, or raises\n `tornado.util.TimeoutError` after a timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n `datetime.timedelta` object for a deadline relative to the\n current time.\n\n .. note::\n\n The ``timeout`` argument of this method differs from that\n of the standard library's `queue.Queue.get`. That method\n interprets numeric values as relative timeouts; this one\n interprets them as absolute deadlines and requires\n ``timedelta`` objects for relative timeouts (consistent\n with other timeouts in Tornado).\n\n \"\"\"\n future = Future() # type: Future[_T]\n try:\n future.set_result(self.get_nowait())\n except QueueEmpty:\n self._getters.append(future)\n _set_timeout(future, timeout)\n return future", "focal_method_lines": [224, 253], "in_stack": false, "globals": ["_T", "__all__"], "type_context": "import collections\nimport datetime\nimport heapq\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.locks import Event\nfrom typing import Union, TypeVar, Generic, Awaitable, Optional\nimport typing\n\n_T = TypeVar(\"_T\")\n__all__ = [\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\"]\n\nclass Queue(Generic[_T]):\n\n _queue = None\n\n def __init__(self, maxsize: int = 0) -> None:\n if maxsize is None:\n raise TypeError(\"maxsize can't be None\")\n\n if maxsize < 0:\n raise ValueError(\"maxsize can't be negative\")\n\n self._maxsize = maxsize\n self._init()\n self._getters = collections.deque([]) # type: Deque[Future[_T]]\n self._putters = collections.deque([]) # type: Deque[Tuple[_T, Future[None]]]\n self._unfinished_tasks = 0\n self._finished = Event()\n self._finished.set()\n\n def get(\n self, timeout: Optional[Union[float, datetime.timedelta]] = None\n ) -> Awaitable[_T]:\n \"\"\"Remove and return an item from the queue.\n\n Returns an awaitable which resolves once an item is available, or raises\n `tornado.util.TimeoutError` after a timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n `datetime.timedelta` object for a deadline relative to the\n current time.\n\n .. note::\n\n The ``timeout`` argument of this method differs from that\n of the standard library's `queue.Queue.get`. That method\n interprets numeric values as relative timeouts; this one\n interprets them as absolute deadlines and requires\n ``timedelta`` objects for relative timeouts (consistent\n with other timeouts in Tornado).\n\n \"\"\"\n future = Future() # type: Future[_T]\n try:\n future.set_result(self.get_nowait())\n except QueueEmpty:\n self._getters.append(future)\n _set_timeout(future, timeout)\n return future", "has_branch": false, "total_branches": 0} {"prompt_id": 736, "project": "tornado", "module": "tornado.queues", "class": "Queue", "method": "get_nowait", "focal_method_txt": " def get_nowait(self) -> _T:\n \"\"\"Remove and return an item from the queue without blocking.\n\n Return an item if one is immediately available, else raise\n `QueueEmpty`.\n \"\"\"\n self._consume_expired()\n if self._putters:\n assert self.full(), \"queue not full, why are putters waiting?\"\n item, putter = self._putters.popleft()\n self.__put_internal(item)\n future_set_result_unless_cancelled(putter, None)\n return self._get()\n elif self.qsize():\n return self._get()\n else:\n raise QueueEmpty", "focal_method_lines": [255, 271], "in_stack": false, "globals": ["_T", "__all__"], "type_context": "import collections\nimport datetime\nimport heapq\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.locks import Event\nfrom typing import Union, TypeVar, Generic, Awaitable, Optional\nimport typing\n\n_T = TypeVar(\"_T\")\n__all__ = [\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\"]\n\nclass Queue(Generic[_T]):\n\n _queue = None\n\n def __init__(self, maxsize: int = 0) -> None:\n if maxsize is None:\n raise TypeError(\"maxsize can't be None\")\n\n if maxsize < 0:\n raise ValueError(\"maxsize can't be negative\")\n\n self._maxsize = maxsize\n self._init()\n self._getters = collections.deque([]) # type: Deque[Future[_T]]\n self._putters = collections.deque([]) # type: Deque[Tuple[_T, Future[None]]]\n self._unfinished_tasks = 0\n self._finished = Event()\n self._finished.set()\n\n def get_nowait(self) -> _T:\n \"\"\"Remove and return an item from the queue without blocking.\n\n Return an item if one is immediately available, else raise\n `QueueEmpty`.\n \"\"\"\n self._consume_expired()\n if self._putters:\n assert self.full(), \"queue not full, why are putters waiting?\"\n item, putter = self._putters.popleft()\n self.__put_internal(item)\n future_set_result_unless_cancelled(putter, None)\n return self._get()\n elif self.qsize():\n return self._get()\n else:\n raise QueueEmpty", "has_branch": true, "total_branches": 2} {"prompt_id": 737, "project": "tornado", "module": "tornado.queues", "class": "Queue", "method": "task_done", "focal_method_txt": " def task_done(self) -> None:\n \"\"\"Indicate that a formerly enqueued task is complete.\n\n Used by queue consumers. For each `.get` used to fetch a task, a\n subsequent call to `.task_done` tells the queue that the processing\n on the task is complete.\n\n If a `.join` is blocking, it resumes when all items have been\n processed; that is, when every `.put` is matched by a `.task_done`.\n\n Raises `ValueError` if called more times than `.put`.\n \"\"\"\n if self._unfinished_tasks <= 0:\n raise ValueError(\"task_done() called too many times\")\n self._unfinished_tasks -= 1\n if self._unfinished_tasks == 0:\n self._finished.set()", "focal_method_lines": [273, 289], "in_stack": false, "globals": ["_T", "__all__"], "type_context": "import collections\nimport datetime\nimport heapq\nfrom tornado import gen, ioloop\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.locks import Event\nfrom typing import Union, TypeVar, Generic, Awaitable, Optional\nimport typing\n\n_T = TypeVar(\"_T\")\n__all__ = [\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\"]\n\nclass Queue(Generic[_T]):\n\n _queue = None\n\n def __init__(self, maxsize: int = 0) -> None:\n if maxsize is None:\n raise TypeError(\"maxsize can't be None\")\n\n if maxsize < 0:\n raise ValueError(\"maxsize can't be negative\")\n\n self._maxsize = maxsize\n self._init()\n self._getters = collections.deque([]) # type: Deque[Future[_T]]\n self._putters = collections.deque([]) # type: Deque[Tuple[_T, Future[None]]]\n self._unfinished_tasks = 0\n self._finished = Event()\n self._finished.set()\n\n def task_done(self) -> None:\n \"\"\"Indicate that a formerly enqueued task is complete.\n\n Used by queue consumers. For each `.get` used to fetch a task, a\n subsequent call to `.task_done` tells the queue that the processing\n on the task is complete.\n\n If a `.join` is blocking, it resumes when all items have been\n processed; that is, when every `.put` is matched by a `.task_done`.\n\n Raises `ValueError` if called more times than `.put`.\n \"\"\"\n if self._unfinished_tasks <= 0:\n raise ValueError(\"task_done() called too many times\")\n self._unfinished_tasks -= 1\n if self._unfinished_tasks == 0:\n self._finished.set()", "has_branch": true, "total_branches": 2} {"prompt_id": 738, "project": "tornado", "module": "tornado.simple_httpclient", "class": "HTTPTimeoutError", "method": "__str__", "focal_method_txt": " def __str__(self) -> str:\n return self.message or \"Timeout\"", "focal_method_lines": [55, 56], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass HTTPTimeoutError(HTTPError):\n\n def __init__(self, message: str) -> None:\n super().__init__(599, message=message)\n\n def __str__(self) -> str:\n return self.message or \"Timeout\"", "has_branch": false, "total_branches": 0} {"prompt_id": 739, "project": "tornado", "module": "tornado.simple_httpclient", "class": "HTTPStreamClosedError", "method": "__str__", "focal_method_txt": " def __str__(self) -> str:\n return self.message or \"Stream closed\"", "focal_method_lines": [74, 75], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass HTTPStreamClosedError(HTTPError):\n\n def __init__(self, message: str) -> None:\n super().__init__(599, message=message)\n\n def __str__(self) -> str:\n return self.message or \"Stream closed\"", "has_branch": false, "total_branches": 0} {"prompt_id": 740, "project": "tornado", "module": "tornado.simple_httpclient", "class": "SimpleAsyncHTTPClient", "method": "initialize", "focal_method_txt": " def initialize( # type: ignore\n self,\n max_clients: int = 10,\n hostname_mapping: Optional[Dict[str, str]] = None,\n max_buffer_size: int = 104857600,\n resolver: Optional[Resolver] = None,\n defaults: Optional[Dict[str, Any]] = None,\n max_header_size: Optional[int] = None,\n max_body_size: Optional[int] = None,\n ) -> None:\n \"\"\"Creates a AsyncHTTPClient.\n\n Only a single AsyncHTTPClient instance exists per IOLoop\n in order to provide limitations on the number of pending connections.\n ``force_instance=True`` may be used to suppress this behavior.\n\n Note that because of this implicit reuse, unless ``force_instance``\n is used, only the first call to the constructor actually uses\n its arguments. It is recommended to use the ``configure`` method\n instead of the constructor to ensure that arguments take effect.\n\n ``max_clients`` is the number of concurrent requests that can be\n in progress; when this limit is reached additional requests will be\n queued. Note that time spent waiting in this queue still counts\n against the ``request_timeout``.\n\n ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.\n It can be used to make local DNS changes when modifying system-wide\n settings like ``/etc/hosts`` is not possible or desirable (e.g. in\n unittests).\n\n ``max_buffer_size`` (default 100MB) is the number of bytes\n that can be read into memory at once. ``max_body_size``\n (defaults to ``max_buffer_size``) is the largest response body\n that the client will accept. Without a\n ``streaming_callback``, the smaller of these two limits\n applies; with a ``streaming_callback`` only ``max_body_size``\n does.\n\n .. versionchanged:: 4.2\n Added the ``max_body_size`` argument.\n \"\"\"\n super().initialize(defaults=defaults)\n self.max_clients = max_clients\n self.queue = (\n collections.deque()\n ) # type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]]\n self.active = (\n {}\n ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]]\n self.waiting = (\n {}\n ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]]\n self.max_buffer_size = max_buffer_size\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n # TCPClient could create a Resolver for us, but we have to do it\n # ourselves to support hostname_mapping.\n if resolver:\n self.resolver = resolver\n self.own_resolver = False\n else:\n self.resolver = Resolver()\n self.own_resolver = True\n if hostname_mapping is not None:\n self.resolver = OverrideResolver(\n resolver=self.resolver, mapping=hostname_mapping\n )\n self.tcp_client = TCPClient(resolver=self.resolver)", "focal_method_lines": [88, 156], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n\n def initialize( # type: ignore\n self,\n max_clients: int = 10,\n hostname_mapping: Optional[Dict[str, str]] = None,\n max_buffer_size: int = 104857600,\n resolver: Optional[Resolver] = None,\n defaults: Optional[Dict[str, Any]] = None,\n max_header_size: Optional[int] = None,\n max_body_size: Optional[int] = None,\n ) -> None:\n \"\"\"Creates a AsyncHTTPClient.\n\n Only a single AsyncHTTPClient instance exists per IOLoop\n in order to provide limitations on the number of pending connections.\n ``force_instance=True`` may be used to suppress this behavior.\n\n Note that because of this implicit reuse, unless ``force_instance``\n is used, only the first call to the constructor actually uses\n its arguments. It is recommended to use the ``configure`` method\n instead of the constructor to ensure that arguments take effect.\n\n ``max_clients`` is the number of concurrent requests that can be\n in progress; when this limit is reached additional requests will be\n queued. Note that time spent waiting in this queue still counts\n against the ``request_timeout``.\n\n ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.\n It can be used to make local DNS changes when modifying system-wide\n settings like ``/etc/hosts`` is not possible or desirable (e.g. in\n unittests).\n\n ``max_buffer_size`` (default 100MB) is the number of bytes\n that can be read into memory at once. ``max_body_size``\n (defaults to ``max_buffer_size``) is the largest response body\n that the client will accept. Without a\n ``streaming_callback``, the smaller of these two limits\n applies; with a ``streaming_callback`` only ``max_body_size``\n does.\n\n .. versionchanged:: 4.2\n Added the ``max_body_size`` argument.\n \"\"\"\n super().initialize(defaults=defaults)\n self.max_clients = max_clients\n self.queue = (\n collections.deque()\n ) # type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]]\n self.active = (\n {}\n ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]]\n self.waiting = (\n {}\n ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]]\n self.max_buffer_size = max_buffer_size\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n # TCPClient could create a Resolver for us, but we have to do it\n # ourselves to support hostname_mapping.\n if resolver:\n self.resolver = resolver\n self.own_resolver = False\n else:\n self.resolver = Resolver()\n self.own_resolver = True\n if hostname_mapping is not None:\n self.resolver = OverrideResolver(\n resolver=self.resolver, mapping=hostname_mapping\n )\n self.tcp_client = TCPClient(resolver=self.resolver)", "has_branch": true, "total_branches": 2} {"prompt_id": 741, "project": "tornado", "module": "tornado.simple_httpclient", "class": "SimpleAsyncHTTPClient", "method": "close", "focal_method_txt": " def close(self) -> None:\n super().close()\n if self.own_resolver:\n self.resolver.close()\n self.tcp_client.close()", "focal_method_lines": [158, 162], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n\n def close(self) -> None:\n super().close()\n if self.own_resolver:\n self.resolver.close()\n self.tcp_client.close()", "has_branch": true, "total_branches": 2} {"prompt_id": 742, "project": "tornado", "module": "tornado.simple_httpclient", "class": "SimpleAsyncHTTPClient", "method": "fetch_impl", "focal_method_txt": " def fetch_impl(\n self, request: HTTPRequest, callback: Callable[[HTTPResponse], None]\n ) -> None:\n key = object()\n self.queue.append((key, request, callback))\n assert request.connect_timeout is not None\n assert request.request_timeout is not None\n timeout_handle = None\n if len(self.active) >= self.max_clients:\n timeout = (\n min(request.connect_timeout, request.request_timeout)\n or request.connect_timeout\n or request.request_timeout\n ) # min but skip zero\n if timeout:\n timeout_handle = self.io_loop.add_timeout(\n self.io_loop.time() + timeout,\n functools.partial(self._on_timeout, key, \"in request queue\"),\n )\n self.waiting[key] = (request, callback, timeout_handle)\n self._process_queue()\n if self.queue:\n gen_log.debug(\n \"max_clients limit reached, request queued. \"\n \"%d active, %d queued requests.\" % (len(self.active), len(self.queue))\n )", "focal_method_lines": [164, 186], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n\n def fetch_impl(\n self, request: HTTPRequest, callback: Callable[[HTTPResponse], None]\n ) -> None:\n key = object()\n self.queue.append((key, request, callback))\n assert request.connect_timeout is not None\n assert request.request_timeout is not None\n timeout_handle = None\n if len(self.active) >= self.max_clients:\n timeout = (\n min(request.connect_timeout, request.request_timeout)\n or request.connect_timeout\n or request.request_timeout\n ) # min but skip zero\n if timeout:\n timeout_handle = self.io_loop.add_timeout(\n self.io_loop.time() + timeout,\n functools.partial(self._on_timeout, key, \"in request queue\"),\n )\n self.waiting[key] = (request, callback, timeout_handle)\n self._process_queue()\n if self.queue:\n gen_log.debug(\n \"max_clients limit reached, request queued. \"\n \"%d active, %d queued requests.\" % (len(self.active), len(self.queue))\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 743, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )", "focal_method_lines": [259, 288], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 744, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "run", "focal_method_txt": " async def run(self) -> None:\n try:\n self.parsed = urllib.parse.urlsplit(_unicode(self.request.url))\n if self.parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported url scheme: %s\" % self.request.url)\n # urlsplit results have hostname and port results, but they\n # didn't support ipv6 literals until python 2.7.\n netloc = self.parsed.netloc\n if \"@\" in netloc:\n userpass, _, netloc = netloc.rpartition(\"@\")\n host, port = httputil.split_host_and_port(netloc)\n if port is None:\n port = 443 if self.parsed.scheme == \"https\" else 80\n if re.match(r\"^\\[.*\\]$\", host):\n # raw ipv6 addresses in urls are enclosed in brackets\n host = host[1:-1]\n self.parsed_hostname = host # save final host for _on_connect\n\n if self.request.allow_ipv6 is False:\n af = socket.AF_INET\n else:\n af = socket.AF_UNSPEC\n\n ssl_options = self._get_ssl_options(self.parsed.scheme)\n\n source_ip = None\n if self.request.network_interface:\n if is_valid_ip(self.request.network_interface):\n source_ip = self.request.network_interface\n else:\n raise ValueError(\n \"Unrecognized IPv4 or IPv6 address for network_interface, got %r\"\n % (self.request.network_interface,)\n )\n\n timeout = (\n min(self.request.connect_timeout, self.request.request_timeout)\n or self.request.connect_timeout\n or self.request.request_timeout\n ) # min but skip zero\n if timeout:\n self._timeout = self.io_loop.add_timeout(\n self.start_time + timeout,\n functools.partial(self._on_timeout, \"while connecting\"),\n )\n stream = await self.tcp_client.connect(\n host,\n port,\n af=af,\n ssl_options=ssl_options,\n max_buffer_size=self.max_buffer_size,\n source_ip=source_ip,\n )\n\n if self.final_callback is None:\n # final_callback is cleared if we've hit our timeout.\n stream.close()\n return\n self.stream = stream\n self.stream.set_close_callback(self.on_connection_close)\n self._remove_timeout()\n if self.final_callback is None:\n return\n if self.request.request_timeout:\n self._timeout = self.io_loop.add_timeout(\n self.start_time + self.request.request_timeout,\n functools.partial(self._on_timeout, \"during request\"),\n )\n if (\n self.request.method not in self._SUPPORTED_METHODS\n and not self.request.allow_nonstandard_methods\n ):\n raise KeyError(\"unknown method %s\" % self.request.method)\n for key in (\n \"proxy_host\",\n \"proxy_port\",\n \"proxy_username\",\n \"proxy_password\",\n \"proxy_auth_mode\",\n ):\n if getattr(self.request, key, None):\n raise NotImplementedError(\"%s not supported\" % key)\n if \"Connection\" not in self.request.headers:\n self.request.headers[\"Connection\"] = \"close\"\n if \"Host\" not in self.request.headers:\n if \"@\" in self.parsed.netloc:\n self.request.headers[\"Host\"] = self.parsed.netloc.rpartition(\"@\")[\n -1\n ]\n else:\n self.request.headers[\"Host\"] = self.parsed.netloc\n username, password = None, None\n if self.parsed.username is not None:\n username, password = self.parsed.username, self.parsed.password\n elif self.request.auth_username is not None:\n username = self.request.auth_username\n password = self.request.auth_password or \"\"\n if username is not None:\n assert password is not None\n if self.request.auth_mode not in (None, \"basic\"):\n raise ValueError(\"unsupported auth_mode %s\", self.request.auth_mode)\n self.request.headers[\"Authorization\"] = \"Basic \" + _unicode(\n base64.b64encode(\n httputil.encode_username_password(username, password)\n )\n )\n if self.request.user_agent:\n self.request.headers[\"User-Agent\"] = self.request.user_agent\n elif self.request.headers.get(\"User-Agent\") is None:\n self.request.headers[\"User-Agent\"] = \"Tornado/{}\".format(version)\n if not self.request.allow_nonstandard_methods:\n # Some HTTP methods nearly always have bodies while others\n # almost never do. Fail in this case unless the user has\n # opted out of sanity checks with allow_nonstandard_methods.\n body_expected = self.request.method in (\"POST\", \"PATCH\", \"PUT\")\n body_present = (\n self.request.body is not None\n or self.request.body_producer is not None\n )\n if (body_expected and not body_present) or (\n body_present and not body_expected\n ):\n raise ValueError(\n \"Body must %sbe None for method %s (unless \"\n \"allow_nonstandard_methods is true)\"\n % (\"not \" if body_expected else \"\", self.request.method)\n )\n if self.request.expect_100_continue:\n self.request.headers[\"Expect\"] = \"100-continue\"\n if self.request.body is not None:\n # When body_producer is used the caller is responsible for\n # setting Content-Length (or else chunked encoding will be used).\n self.request.headers[\"Content-Length\"] = str(len(self.request.body))\n if (\n self.request.method == \"POST\"\n and \"Content-Type\" not in self.request.headers\n ):\n self.request.headers[\n \"Content-Type\"\n ] = \"application/x-www-form-urlencoded\"\n if self.request.decompress_response:\n self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n req_path = (self.parsed.path or \"/\") + (\n (\"?\" + self.parsed.query) if self.parsed.query else \"\"\n )\n self.connection = self._create_connection(stream)\n start_line = httputil.RequestStartLine(self.request.method, req_path, \"\")\n self.connection.write_headers(start_line, self.request.headers)\n if self.request.expect_100_continue:\n await self.connection.read_response(self)\n else:\n await self._write_body(True)\n except Exception:\n if not self._handle_exception(*sys.exc_info()):\n raise", "focal_method_lines": [292, 446], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )\n\n async def run(self) -> None:\n try:\n self.parsed = urllib.parse.urlsplit(_unicode(self.request.url))\n if self.parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported url scheme: %s\" % self.request.url)\n # urlsplit results have hostname and port results, but they\n # didn't support ipv6 literals until python 2.7.\n netloc = self.parsed.netloc\n if \"@\" in netloc:\n userpass, _, netloc = netloc.rpartition(\"@\")\n host, port = httputil.split_host_and_port(netloc)\n if port is None:\n port = 443 if self.parsed.scheme == \"https\" else 80\n if re.match(r\"^\\[.*\\]$\", host):\n # raw ipv6 addresses in urls are enclosed in brackets\n host = host[1:-1]\n self.parsed_hostname = host # save final host for _on_connect\n\n if self.request.allow_ipv6 is False:\n af = socket.AF_INET\n else:\n af = socket.AF_UNSPEC\n\n ssl_options = self._get_ssl_options(self.parsed.scheme)\n\n source_ip = None\n if self.request.network_interface:\n if is_valid_ip(self.request.network_interface):\n source_ip = self.request.network_interface\n else:\n raise ValueError(\n \"Unrecognized IPv4 or IPv6 address for network_interface, got %r\"\n % (self.request.network_interface,)\n )\n\n timeout = (\n min(self.request.connect_timeout, self.request.request_timeout)\n or self.request.connect_timeout\n or self.request.request_timeout\n ) # min but skip zero\n if timeout:\n self._timeout = self.io_loop.add_timeout(\n self.start_time + timeout,\n functools.partial(self._on_timeout, \"while connecting\"),\n )\n stream = await self.tcp_client.connect(\n host,\n port,\n af=af,\n ssl_options=ssl_options,\n max_buffer_size=self.max_buffer_size,\n source_ip=source_ip,\n )\n\n if self.final_callback is None:\n # final_callback is cleared if we've hit our timeout.\n stream.close()\n return\n self.stream = stream\n self.stream.set_close_callback(self.on_connection_close)\n self._remove_timeout()\n if self.final_callback is None:\n return\n if self.request.request_timeout:\n self._timeout = self.io_loop.add_timeout(\n self.start_time + self.request.request_timeout,\n functools.partial(self._on_timeout, \"during request\"),\n )\n if (\n self.request.method not in self._SUPPORTED_METHODS\n and not self.request.allow_nonstandard_methods\n ):\n raise KeyError(\"unknown method %s\" % self.request.method)\n for key in (\n \"proxy_host\",\n \"proxy_port\",\n \"proxy_username\",\n \"proxy_password\",\n \"proxy_auth_mode\",\n ):\n if getattr(self.request, key, None):\n raise NotImplementedError(\"%s not supported\" % key)\n if \"Connection\" not in self.request.headers:\n self.request.headers[\"Connection\"] = \"close\"\n if \"Host\" not in self.request.headers:\n if \"@\" in self.parsed.netloc:\n self.request.headers[\"Host\"] = self.parsed.netloc.rpartition(\"@\")[\n -1\n ]\n else:\n self.request.headers[\"Host\"] = self.parsed.netloc\n username, password = None, None\n if self.parsed.username is not None:\n username, password = self.parsed.username, self.parsed.password\n elif self.request.auth_username is not None:\n username = self.request.auth_username\n password = self.request.auth_password or \"\"\n if username is not None:\n assert password is not None\n if self.request.auth_mode not in (None, \"basic\"):\n raise ValueError(\"unsupported auth_mode %s\", self.request.auth_mode)\n self.request.headers[\"Authorization\"] = \"Basic \" + _unicode(\n base64.b64encode(\n httputil.encode_username_password(username, password)\n )\n )\n if self.request.user_agent:\n self.request.headers[\"User-Agent\"] = self.request.user_agent\n elif self.request.headers.get(\"User-Agent\") is None:\n self.request.headers[\"User-Agent\"] = \"Tornado/{}\".format(version)\n if not self.request.allow_nonstandard_methods:\n # Some HTTP methods nearly always have bodies while others\n # almost never do. Fail in this case unless the user has\n # opted out of sanity checks with allow_nonstandard_methods.\n body_expected = self.request.method in (\"POST\", \"PATCH\", \"PUT\")\n body_present = (\n self.request.body is not None\n or self.request.body_producer is not None\n )\n if (body_expected and not body_present) or (\n body_present and not body_expected\n ):\n raise ValueError(\n \"Body must %sbe None for method %s (unless \"\n \"allow_nonstandard_methods is true)\"\n % (\"not \" if body_expected else \"\", self.request.method)\n )\n if self.request.expect_100_continue:\n self.request.headers[\"Expect\"] = \"100-continue\"\n if self.request.body is not None:\n # When body_producer is used the caller is responsible for\n # setting Content-Length (or else chunked encoding will be used).\n self.request.headers[\"Content-Length\"] = str(len(self.request.body))\n if (\n self.request.method == \"POST\"\n and \"Content-Type\" not in self.request.headers\n ):\n self.request.headers[\n \"Content-Type\"\n ] = \"application/x-www-form-urlencoded\"\n if self.request.decompress_response:\n self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n req_path = (self.parsed.path or \"/\") + (\n (\"?\" + self.parsed.query) if self.parsed.query else \"\"\n )\n self.connection = self._create_connection(stream)\n start_line = httputil.RequestStartLine(self.request.method, req_path, \"\")\n self.connection.write_headers(start_line, self.request.headers)\n if self.request.expect_100_continue:\n await self.connection.read_response(self)\n else:\n await self._write_body(True)\n except Exception:\n if not self._handle_exception(*sys.exc_info()):\n raise", "has_branch": true, "total_branches": 2} {"prompt_id": 745, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "on_connection_close", "focal_method_txt": " def on_connection_close(self) -> None:\n if self.final_callback is not None:\n message = \"Connection closed\"\n if self.stream.error:\n raise self.stream.error\n try:\n raise HTTPStreamClosedError(message)\n except HTTPStreamClosedError:\n self._handle_exception(*sys.exc_info())", "focal_method_lines": [577, 585], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass HTTPStreamClosedError(HTTPError):\n\n def __init__(self, message: str) -> None:\n super().__init__(599, message=message)\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )\n\n def on_connection_close(self) -> None:\n if self.final_callback is not None:\n message = \"Connection closed\"\n if self.stream.error:\n raise self.stream.error\n try:\n raise HTTPStreamClosedError(message)\n except HTTPStreamClosedError:\n self._handle_exception(*sys.exc_info())", "has_branch": true, "total_branches": 2} {"prompt_id": 746, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "headers_received", "focal_method_txt": " async def headers_received(\n self,\n first_line: Union[httputil.ResponseStartLine, httputil.RequestStartLine],\n headers: httputil.HTTPHeaders,\n ) -> None:\n assert isinstance(first_line, httputil.ResponseStartLine)\n if self.request.expect_100_continue and first_line.code == 100:\n await self._write_body(False)\n return\n self.code = first_line.code\n self.reason = first_line.reason\n self.headers = headers\n\n if self._should_follow_redirect():\n return\n\n if self.request.header_callback is not None:\n # Reassemble the start line.\n self.request.header_callback(\"%s %s %s\\r\\n\" % first_line)\n for k, v in self.headers.get_all():\n self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n self.request.header_callback(\"\\r\\n\")", "focal_method_lines": [587, 608], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )\n\n async def headers_received(\n self,\n first_line: Union[httputil.ResponseStartLine, httputil.RequestStartLine],\n headers: httputil.HTTPHeaders,\n ) -> None:\n assert isinstance(first_line, httputil.ResponseStartLine)\n if self.request.expect_100_continue and first_line.code == 100:\n await self._write_body(False)\n return\n self.code = first_line.code\n self.reason = first_line.reason\n self.headers = headers\n\n if self._should_follow_redirect():\n return\n\n if self.request.header_callback is not None:\n # Reassemble the start line.\n self.request.header_callback(\"%s %s %s\\r\\n\" % first_line)\n for k, v in self.headers.get_all():\n self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n self.request.header_callback(\"\\r\\n\")", "has_branch": true, "total_branches": 2} {"prompt_id": 747, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "finish", "focal_method_txt": " def finish(self) -> None:\n assert self.code is not None\n data = b\"\".join(self.chunks)\n self._remove_timeout()\n original_request = getattr(self.request, \"original_request\", self.request)\n if self._should_follow_redirect():\n assert isinstance(self.request, _RequestProxy)\n new_request = copy.copy(self.request.request)\n new_request.url = urllib.parse.urljoin(\n self.request.url, self.headers[\"Location\"]\n )\n new_request.max_redirects = self.request.max_redirects - 1\n del new_request.headers[\"Host\"]\n # https://tools.ietf.org/html/rfc7231#section-6.4\n #\n # The original HTTP spec said that after a 301 or 302\n # redirect, the request method should be preserved.\n # However, browsers implemented this by changing the\n # method to GET, and the behavior stuck. 303 redirects\n # always specified this POST-to-GET behavior, arguably\n # for *all* methods, but libcurl < 7.70 only does this\n # for POST, while libcurl >= 7.70 does it for other methods.\n if (self.code == 303 and self.request.method != \"HEAD\") or (\n self.code in (301, 302) and self.request.method == \"POST\"\n ):\n new_request.method = \"GET\"\n new_request.body = None\n for h in [\n \"Content-Length\",\n \"Content-Type\",\n \"Content-Encoding\",\n \"Transfer-Encoding\",\n ]:\n try:\n del self.request.headers[h]\n except KeyError:\n pass\n new_request.original_request = original_request\n final_callback = self.final_callback\n self.final_callback = None\n self._release()\n fut = self.client.fetch(new_request, raise_error=False)\n fut.add_done_callback(lambda f: final_callback(f.result()))\n self._on_end_request()\n return\n if self.request.streaming_callback:\n buffer = BytesIO()\n else:\n buffer = BytesIO(data) # TODO: don't require one big string?\n response = HTTPResponse(\n original_request,\n self.code,\n reason=getattr(self, \"reason\", None),\n headers=self.headers,\n request_time=self.io_loop.time() - self.start_time,\n start_time=self.start_wall_time,\n buffer=buffer,\n effective_url=self.request.url,\n )\n self._run_callback(response)\n self._on_end_request()", "focal_method_lines": [621, 681], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )\n\n def finish(self) -> None:\n assert self.code is not None\n data = b\"\".join(self.chunks)\n self._remove_timeout()\n original_request = getattr(self.request, \"original_request\", self.request)\n if self._should_follow_redirect():\n assert isinstance(self.request, _RequestProxy)\n new_request = copy.copy(self.request.request)\n new_request.url = urllib.parse.urljoin(\n self.request.url, self.headers[\"Location\"]\n )\n new_request.max_redirects = self.request.max_redirects - 1\n del new_request.headers[\"Host\"]\n # https://tools.ietf.org/html/rfc7231#section-6.4\n #\n # The original HTTP spec said that after a 301 or 302\n # redirect, the request method should be preserved.\n # However, browsers implemented this by changing the\n # method to GET, and the behavior stuck. 303 redirects\n # always specified this POST-to-GET behavior, arguably\n # for *all* methods, but libcurl < 7.70 only does this\n # for POST, while libcurl >= 7.70 does it for other methods.\n if (self.code == 303 and self.request.method != \"HEAD\") or (\n self.code in (301, 302) and self.request.method == \"POST\"\n ):\n new_request.method = \"GET\"\n new_request.body = None\n for h in [\n \"Content-Length\",\n \"Content-Type\",\n \"Content-Encoding\",\n \"Transfer-Encoding\",\n ]:\n try:\n del self.request.headers[h]\n except KeyError:\n pass\n new_request.original_request = original_request\n final_callback = self.final_callback\n self.final_callback = None\n self._release()\n fut = self.client.fetch(new_request, raise_error=False)\n fut.add_done_callback(lambda f: final_callback(f.result()))\n self._on_end_request()\n return\n if self.request.streaming_callback:\n buffer = BytesIO()\n else:\n buffer = BytesIO(data) # TODO: don't require one big string?\n response = HTTPResponse(\n original_request,\n self.code,\n reason=getattr(self, \"reason\", None),\n headers=self.headers,\n request_time=self.io_loop.time() - self.start_time,\n start_time=self.start_wall_time,\n buffer=buffer,\n effective_url=self.request.url,\n )\n self._run_callback(response)\n self._on_end_request()", "has_branch": true, "total_branches": 2} {"prompt_id": 748, "project": "tornado", "module": "tornado.simple_httpclient", "class": "_HTTPConnection", "method": "data_received", "focal_method_txt": " def data_received(self, chunk: bytes) -> None:\n if self._should_follow_redirect():\n # We're going to follow a redirect so just discard the body.\n return\n if self.request.streaming_callback is not None:\n self.request.streaming_callback(chunk)\n else:\n self.chunks.append(chunk)", "focal_method_lines": [686, 693], "in_stack": false, "globals": [], "type_context": "from tornado.escape import _unicode\nfrom tornado import gen, version\nfrom tornado.httpclient import (\n HTTPResponse,\n HTTPError,\n AsyncHTTPClient,\n main,\n _RequestProxy,\n HTTPRequest,\n)\nfrom tornado import httputil\nfrom tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.netutil import (\n Resolver,\n OverrideResolver,\n _client_ssl_defaults,\n is_valid_ip,\n)\nfrom tornado.log import gen_log\nfrom tornado.tcpclient import TCPClient\nimport base64\nimport collections\nimport copy\nimport functools\nimport re\nimport socket\nimport ssl\nimport sys\nimport time\nfrom io import BytesIO\nimport urllib.parse\nfrom typing import Dict, Any, Callable, Optional, Type, Union\nfrom types import TracebackType\nimport typing\n\n\n\nclass _HTTPConnection(httputil.HTTPMessageDelegate):\n\n _SUPPORTED_METHODS = set(\n [\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"]\n )\n\n def __init__(\n self,\n client: Optional[SimpleAsyncHTTPClient],\n request: HTTPRequest,\n release_callback: Callable[[], None],\n final_callback: Callable[[HTTPResponse], None],\n max_buffer_size: int,\n tcp_client: TCPClient,\n max_header_size: int,\n max_body_size: int,\n ) -> None:\n self.io_loop = IOLoop.current()\n self.start_time = self.io_loop.time()\n self.start_wall_time = time.time()\n self.client = client\n self.request = request\n self.release_callback = release_callback\n self.final_callback = final_callback\n self.max_buffer_size = max_buffer_size\n self.tcp_client = tcp_client\n self.max_header_size = max_header_size\n self.max_body_size = max_body_size\n self.code = None # type: Optional[int]\n self.headers = None # type: Optional[httputil.HTTPHeaders]\n self.chunks = [] # type: List[bytes]\n self._decompressor = None\n # Timeout handle returned by IOLoop.add_timeout\n self._timeout = None # type: object\n self._sockaddr = None\n IOLoop.current().add_future(\n gen.convert_yielded(self.run()), lambda f: f.result()\n )\n\n def data_received(self, chunk: bytes) -> None:\n if self._should_follow_redirect():\n # We're going to follow a redirect so just discard the body.\n return\n if self.request.streaming_callback is not None:\n self.request.streaming_callback(chunk)\n else:\n self.chunks.append(chunk)", "has_branch": true, "total_branches": 2} {"prompt_id": 749, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()", "focal_method_lines": [54, 72], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()", "has_branch": false, "total_branches": 0} {"prompt_id": 750, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "split", "focal_method_txt": " @staticmethod\n def split(\n addrinfo: List[Tuple],\n ) -> Tuple[\n List[Tuple[socket.AddressFamily, Tuple]],\n List[Tuple[socket.AddressFamily, Tuple]],\n ]:\n \"\"\"Partition the ``addrinfo`` list by address family.\n\n Returns two lists. The first list contains the first entry from\n ``addrinfo`` and all others with the same family, and the\n second list contains all other addresses (normally one list will\n be AF_INET and the other AF_INET6, although non-standard resolvers\n may return additional families).\n \"\"\"\n primary = []\n secondary = []\n primary_af = addrinfo[0][0]\n for af, addr in addrinfo:\n if af == primary_af:\n primary.append((af, addr))\n else:\n secondary.append((af, addr))\n return primary, secondary", "focal_method_lines": [75, 97], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n @staticmethod\n def split(\n addrinfo: List[Tuple],\n ) -> Tuple[\n List[Tuple[socket.AddressFamily, Tuple]],\n List[Tuple[socket.AddressFamily, Tuple]],\n ]:\n \"\"\"Partition the ``addrinfo`` list by address family.\n\n Returns two lists. The first list contains the first entry from\n ``addrinfo`` and all others with the same family, and the\n second list contains all other addresses (normally one list will\n be AF_INET and the other AF_INET6, although non-standard resolvers\n may return additional families).\n \"\"\"\n primary = []\n secondary = []\n primary_af = addrinfo[0][0]\n for af, addr in addrinfo:\n if af == primary_af:\n primary.append((af, addr))\n else:\n secondary.append((af, addr))\n return primary, secondary", "has_branch": true, "total_branches": 2} {"prompt_id": 751, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "start", "focal_method_txt": " def start(\n self,\n timeout: float = _INITIAL_CONNECT_TIMEOUT,\n connect_timeout: Optional[Union[float, datetime.timedelta]] = None,\n ) -> \"Future[Tuple[socket.AddressFamily, Any, IOStream]]\":\n self.try_connect(iter(self.primary_addrs))\n self.set_timeout(timeout)\n if connect_timeout is not None:\n self.set_connect_timeout(connect_timeout)\n return self.future", "focal_method_lines": [99, 108], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def start(\n self,\n timeout: float = _INITIAL_CONNECT_TIMEOUT,\n connect_timeout: Optional[Union[float, datetime.timedelta]] = None,\n ) -> \"Future[Tuple[socket.AddressFamily, Any, IOStream]]\":\n self.try_connect(iter(self.primary_addrs))\n self.set_timeout(timeout)\n if connect_timeout is not None:\n self.set_connect_timeout(connect_timeout)\n return self.future", "has_branch": true, "total_branches": 2} {"prompt_id": 752, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "try_connect", "focal_method_txt": " def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:\n try:\n af, addr = next(addrs)\n except StopIteration:\n # We've reached the end of our queue, but the other queue\n # might still be working. Send a final error on the future\n # only when both queues are finished.\n if self.remaining == 0 and not self.future.done():\n self.future.set_exception(\n self.last_error or IOError(\"connection failed\")\n )\n return\n stream, future = self.connect(af, addr)\n self.streams.add(stream)\n future_add_done_callback(\n future, functools.partial(self.on_connect_done, addrs, af, addr)\n )", "focal_method_lines": [110, 124], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:\n try:\n af, addr = next(addrs)\n except StopIteration:\n # We've reached the end of our queue, but the other queue\n # might still be working. Send a final error on the future\n # only when both queues are finished.\n if self.remaining == 0 and not self.future.done():\n self.future.set_exception(\n self.last_error or IOError(\"connection failed\")\n )\n return\n stream, future = self.connect(af, addr)\n self.streams.add(stream)\n future_add_done_callback(\n future, functools.partial(self.on_connect_done, addrs, af, addr)\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 753, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "on_connect_done", "focal_method_txt": " def on_connect_done(\n self,\n addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],\n af: socket.AddressFamily,\n addr: Tuple,\n future: \"Future[IOStream]\",\n ) -> None:\n self.remaining -= 1\n try:\n stream = future.result()\n except Exception as e:\n if self.future.done():\n return\n # Error: try again (but remember what happened so we have an\n # error to raise in the end)\n self.last_error = e\n self.try_connect(addrs)\n if self.timeout is not None:\n # If the first attempt failed, don't wait for the\n # timeout to try an address from the secondary queue.\n self.io_loop.remove_timeout(self.timeout)\n self.on_timeout()\n return\n self.clear_timeouts()\n if self.future.done():\n # This is a late arrival; just drop it.\n stream.close()\n else:\n self.streams.discard(stream)\n self.future.set_result((af, addr, stream))\n self.close_streams()", "focal_method_lines": [128, 158], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def on_connect_done(\n self,\n addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],\n af: socket.AddressFamily,\n addr: Tuple,\n future: \"Future[IOStream]\",\n ) -> None:\n self.remaining -= 1\n try:\n stream = future.result()\n except Exception as e:\n if self.future.done():\n return\n # Error: try again (but remember what happened so we have an\n # error to raise in the end)\n self.last_error = e\n self.try_connect(addrs)\n if self.timeout is not None:\n # If the first attempt failed, don't wait for the\n # timeout to try an address from the secondary queue.\n self.io_loop.remove_timeout(self.timeout)\n self.on_timeout()\n return\n self.clear_timeouts()\n if self.future.done():\n # This is a late arrival; just drop it.\n stream.close()\n else:\n self.streams.discard(stream)\n self.future.set_result((af, addr, stream))\n self.close_streams()", "has_branch": true, "total_branches": 2} {"prompt_id": 754, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "set_timeout", "focal_method_txt": " def set_timeout(self, timeout: float) -> None:\n self.timeout = self.io_loop.add_timeout(\n self.io_loop.time() + timeout, self.on_timeout\n )", "focal_method_lines": [160, 161], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def set_timeout(self, timeout: float) -> None:\n self.timeout = self.io_loop.add_timeout(\n self.io_loop.time() + timeout, self.on_timeout\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 755, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "on_timeout", "focal_method_txt": " def on_timeout(self) -> None:\n self.timeout = None\n if not self.future.done():\n self.try_connect(iter(self.secondary_addrs))", "focal_method_lines": [165, 168], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def on_timeout(self) -> None:\n self.timeout = None\n if not self.future.done():\n self.try_connect(iter(self.secondary_addrs))", "has_branch": true, "total_branches": 2} {"prompt_id": 756, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "clear_timeout", "focal_method_txt": " def clear_timeout(self) -> None:\n if self.timeout is not None:\n self.io_loop.remove_timeout(self.timeout)", "focal_method_lines": [170, 172], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def clear_timeout(self) -> None:\n if self.timeout is not None:\n self.io_loop.remove_timeout(self.timeout)", "has_branch": true, "total_branches": 2} {"prompt_id": 757, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "set_connect_timeout", "focal_method_txt": " def set_connect_timeout(\n self, connect_timeout: Union[float, datetime.timedelta]\n ) -> None:\n self.connect_timeout = self.io_loop.add_timeout(\n connect_timeout, self.on_connect_timeout\n )", "focal_method_lines": [174, 177], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def set_connect_timeout(\n self, connect_timeout: Union[float, datetime.timedelta]\n ) -> None:\n self.connect_timeout = self.io_loop.add_timeout(\n connect_timeout, self.on_connect_timeout\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 758, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "on_connect_timeout", "focal_method_txt": " def on_connect_timeout(self) -> None:\n if not self.future.done():\n self.future.set_exception(TimeoutError())\n self.close_streams()", "focal_method_lines": [181, 184], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def on_connect_timeout(self) -> None:\n if not self.future.done():\n self.future.set_exception(TimeoutError())\n self.close_streams()", "has_branch": true, "total_branches": 2} {"prompt_id": 759, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "clear_timeouts", "focal_method_txt": " def clear_timeouts(self) -> None:\n if self.timeout is not None:\n self.io_loop.remove_timeout(self.timeout)\n if self.connect_timeout is not None:\n self.io_loop.remove_timeout(self.connect_timeout)", "focal_method_lines": [186, 190], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def clear_timeouts(self) -> None:\n if self.timeout is not None:\n self.io_loop.remove_timeout(self.timeout)\n if self.connect_timeout is not None:\n self.io_loop.remove_timeout(self.connect_timeout)", "has_branch": true, "total_branches": 2} {"prompt_id": 760, "project": "tornado", "module": "tornado.tcpclient", "class": "_Connector", "method": "close_streams", "focal_method_txt": " def close_streams(self) -> None:\n for stream in self.streams:\n stream.close()", "focal_method_lines": [192, 194], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\n def close_streams(self) -> None:\n for stream in self.streams:\n stream.close()", "has_branch": true, "total_branches": 2} {"prompt_id": 761, "project": "tornado", "module": "tornado.tcpclient", "class": "TCPClient", "method": "connect", "focal_method_txt": " async def connect(\n self,\n host: str,\n port: int,\n af: socket.AddressFamily = socket.AF_UNSPEC,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n max_buffer_size: Optional[int] = None,\n source_ip: Optional[str] = None,\n source_port: Optional[int] = None,\n timeout: Optional[Union[float, datetime.timedelta]] = None,\n ) -> IOStream:\n \"\"\"Connect to the given host and port.\n\n Asynchronously returns an `.IOStream` (or `.SSLIOStream` if\n ``ssl_options`` is not None).\n\n Using the ``source_ip`` kwarg, one can specify the source\n IP address to use when establishing the connection.\n In case the user needs to resolve and\n use a specific interface, it has to be handled outside\n of Tornado as this depends very much on the platform.\n\n Raises `TimeoutError` if the input future does not complete before\n ``timeout``, which may be specified in any form allowed by\n `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n relative to `.IOLoop.time`)\n\n Similarly, when the user requires a certain source port, it can\n be specified using the ``source_port`` arg.\n\n .. versionchanged:: 4.5\n Added the ``source_ip`` and ``source_port`` arguments.\n\n .. versionchanged:: 5.0\n Added the ``timeout`` argument.\n \"\"\"\n if timeout is not None:\n if isinstance(timeout, numbers.Real):\n timeout = IOLoop.current().time() + timeout\n elif isinstance(timeout, datetime.timedelta):\n timeout = IOLoop.current().time() + timeout.total_seconds()\n else:\n raise TypeError(\"Unsupported timeout %r\" % timeout)\n if timeout is not None:\n addrinfo = await gen.with_timeout(\n timeout, self.resolver.resolve(host, port, af)\n )\n else:\n addrinfo = await self.resolver.resolve(host, port, af)\n connector = _Connector(\n addrinfo,\n functools.partial(\n self._create_stream,\n max_buffer_size,\n source_ip=source_ip,\n source_port=source_port,\n ),\n )\n af, addr, stream = await connector.start(connect_timeout=timeout)\n # TODO: For better performance we could cache the (af, addr)\n # information here and re-use it on subsequent connections to\n # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)\n if ssl_options is not None:\n if timeout is not None:\n stream = await gen.with_timeout(\n timeout,\n stream.start_tls(\n False, ssl_options=ssl_options, server_hostname=host\n ),\n )\n else:\n stream = await stream.start_tls(\n False, ssl_options=ssl_options, server_hostname=host\n )\n return stream", "focal_method_lines": [216, 290], "in_stack": false, "globals": ["_INITIAL_CONNECT_TIMEOUT"], "type_context": "import functools\nimport socket\nimport numbers\nimport datetime\nimport ssl\nfrom tornado.concurrent import Future, future_add_done_callback\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado import gen\nfrom tornado.netutil import Resolver\nfrom tornado.gen import TimeoutError\nfrom typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set\n\n_INITIAL_CONNECT_TIMEOUT = 0.3\n\nclass _Connector(object):\n\n def __init__(\n self,\n addrinfo: List[Tuple],\n connect: Callable[\n [socket.AddressFamily, Tuple], Tuple[IOStream, \"Future[IOStream]\"]\n ],\n ) -> None:\n self.io_loop = IOLoop.current()\n self.connect = connect\n\n self.future = (\n Future()\n ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]\n self.timeout = None # type: Optional[object]\n self.connect_timeout = None # type: Optional[object]\n self.last_error = None # type: Optional[Exception]\n self.remaining = len(addrinfo)\n self.primary_addrs, self.secondary_addrs = self.split(addrinfo)\n self.streams = set()\n\nclass TCPClient(object):\n\n def __init__(self, resolver: Optional[Resolver] = None) -> None:\n if resolver is not None:\n self.resolver = resolver\n self._own_resolver = False\n else:\n self.resolver = Resolver()\n self._own_resolver = True\n\n async def connect(\n self,\n host: str,\n port: int,\n af: socket.AddressFamily = socket.AF_UNSPEC,\n ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,\n max_buffer_size: Optional[int] = None,\n source_ip: Optional[str] = None,\n source_port: Optional[int] = None,\n timeout: Optional[Union[float, datetime.timedelta]] = None,\n ) -> IOStream:\n \"\"\"Connect to the given host and port.\n\n Asynchronously returns an `.IOStream` (or `.SSLIOStream` if\n ``ssl_options`` is not None).\n\n Using the ``source_ip`` kwarg, one can specify the source\n IP address to use when establishing the connection.\n In case the user needs to resolve and\n use a specific interface, it has to be handled outside\n of Tornado as this depends very much on the platform.\n\n Raises `TimeoutError` if the input future does not complete before\n ``timeout``, which may be specified in any form allowed by\n `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n relative to `.IOLoop.time`)\n\n Similarly, when the user requires a certain source port, it can\n be specified using the ``source_port`` arg.\n\n .. versionchanged:: 4.5\n Added the ``source_ip`` and ``source_port`` arguments.\n\n .. versionchanged:: 5.0\n Added the ``timeout`` argument.\n \"\"\"\n if timeout is not None:\n if isinstance(timeout, numbers.Real):\n timeout = IOLoop.current().time() + timeout\n elif isinstance(timeout, datetime.timedelta):\n timeout = IOLoop.current().time() + timeout.total_seconds()\n else:\n raise TypeError(\"Unsupported timeout %r\" % timeout)\n if timeout is not None:\n addrinfo = await gen.with_timeout(\n timeout, self.resolver.resolve(host, port, af)\n )\n else:\n addrinfo = await self.resolver.resolve(host, port, af)\n connector = _Connector(\n addrinfo,\n functools.partial(\n self._create_stream,\n max_buffer_size,\n source_ip=source_ip,\n source_port=source_port,\n ),\n )\n af, addr, stream = await connector.start(connect_timeout=timeout)\n # TODO: For better performance we could cache the (af, addr)\n # information here and re-use it on subsequent connections to\n # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)\n if ssl_options is not None:\n if timeout is not None:\n stream = await gen.with_timeout(\n timeout,\n stream.start_tls(\n False, ssl_options=ssl_options, server_hostname=host\n ),\n )\n else:\n stream = await stream.start_tls(\n False, ssl_options=ssl_options, server_hostname=host\n )\n return stream", "has_branch": true, "total_branches": 2} {"prompt_id": 762, "project": "tornado", "module": "tornado.util", "class": "", "method": "import_object", "focal_method_txt": "def import_object(name: str) -> Any:\n \"\"\"Imports an object by name.\n\n ``import_object('x')`` is equivalent to ``import x``.\n ``import_object('x.y.z')`` is equivalent to ``from x.y import z``.\n\n >>> import tornado.escape\n >>> import_object('tornado.escape') is tornado.escape\n True\n >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n True\n >>> import_object('tornado') is tornado\n True\n >>> import_object('tornado.missing_module')\n Traceback (most recent call last):\n ...\n ImportError: No module named missing_module\n \"\"\"\n if name.count(\".\") == 0:\n return __import__(name)\n\n parts = name.split(\".\")\n obj = __import__(\".\".join(parts[:-1]), fromlist=[parts[-1]])\n try:\n return getattr(obj, parts[-1])\n except AttributeError:\n raise ImportError(\"No module named %s\" % parts[-1])", "focal_method_lines": [130, 156], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\ndef import_object(name: str) -> Any:\n \"\"\"Imports an object by name.\n\n ``import_object('x')`` is equivalent to ``import x``.\n ``import_object('x.y.z')`` is equivalent to ``from x.y import z``.\n\n >>> import tornado.escape\n >>> import_object('tornado.escape') is tornado.escape\n True\n >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n True\n >>> import_object('tornado') is tornado\n True\n >>> import_object('tornado.missing_module')\n Traceback (most recent call last):\n ...\n ImportError: No module named missing_module\n \"\"\"\n if name.count(\".\") == 0:\n return __import__(name)\n\n parts = name.split(\".\")\n obj = __import__(\".\".join(parts[:-1]), fromlist=[parts[-1]])\n try:\n return getattr(obj, parts[-1])\n except AttributeError:\n raise ImportError(\"No module named %s\" % parts[-1])", "has_branch": true, "total_branches": 2} {"prompt_id": 763, "project": "tornado", "module": "tornado.util", "class": "", "method": "raise_exc_info", "focal_method_txt": "def raise_exc_info(\n exc_info, # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]\n):\n # type: (...) -> typing.NoReturn\n #\n # This function's type annotation must use comments instead of\n # real annotations because typing.NoReturn does not exist in\n # python 3.5's typing module. The formatting is funky because this\n # is apparently what flake8 wants.\n try:\n if exc_info[1] is not None:\n raise exc_info[1].with_traceback(exc_info[2])\n else:\n raise TypeError(\"raise_exc_info called with no exception\")\n finally:\n # Clear the traceback reference from our stack frame to\n # minimize circular references that slow down GC.\n exc_info = (None, None, None)", "focal_method_lines": [169, 186], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\ndef raise_exc_info(\n exc_info, # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]\n):\n # type: (...) -> typing.NoReturn\n #\n # This function's type annotation must use comments instead of\n # real annotations because typing.NoReturn does not exist in\n # python 3.5's typing module. The formatting is funky because this\n # is apparently what flake8 wants.\n try:\n if exc_info[1] is not None:\n raise exc_info[1].with_traceback(exc_info[2])\n else:\n raise TypeError(\"raise_exc_info called with no exception\")\n finally:\n # Clear the traceback reference from our stack frame to\n # minimize circular references that slow down GC.\n exc_info = (None, None, None)", "has_branch": true, "total_branches": 2} {"prompt_id": 764, "project": "tornado", "module": "tornado.util", "class": "", "method": "errno_from_exception", "focal_method_txt": "def errno_from_exception(e: BaseException) -> Optional[int]:\n \"\"\"Provides the errno from an Exception object.\n\n There are cases that the errno attribute was not set so we pull\n the errno out of the args but if someone instantiates an Exception\n without any args you will get a tuple error. So this function\n abstracts all that behavior to give you a safe way to get the\n errno.\n \"\"\"\n\n if hasattr(e, \"errno\"):\n return e.errno # type: ignore\n elif e.args:\n return e.args[0]\n else:\n return None", "focal_method_lines": [189, 204], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\ndef errno_from_exception(e: BaseException) -> Optional[int]:\n \"\"\"Provides the errno from an Exception object.\n\n There are cases that the errno attribute was not set so we pull\n the errno out of the args but if someone instantiates an Exception\n without any args you will get a tuple error. So this function\n abstracts all that behavior to give you a safe way to get the\n errno.\n \"\"\"\n\n if hasattr(e, \"errno\"):\n return e.errno # type: ignore\n elif e.args:\n return e.args[0]\n else:\n return None", "has_branch": true, "total_branches": 2} {"prompt_id": 765, "project": "tornado", "module": "tornado.util", "class": "ObjectDict", "method": "__getattr__", "focal_method_txt": " def __getattr__(self, name: str) -> Any:\n try:\n return self[name]\n except KeyError:\n raise AttributeError(name)", "focal_method_lines": [79, 83], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\nclass ObjectDict(Dict[str, Any]):\n\n def __getattr__(self, name: str) -> Any:\n try:\n return self[name]\n except KeyError:\n raise AttributeError(name)", "has_branch": false, "total_branches": 0} {"prompt_id": 766, "project": "tornado", "module": "tornado.util", "class": "Configurable", "method": "__new__", "focal_method_txt": " def __new__(cls, *args: Any, **kwargs: Any) -> Any:\n base = cls.configurable_base()\n init_kwargs = {} # type: Dict[str, Any]\n if cls is base:\n impl = cls.configured_class()\n if base.__impl_kwargs:\n init_kwargs.update(base.__impl_kwargs)\n else:\n impl = cls\n init_kwargs.update(kwargs)\n if impl.configurable_base() is not base:\n # The impl class is itself configurable, so recurse.\n return impl(*args, **init_kwargs)\n instance = super(Configurable, cls).__new__(impl)\n # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n # singleton magic. If we get rid of that we can switch to __init__\n # here too.\n instance.initialize(*args, **init_kwargs)\n return instance", "focal_method_lines": [270, 288], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\nclass Configurable(object):\n\n __impl_class = None\n\n __impl_kwargs = None\n\n initialize = _initialize\n\n def __new__(cls, *args: Any, **kwargs: Any) -> Any:\n base = cls.configurable_base()\n init_kwargs = {} # type: Dict[str, Any]\n if cls is base:\n impl = cls.configured_class()\n if base.__impl_kwargs:\n init_kwargs.update(base.__impl_kwargs)\n else:\n impl = cls\n init_kwargs.update(kwargs)\n if impl.configurable_base() is not base:\n # The impl class is itself configurable, so recurse.\n return impl(*args, **init_kwargs)\n instance = super(Configurable, cls).__new__(impl)\n # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n # singleton magic. If we get rid of that we can switch to __init__\n # here too.\n instance.initialize(*args, **init_kwargs)\n return instance", "has_branch": true, "total_branches": 2} {"prompt_id": 767, "project": "tornado", "module": "tornado.util", "class": "ArgReplacer", "method": "__init__", "focal_method_txt": " def __init__(self, func: Callable, name: str) -> None:\n self.name = name\n try:\n self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]\n except ValueError:\n # Not a positional parameter\n self.arg_pos = None", "focal_method_lines": [375, 381], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\nclass ArgReplacer(object):\n\n def __init__(self, func: Callable, name: str) -> None:\n self.name = name\n try:\n self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]\n except ValueError:\n # Not a positional parameter\n self.arg_pos = None", "has_branch": false, "total_branches": 0} {"prompt_id": 768, "project": "tornado", "module": "tornado.util", "class": "ArgReplacer", "method": "get_old_value", "focal_method_txt": " def get_old_value(\n self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None\n ) -> Any:\n \"\"\"Returns the old value of the named argument without replacing it.\n\n Returns ``default`` if the argument is not present.\n \"\"\"\n if self.arg_pos is not None and len(args) > self.arg_pos:\n return args[self.arg_pos]\n else:\n return kwargs.get(self.name, default)", "focal_method_lines": [398, 408], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\nclass ArgReplacer(object):\n\n def __init__(self, func: Callable, name: str) -> None:\n self.name = name\n try:\n self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]\n except ValueError:\n # Not a positional parameter\n self.arg_pos = None\n\n def get_old_value(\n self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None\n ) -> Any:\n \"\"\"Returns the old value of the named argument without replacing it.\n\n Returns ``default`` if the argument is not present.\n \"\"\"\n if self.arg_pos is not None and len(args) > self.arg_pos:\n return args[self.arg_pos]\n else:\n return kwargs.get(self.name, default)", "has_branch": true, "total_branches": 2} {"prompt_id": 769, "project": "tornado", "module": "tornado.util", "class": "ArgReplacer", "method": "replace", "focal_method_txt": " def replace(\n self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any]\n ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]:\n \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n Returns ``(old_value, args, kwargs)``. The returned ``args`` and\n ``kwargs`` objects may not be the same as the input objects, or\n the input objects may be mutated.\n\n If the named argument was not found, ``new_value`` will be added\n to ``kwargs`` and None will be returned as ``old_value``.\n \"\"\"\n if self.arg_pos is not None and len(args) > self.arg_pos:\n # The arg to replace is passed positionally\n old_value = args[self.arg_pos]\n args = list(args) # *args is normally a tuple\n args[self.arg_pos] = new_value\n else:\n # The arg to replace is either omitted or passed by keyword.\n old_value = kwargs.get(self.name)\n kwargs[self.name] = new_value\n return old_value, args, kwargs", "focal_method_lines": [410, 431], "in_stack": false, "globals": ["bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern"], "type_context": "import array\nimport atexit\nfrom inspect import getfullargspec\nimport os\nimport re\nimport typing\nimport zlib\nfrom typing import (\n Any,\n Optional,\n Dict,\n Mapping,\n List,\n Tuple,\n Match,\n Callable,\n Type,\n Sequence,\n)\n\nbytes_type = bytes\nunicode_type = str\nbasestring_type = str\n_alphanum = frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n_re_unescape_pattern = re.compile(r\"\\\\(.)\", re.DOTALL)\n\nclass ArgReplacer(object):\n\n def __init__(self, func: Callable, name: str) -> None:\n self.name = name\n try:\n self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]\n except ValueError:\n # Not a positional parameter\n self.arg_pos = None\n\n def replace(\n self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any]\n ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]:\n \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n Returns ``(old_value, args, kwargs)``. The returned ``args`` and\n ``kwargs`` objects may not be the same as the input objects, or\n the input objects may be mutated.\n\n If the named argument was not found, ``new_value`` will be added\n to ``kwargs`` and None will be returned as ``old_value``.\n \"\"\"\n if self.arg_pos is not None and len(args) > self.arg_pos:\n # The arg to replace is passed positionally\n old_value = args[self.arg_pos]\n args = list(args) # *args is normally a tuple\n args[self.arg_pos] = new_value\n else:\n # The arg to replace is either omitted or passed by keyword.\n old_value = kwargs.get(self.name)\n kwargs[self.name] = new_value\n return old_value, args, kwargs", "has_branch": true, "total_branches": 2} {"prompt_id": 770, "project": "tqdm", "module": "tqdm._tqdm_pandas", "class": "", "method": "tqdm_pandas", "focal_method_txt": "def tqdm_pandas(tclass, **tqdm_kwargs):\n \"\"\"\n Registers the given `tqdm` instance with\n `pandas.core.groupby.DataFrameGroupBy.progress_apply`.\n \"\"\"\n from tqdm import TqdmDeprecationWarning\n\n if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(\n 'tqdm_')): # delayed adapter case\n TqdmDeprecationWarning(\n \"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.\",\n fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))\n tclass.pandas(**tqdm_kwargs)\n else:\n TqdmDeprecationWarning(\n \"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.\",\n fp_write=getattr(tclass.fp, 'write', sys.stderr.write))\n type(tclass).pandas(deprecated_t=tclass)", "focal_method_lines": [6, 23], "in_stack": false, "globals": ["__author__", "__all__"], "type_context": "import sys\n\n__author__ = \"github.com/casperdcl\"\n__all__ = ['tqdm_pandas']\n\ndef tqdm_pandas(tclass, **tqdm_kwargs):\n \"\"\"\n Registers the given `tqdm` instance with\n `pandas.core.groupby.DataFrameGroupBy.progress_apply`.\n \"\"\"\n from tqdm import TqdmDeprecationWarning\n\n if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(\n 'tqdm_')): # delayed adapter case\n TqdmDeprecationWarning(\n \"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.\",\n fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))\n tclass.pandas(**tqdm_kwargs)\n else:\n TqdmDeprecationWarning(\n \"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.\",\n fp_write=getattr(tclass.fp, 'write', sys.stderr.write))\n type(tclass).pandas(deprecated_t=tclass)", "has_branch": true, "total_branches": 2} {"prompt_id": 771, "project": "tqdm", "module": "tqdm.contrib.itertools", "class": "", "method": "product", "focal_method_txt": "def product(*iterables, **tqdm_kwargs):\n \"\"\"\n Equivalent of `itertools.product`.\n\n Parameters\n ----------\n tqdm_class : [default: tqdm.auto.tqdm].\n \"\"\"\n kwargs = tqdm_kwargs.copy()\n tqdm_class = kwargs.pop(\"tqdm_class\", tqdm_auto)\n try:\n lens = list(map(len, iterables))\n except TypeError:\n total = None\n else:\n total = 1\n for i in lens:\n total *= i\n kwargs.setdefault(\"total\", total)\n with tqdm_class(**kwargs) as t:\n for i in itertools.product(*iterables):\n yield i\n t.update()", "focal_method_lines": [13, 35], "in_stack": false, "globals": ["__author__", "__all__"], "type_context": "import itertools\nfrom ..auto import tqdm as tqdm_auto\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['product']\n\ndef product(*iterables, **tqdm_kwargs):\n \"\"\"\n Equivalent of `itertools.product`.\n\n Parameters\n ----------\n tqdm_class : [default: tqdm.auto.tqdm].\n \"\"\"\n kwargs = tqdm_kwargs.copy()\n tqdm_class = kwargs.pop(\"tqdm_class\", tqdm_auto)\n try:\n lens = list(map(len, iterables))\n except TypeError:\n total = None\n else:\n total = 1\n for i in lens:\n total *= i\n kwargs.setdefault(\"total\", total)\n with tqdm_class(**kwargs) as t:\n for i in itertools.product(*iterables):\n yield i\n t.update()", "has_branch": true, "total_branches": 2} {"prompt_id": 772, "project": "tqdm", "module": "tqdm.contrib.logging", "class": "_TqdmLoggingHandler", "method": "emit", "focal_method_txt": " def emit(self, record):\n try:\n msg = self.format(record)\n self.tqdm_class.write(msg, file=self.stream)\n self.flush()\n except (KeyboardInterrupt, SystemExit):\n raise\n except: # noqa pylint: disable=bare-except\n self.handleError(record)", "focal_method_lines": [25, 33], "in_stack": false, "globals": [], "type_context": "import logging\nimport sys\nfrom contextlib import contextmanager\nfrom ..std import tqdm as std_tqdm\n\n\n\nclass _TqdmLoggingHandler(logging.StreamHandler):\n\n def __init__(\n self,\n tqdm_class=std_tqdm # type: Type[std_tqdm]\n ):\n super(_TqdmLoggingHandler, self).__init__()\n self.tqdm_class = tqdm_class\n\n def emit(self, record):\n try:\n msg = self.format(record)\n self.tqdm_class.write(msg, file=self.stream)\n self.flush()\n except (KeyboardInterrupt, SystemExit):\n raise\n except: # noqa pylint: disable=bare-except\n self.handleError(record)", "has_branch": false, "total_branches": 0} {"prompt_id": 773, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "TelegramIO", "method": "write", "focal_method_txt": " def write(self, s):\n \"\"\"Replaces internal `message_id`'s text with `s`.\"\"\"\n if not s:\n s = \"...\"\n s = s.replace('\\r', '').strip()\n if s == self.text:\n return # avoid duplicate message Bot error\n message_id = self.message_id\n if message_id is None:\n return\n self.text = s\n try:\n future = self.submit(\n self.session.post, self.API + '%s/editMessageText' % self.token,\n data={'text': '`' + s + '`', 'chat_id': self.chat_id,\n 'message_id': message_id, 'parse_mode': 'MarkdownV2'})\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n return future", "focal_method_lines": [58, 77], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass TelegramIO(MonoWorker):\n\n API = 'https://api.telegram.org/bot'\n\n def __init__(self, token, chat_id):\n \"\"\"Creates a new message in the given `chat_id`.\"\"\"\n super(TelegramIO, self).__init__()\n self.token = token\n self.chat_id = chat_id\n self.session = Session()\n self.text = self.__class__.__name__\n self.message_id\n\n def write(self, s):\n \"\"\"Replaces internal `message_id`'s text with `s`.\"\"\"\n if not s:\n s = \"...\"\n s = s.replace('\\r', '').strip()\n if s == self.text:\n return # avoid duplicate message Bot error\n message_id = self.message_id\n if message_id is None:\n return\n self.text = s\n try:\n future = self.submit(\n self.session.post, self.API + '%s/editMessageText' % self.token,\n data={'text': '`' + s + '`', 'chat_id': self.chat_id,\n 'message_id': message_id, 'parse_mode': 'MarkdownV2'})\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n return future", "has_branch": true, "total_branches": 2} {"prompt_id": 774, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "TelegramIO", "method": "delete", "focal_method_txt": " def delete(self):\n \"\"\"Deletes internal `message_id`.\"\"\"\n try:\n future = self.submit(\n self.session.post, self.API + '%s/deleteMessage' % self.token,\n data={'chat_id': self.chat_id, 'message_id': self.message_id})\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n return future", "focal_method_lines": [79, 88], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass TelegramIO(MonoWorker):\n\n API = 'https://api.telegram.org/bot'\n\n def __init__(self, token, chat_id):\n \"\"\"Creates a new message in the given `chat_id`.\"\"\"\n super(TelegramIO, self).__init__()\n self.token = token\n self.chat_id = chat_id\n self.session = Session()\n self.text = self.__class__.__name__\n self.message_id\n\n def delete(self):\n \"\"\"Deletes internal `message_id`.\"\"\"\n try:\n future = self.submit(\n self.session.post, self.API + '%s/deleteMessage' % self.token,\n data={'chat_id': self.chat_id, 'message_id': self.message_id})\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n return future", "has_branch": false, "total_branches": 0} {"prompt_id": 775, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "tqdm_telegram", "method": "__init__", "focal_method_txt": " def __init__(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n token : str, required. Telegram token\n [default: ${TQDM_TELEGRAM_TOKEN}].\n chat_id : str, required. Telegram chat ID\n [default: ${TQDM_TELEGRAM_CHAT_ID}].\n\n See `tqdm.auto.tqdm.__init__` for other parameters.\n \"\"\"\n if not kwargs.get('disable'):\n kwargs = kwargs.copy()\n self.tgio = TelegramIO(\n kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),\n kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))\n super(tqdm_telegram, self).__init__(*args, **kwargs)", "focal_method_lines": [107, 123], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass TelegramIO(MonoWorker):\n\n API = 'https://api.telegram.org/bot'\n\n def __init__(self, token, chat_id):\n \"\"\"Creates a new message in the given `chat_id`.\"\"\"\n super(TelegramIO, self).__init__()\n self.token = token\n self.chat_id = chat_id\n self.session = Session()\n self.text = self.__class__.__name__\n self.message_id\n\nclass tqdm_telegram(tqdm_auto):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n token : str, required. Telegram token\n [default: ${TQDM_TELEGRAM_TOKEN}].\n chat_id : str, required. Telegram chat ID\n [default: ${TQDM_TELEGRAM_CHAT_ID}].\n\n See `tqdm.auto.tqdm.__init__` for other parameters.\n \"\"\"\n if not kwargs.get('disable'):\n kwargs = kwargs.copy()\n self.tgio = TelegramIO(\n kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),\n kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))\n super(tqdm_telegram, self).__init__(*args, **kwargs)", "has_branch": true, "total_branches": 2} {"prompt_id": 776, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "tqdm_telegram", "method": "display", "focal_method_txt": " def display(self, **kwargs):\n super(tqdm_telegram, self).display(**kwargs)\n fmt = self.format_dict\n if fmt.get('bar_format', None):\n fmt['bar_format'] = fmt['bar_format'].replace(\n '', '{bar:10u}').replace('{bar}', '{bar:10u}')\n else:\n fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'\n self.tgio.write(self.format_meter(**fmt))", "focal_method_lines": [125, 133], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass tqdm_telegram(tqdm_auto):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n token : str, required. Telegram token\n [default: ${TQDM_TELEGRAM_TOKEN}].\n chat_id : str, required. Telegram chat ID\n [default: ${TQDM_TELEGRAM_CHAT_ID}].\n\n See `tqdm.auto.tqdm.__init__` for other parameters.\n \"\"\"\n if not kwargs.get('disable'):\n kwargs = kwargs.copy()\n self.tgio = TelegramIO(\n kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),\n kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))\n super(tqdm_telegram, self).__init__(*args, **kwargs)\n\n def display(self, **kwargs):\n super(tqdm_telegram, self).display(**kwargs)\n fmt = self.format_dict\n if fmt.get('bar_format', None):\n fmt['bar_format'] = fmt['bar_format'].replace(\n '', '{bar:10u}').replace('{bar}', '{bar:10u}')\n else:\n fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'\n self.tgio.write(self.format_meter(**fmt))", "has_branch": true, "total_branches": 2} {"prompt_id": 777, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "tqdm_telegram", "method": "clear", "focal_method_txt": " def clear(self, *args, **kwargs):\n super(tqdm_telegram, self).clear(*args, **kwargs)\n if not self.disable:\n self.tgio.write(\"\")", "focal_method_lines": [135, 138], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass tqdm_telegram(tqdm_auto):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n token : str, required. Telegram token\n [default: ${TQDM_TELEGRAM_TOKEN}].\n chat_id : str, required. Telegram chat ID\n [default: ${TQDM_TELEGRAM_CHAT_ID}].\n\n See `tqdm.auto.tqdm.__init__` for other parameters.\n \"\"\"\n if not kwargs.get('disable'):\n kwargs = kwargs.copy()\n self.tgio = TelegramIO(\n kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),\n kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))\n super(tqdm_telegram, self).__init__(*args, **kwargs)\n\n def clear(self, *args, **kwargs):\n super(tqdm_telegram, self).clear(*args, **kwargs)\n if not self.disable:\n self.tgio.write(\"\")", "has_branch": true, "total_branches": 2} {"prompt_id": 778, "project": "tqdm", "module": "tqdm.contrib.telegram", "class": "tqdm_telegram", "method": "close", "focal_method_txt": " def close(self):\n if self.disable:\n return\n super(tqdm_telegram, self).close()\n if not (self.leave or (self.leave is None and self.pos == 0)):\n self.tgio.delete()", "focal_method_lines": [140, 145], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from os import getenv\nfrom warnings import warn\nfrom requests import Session\nfrom ..auto import tqdm as tqdm_auto\nfrom ..std import TqdmWarning\nfrom ..utils import _range\nfrom .utils_worker import MonoWorker\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']\ntqdm = tqdm_telegram\ntrange = ttgrange\n\nclass tqdm_telegram(tqdm_auto):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n token : str, required. Telegram token\n [default: ${TQDM_TELEGRAM_TOKEN}].\n chat_id : str, required. Telegram chat ID\n [default: ${TQDM_TELEGRAM_CHAT_ID}].\n\n See `tqdm.auto.tqdm.__init__` for other parameters.\n \"\"\"\n if not kwargs.get('disable'):\n kwargs = kwargs.copy()\n self.tgio = TelegramIO(\n kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),\n kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))\n super(tqdm_telegram, self).__init__(*args, **kwargs)\n\n def close(self):\n if self.disable:\n return\n super(tqdm_telegram, self).close()\n if not (self.leave or (self.leave is None and self.pos == 0)):\n self.tgio.delete()", "has_branch": true, "total_branches": 2} {"prompt_id": 779, "project": "tqdm", "module": "tqdm.contrib.utils_worker", "class": "MonoWorker", "method": "submit", "focal_method_txt": " def submit(self, func, *args, **kwargs):\n \"\"\"`func(*args, **kwargs)` may replace currently waiting task.\"\"\"\n futures = self.futures\n if len(futures) == futures.maxlen:\n running = futures.popleft()\n if not running.done():\n if len(futures): # clear waiting\n waiting = futures.pop()\n waiting.cancel()\n futures.appendleft(running) # re-insert running\n try:\n waiting = self.pool.submit(func, *args, **kwargs)\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n futures.append(waiting)\n return waiting", "focal_method_lines": [23, 39], "in_stack": false, "globals": ["__author__", "__all__"], "type_context": "from collections import deque\nfrom concurrent.futures import ThreadPoolExecutor\nfrom ..auto import tqdm as tqdm_auto\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['MonoWorker']\n\nclass MonoWorker(object):\n\n def __init__(self):\n self.pool = ThreadPoolExecutor(max_workers=1)\n self.futures = deque([], 2)\n\n def submit(self, func, *args, **kwargs):\n \"\"\"`func(*args, **kwargs)` may replace currently waiting task.\"\"\"\n futures = self.futures\n if len(futures) == futures.maxlen:\n running = futures.popleft()\n if not running.done():\n if len(futures): # clear waiting\n waiting = futures.pop()\n waiting.cancel()\n futures.appendleft(running) # re-insert running\n try:\n waiting = self.pool.submit(func, *args, **kwargs)\n except Exception as e:\n tqdm_auto.write(str(e))\n else:\n futures.append(waiting)\n return waiting", "has_branch": true, "total_branches": 2} {"prompt_id": 780, "project": "tqdm", "module": "tqdm.gui", "class": "tqdm_gui", "method": "__init__", "focal_method_txt": " def __init__(self, *args, **kwargs):\n from collections import deque\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n colour = kwargs.pop('colour', 'g')\n super(tqdm_gui, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"GUI is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n self.mpl = mpl\n self.plt = plt\n\n # Remember if external environment uses toolbars\n self.toolbar = self.mpl.rcParams['toolbar']\n self.mpl.rcParams['toolbar'] = 'None'\n\n self.mininterval = max(self.mininterval, 0.5)\n self.fig, ax = plt.subplots(figsize=(9, 2.2))\n # self.fig.subplots_adjust(bottom=0.2)\n total = self.__len__() # avoids TypeError on None #971\n if total is not None:\n self.xdata = []\n self.ydata = []\n self.zdata = []\n else:\n self.xdata = deque([])\n self.ydata = deque([])\n self.zdata = deque([])\n self.line1, = ax.plot(self.xdata, self.ydata, color='b')\n self.line2, = ax.plot(self.xdata, self.zdata, color='k')\n ax.set_ylim(0, 0.001)\n if total is not None:\n ax.set_xlim(0, 100)\n ax.set_xlabel(\"percent\")\n self.fig.legend((self.line1, self.line2), (\"cur\", \"est\"),\n loc='center right')\n # progressbar\n self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)\n else:\n # ax.set_xlim(-60, 0)\n ax.set_xlim(0, 60)\n ax.invert_xaxis()\n ax.set_xlabel(\"seconds\")\n ax.legend((\"cur\", \"est\"), loc='lower left')\n ax.grid()\n # ax.set_xlabel('seconds')\n ax.set_ylabel((self.unit if self.unit else \"it\") + \"/s\")\n if self.unit_scale:\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.yaxis.get_offset_text().set_x(-0.15)\n\n # Remember if external environment is interactive\n self.wasion = plt.isinteractive()\n plt.ion()\n self.ax = ax", "focal_method_lines": [28, 87], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nfrom warnings import warn\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\", \"lrq3000\"]}\n__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']\ntqdm = tqdm_gui\ntrange = tgrange\n\nclass tqdm_gui(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n from collections import deque\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n colour = kwargs.pop('colour', 'g')\n super(tqdm_gui, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"GUI is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n self.mpl = mpl\n self.plt = plt\n\n # Remember if external environment uses toolbars\n self.toolbar = self.mpl.rcParams['toolbar']\n self.mpl.rcParams['toolbar'] = 'None'\n\n self.mininterval = max(self.mininterval, 0.5)\n self.fig, ax = plt.subplots(figsize=(9, 2.2))\n # self.fig.subplots_adjust(bottom=0.2)\n total = self.__len__() # avoids TypeError on None #971\n if total is not None:\n self.xdata = []\n self.ydata = []\n self.zdata = []\n else:\n self.xdata = deque([])\n self.ydata = deque([])\n self.zdata = deque([])\n self.line1, = ax.plot(self.xdata, self.ydata, color='b')\n self.line2, = ax.plot(self.xdata, self.zdata, color='k')\n ax.set_ylim(0, 0.001)\n if total is not None:\n ax.set_xlim(0, 100)\n ax.set_xlabel(\"percent\")\n self.fig.legend((self.line1, self.line2), (\"cur\", \"est\"),\n loc='center right')\n # progressbar\n self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)\n else:\n # ax.set_xlim(-60, 0)\n ax.set_xlim(0, 60)\n ax.invert_xaxis()\n ax.set_xlabel(\"seconds\")\n ax.legend((\"cur\", \"est\"), loc='lower left')\n ax.grid()\n # ax.set_xlabel('seconds')\n ax.set_ylabel((self.unit if self.unit else \"it\") + \"/s\")\n if self.unit_scale:\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.yaxis.get_offset_text().set_x(-0.15)\n\n # Remember if external environment is interactive\n self.wasion = plt.isinteractive()\n plt.ion()\n self.ax = ax", "has_branch": false, "total_branches": 0} {"prompt_id": 781, "project": "tqdm", "module": "tqdm.gui", "class": "tqdm_gui", "method": "close", "focal_method_txt": " def close(self):\n if self.disable:\n return\n\n self.disable = True\n\n with self.get_lock():\n self._instances.remove(self)\n\n # Restore toolbars\n self.mpl.rcParams['toolbar'] = self.toolbar\n # Return to non-interactive mode\n if not self.wasion:\n self.plt.ioff()\n if self.leave:\n self.display()\n else:\n self.plt.close(self.fig)", "focal_method_lines": [89, 106], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nfrom warnings import warn\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\", \"lrq3000\"]}\n__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']\ntqdm = tqdm_gui\ntrange = tgrange\n\nclass tqdm_gui(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n from collections import deque\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n colour = kwargs.pop('colour', 'g')\n super(tqdm_gui, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"GUI is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n self.mpl = mpl\n self.plt = plt\n\n # Remember if external environment uses toolbars\n self.toolbar = self.mpl.rcParams['toolbar']\n self.mpl.rcParams['toolbar'] = 'None'\n\n self.mininterval = max(self.mininterval, 0.5)\n self.fig, ax = plt.subplots(figsize=(9, 2.2))\n # self.fig.subplots_adjust(bottom=0.2)\n total = self.__len__() # avoids TypeError on None #971\n if total is not None:\n self.xdata = []\n self.ydata = []\n self.zdata = []\n else:\n self.xdata = deque([])\n self.ydata = deque([])\n self.zdata = deque([])\n self.line1, = ax.plot(self.xdata, self.ydata, color='b')\n self.line2, = ax.plot(self.xdata, self.zdata, color='k')\n ax.set_ylim(0, 0.001)\n if total is not None:\n ax.set_xlim(0, 100)\n ax.set_xlabel(\"percent\")\n self.fig.legend((self.line1, self.line2), (\"cur\", \"est\"),\n loc='center right')\n # progressbar\n self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)\n else:\n # ax.set_xlim(-60, 0)\n ax.set_xlim(0, 60)\n ax.invert_xaxis()\n ax.set_xlabel(\"seconds\")\n ax.legend((\"cur\", \"est\"), loc='lower left')\n ax.grid()\n # ax.set_xlabel('seconds')\n ax.set_ylabel((self.unit if self.unit else \"it\") + \"/s\")\n if self.unit_scale:\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.yaxis.get_offset_text().set_x(-0.15)\n\n # Remember if external environment is interactive\n self.wasion = plt.isinteractive()\n plt.ion()\n self.ax = ax\n\n def close(self):\n if self.disable:\n return\n\n self.disable = True\n\n with self.get_lock():\n self._instances.remove(self)\n\n # Restore toolbars\n self.mpl.rcParams['toolbar'] = self.toolbar\n # Return to non-interactive mode\n if not self.wasion:\n self.plt.ioff()\n if self.leave:\n self.display()\n else:\n self.plt.close(self.fig)", "has_branch": false, "total_branches": 0} {"prompt_id": 782, "project": "tqdm", "module": "tqdm.gui", "class": "tqdm_gui", "method": "clear", "focal_method_txt": " def clear(self, *_, **__):\n pass", "focal_method_lines": [108, 109], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nfrom warnings import warn\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\", \"lrq3000\"]}\n__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']\ntqdm = tqdm_gui\ntrange = tgrange\n\nclass tqdm_gui(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n from collections import deque\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n colour = kwargs.pop('colour', 'g')\n super(tqdm_gui, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"GUI is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n self.mpl = mpl\n self.plt = plt\n\n # Remember if external environment uses toolbars\n self.toolbar = self.mpl.rcParams['toolbar']\n self.mpl.rcParams['toolbar'] = 'None'\n\n self.mininterval = max(self.mininterval, 0.5)\n self.fig, ax = plt.subplots(figsize=(9, 2.2))\n # self.fig.subplots_adjust(bottom=0.2)\n total = self.__len__() # avoids TypeError on None #971\n if total is not None:\n self.xdata = []\n self.ydata = []\n self.zdata = []\n else:\n self.xdata = deque([])\n self.ydata = deque([])\n self.zdata = deque([])\n self.line1, = ax.plot(self.xdata, self.ydata, color='b')\n self.line2, = ax.plot(self.xdata, self.zdata, color='k')\n ax.set_ylim(0, 0.001)\n if total is not None:\n ax.set_xlim(0, 100)\n ax.set_xlabel(\"percent\")\n self.fig.legend((self.line1, self.line2), (\"cur\", \"est\"),\n loc='center right')\n # progressbar\n self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)\n else:\n # ax.set_xlim(-60, 0)\n ax.set_xlim(0, 60)\n ax.invert_xaxis()\n ax.set_xlabel(\"seconds\")\n ax.legend((\"cur\", \"est\"), loc='lower left')\n ax.grid()\n # ax.set_xlabel('seconds')\n ax.set_ylabel((self.unit if self.unit else \"it\") + \"/s\")\n if self.unit_scale:\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.yaxis.get_offset_text().set_x(-0.15)\n\n # Remember if external environment is interactive\n self.wasion = plt.isinteractive()\n plt.ion()\n self.ax = ax\n\n def clear(self, *_, **__):\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 783, "project": "tqdm", "module": "tqdm.gui", "class": "tqdm_gui", "method": "display", "focal_method_txt": " def display(self, *_, **__):\n n = self.n\n cur_t = self._time()\n elapsed = cur_t - self.start_t\n delta_it = n - self.last_print_n\n delta_t = cur_t - self.last_print_t\n\n # Inline due to multiple calls\n total = self.total\n xdata = self.xdata\n ydata = self.ydata\n zdata = self.zdata\n ax = self.ax\n line1 = self.line1\n line2 = self.line2\n # instantaneous rate\n y = delta_it / delta_t\n # overall rate\n z = n / elapsed\n # update line data\n xdata.append(n * 100.0 / total if total else cur_t)\n ydata.append(y)\n zdata.append(z)\n\n # Discard old values\n # xmin, xmax = ax.get_xlim()\n # if (not total) and elapsed > xmin * 1.1:\n if (not total) and elapsed > 66:\n xdata.popleft()\n ydata.popleft()\n zdata.popleft()\n\n ymin, ymax = ax.get_ylim()\n if y > ymax or z > ymax:\n ymax = 1.1 * y\n ax.set_ylim(ymin, ymax)\n ax.figure.canvas.draw()\n\n if total:\n line1.set_data(xdata, ydata)\n line2.set_data(xdata, zdata)\n try:\n poly_lims = self.hspan.get_xy()\n except AttributeError:\n self.hspan = self.plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g')\n poly_lims = self.hspan.get_xy()\n poly_lims[0, 1] = ymin\n poly_lims[1, 1] = ymax\n poly_lims[2] = [n / total, ymax]\n poly_lims[3] = [poly_lims[2, 0], ymin]\n if len(poly_lims) > 4:\n poly_lims[4, 1] = ymin\n self.hspan.set_xy(poly_lims)\n else:\n t_ago = [cur_t - i for i in xdata]\n line1.set_data(t_ago, ydata)\n line2.set_data(t_ago, zdata)\n\n d = self.format_dict\n # remove {bar}\n d['bar_format'] = (d['bar_format'] or \"{l_bar}{r_bar}\").replace(\n \"{bar}\", \"\")\n msg = self.format_meter(**d)\n if '' in msg:\n msg = \"\".join(re.split(r'\\|?\\|?', msg, 1))\n ax.set_title(msg, fontname=\"DejaVu Sans Mono\", fontsize=11)\n self.plt.pause(1e-9)", "focal_method_lines": [111, 177], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nfrom warnings import warn\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\", \"lrq3000\"]}\n__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']\ntqdm = tqdm_gui\ntrange = tgrange\n\nclass tqdm_gui(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n from collections import deque\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n colour = kwargs.pop('colour', 'g')\n super(tqdm_gui, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"GUI is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n self.mpl = mpl\n self.plt = plt\n\n # Remember if external environment uses toolbars\n self.toolbar = self.mpl.rcParams['toolbar']\n self.mpl.rcParams['toolbar'] = 'None'\n\n self.mininterval = max(self.mininterval, 0.5)\n self.fig, ax = plt.subplots(figsize=(9, 2.2))\n # self.fig.subplots_adjust(bottom=0.2)\n total = self.__len__() # avoids TypeError on None #971\n if total is not None:\n self.xdata = []\n self.ydata = []\n self.zdata = []\n else:\n self.xdata = deque([])\n self.ydata = deque([])\n self.zdata = deque([])\n self.line1, = ax.plot(self.xdata, self.ydata, color='b')\n self.line2, = ax.plot(self.xdata, self.zdata, color='k')\n ax.set_ylim(0, 0.001)\n if total is not None:\n ax.set_xlim(0, 100)\n ax.set_xlabel(\"percent\")\n self.fig.legend((self.line1, self.line2), (\"cur\", \"est\"),\n loc='center right')\n # progressbar\n self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)\n else:\n # ax.set_xlim(-60, 0)\n ax.set_xlim(0, 60)\n ax.invert_xaxis()\n ax.set_xlabel(\"seconds\")\n ax.legend((\"cur\", \"est\"), loc='lower left')\n ax.grid()\n # ax.set_xlabel('seconds')\n ax.set_ylabel((self.unit if self.unit else \"it\") + \"/s\")\n if self.unit_scale:\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.yaxis.get_offset_text().set_x(-0.15)\n\n # Remember if external environment is interactive\n self.wasion = plt.isinteractive()\n plt.ion()\n self.ax = ax\n\n def display(self, *_, **__):\n n = self.n\n cur_t = self._time()\n elapsed = cur_t - self.start_t\n delta_it = n - self.last_print_n\n delta_t = cur_t - self.last_print_t\n\n # Inline due to multiple calls\n total = self.total\n xdata = self.xdata\n ydata = self.ydata\n zdata = self.zdata\n ax = self.ax\n line1 = self.line1\n line2 = self.line2\n # instantaneous rate\n y = delta_it / delta_t\n # overall rate\n z = n / elapsed\n # update line data\n xdata.append(n * 100.0 / total if total else cur_t)\n ydata.append(y)\n zdata.append(z)\n\n # Discard old values\n # xmin, xmax = ax.get_xlim()\n # if (not total) and elapsed > xmin * 1.1:\n if (not total) and elapsed > 66:\n xdata.popleft()\n ydata.popleft()\n zdata.popleft()\n\n ymin, ymax = ax.get_ylim()\n if y > ymax or z > ymax:\n ymax = 1.1 * y\n ax.set_ylim(ymin, ymax)\n ax.figure.canvas.draw()\n\n if total:\n line1.set_data(xdata, ydata)\n line2.set_data(xdata, zdata)\n try:\n poly_lims = self.hspan.get_xy()\n except AttributeError:\n self.hspan = self.plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g')\n poly_lims = self.hspan.get_xy()\n poly_lims[0, 1] = ymin\n poly_lims[1, 1] = ymax\n poly_lims[2] = [n / total, ymax]\n poly_lims[3] = [poly_lims[2, 0], ymin]\n if len(poly_lims) > 4:\n poly_lims[4, 1] = ymin\n self.hspan.set_xy(poly_lims)\n else:\n t_ago = [cur_t - i for i in xdata]\n line1.set_data(t_ago, ydata)\n line2.set_data(t_ago, zdata)\n\n d = self.format_dict\n # remove {bar}\n d['bar_format'] = (d['bar_format'] or \"{l_bar}{r_bar}\").replace(\n \"{bar}\", \"\")\n msg = self.format_meter(**d)\n if '' in msg:\n msg = \"\".join(re.split(r'\\|?\\|?', msg, 1))\n ax.set_title(msg, fontname=\"DejaVu Sans Mono\", fontsize=11)\n self.plt.pause(1e-9)", "has_branch": false, "total_branches": 0} {"prompt_id": 784, "project": "tqdm", "module": "tqdm.notebook", "class": "TqdmHBox", "method": "__repr__", "focal_method_txt": " def __repr__(self, pretty=False):\n pbar = getattr(self, 'pbar', None)\n if pbar is None:\n return super(TqdmHBox, self).__repr__()\n return pbar.format_meter(**self._repr_json_(pretty))", "focal_method_lines": [86, 90], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass TqdmHBox(HBox):\n\n def __repr__(self, pretty=False):\n pbar = getattr(self, 'pbar', None)\n if pbar is None:\n return super(TqdmHBox, self).__repr__()\n return pbar.format_meter(**self._repr_json_(pretty))", "has_branch": true, "total_branches": 2} {"prompt_id": 785, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "status_printer", "focal_method_txt": " @staticmethod\n def status_printer(_, total=None, desc=None, ncols=None):\n \"\"\"\n Manage the printing of an IPython/Jupyter Notebook progress bar widget.\n \"\"\"\n # Fallback to text bar if there's no total\n # DEPRECATED: replaced with an 'info' style bar\n # if not total:\n # return super(tqdm_notebook, tqdm_notebook).status_printer(file)\n\n # fp = file\n\n # Prepare IPython progress bar\n if IProgress is None: # #187 #451 #558 #872\n raise ImportError(\n \"IProgress not found. Please update jupyter and ipywidgets.\"\n \" See https://ipywidgets.readthedocs.io/en/stable\"\n \"/user_install.html\")\n if total:\n pbar = IProgress(min=0, max=total)\n else: # No total? Show info style bar with no progress tqdm status\n pbar = IProgress(min=0, max=1)\n pbar.value = 1\n pbar.bar_style = 'info'\n if ncols is None:\n pbar.layout.width = \"20px\"\n\n ltext = HTML()\n rtext = HTML()\n if desc:\n ltext.value = desc\n container = TqdmHBox(children=[ltext, pbar, rtext])\n # Prepare layout\n if ncols is not None: # use default style of ipywidgets\n # ncols could be 100, \"100px\", \"100%\"\n ncols = str(ncols) # ipywidgets only accepts string\n try:\n if int(ncols) > 0: # isnumeric and positive\n ncols += 'px'\n except ValueError:\n pass\n pbar.layout.flex = '2'\n container.layout.width = ncols\n container.layout.display = 'inline-flex'\n container.layout.flex_flow = 'row wrap'\n\n return container", "focal_method_lines": [101, 146], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n @staticmethod\n def status_printer(_, total=None, desc=None, ncols=None):\n \"\"\"\n Manage the printing of an IPython/Jupyter Notebook progress bar widget.\n \"\"\"\n # Fallback to text bar if there's no total\n # DEPRECATED: replaced with an 'info' style bar\n # if not total:\n # return super(tqdm_notebook, tqdm_notebook).status_printer(file)\n\n # fp = file\n\n # Prepare IPython progress bar\n if IProgress is None: # #187 #451 #558 #872\n raise ImportError(\n \"IProgress not found. Please update jupyter and ipywidgets.\"\n \" See https://ipywidgets.readthedocs.io/en/stable\"\n \"/user_install.html\")\n if total:\n pbar = IProgress(min=0, max=total)\n else: # No total? Show info style bar with no progress tqdm status\n pbar = IProgress(min=0, max=1)\n pbar.value = 1\n pbar.bar_style = 'info'\n if ncols is None:\n pbar.layout.width = \"20px\"\n\n ltext = HTML()\n rtext = HTML()\n if desc:\n ltext.value = desc\n container = TqdmHBox(children=[ltext, pbar, rtext])\n # Prepare layout\n if ncols is not None: # use default style of ipywidgets\n # ncols could be 100, \"100px\", \"100%\"\n ncols = str(ncols) # ipywidgets only accepts string\n try:\n if int(ncols) > 0: # isnumeric and positive\n ncols += 'px'\n except ValueError:\n pass\n pbar.layout.flex = '2'\n container.layout.width = ncols\n container.layout.display = 'inline-flex'\n container.layout.flex_flow = 'row wrap'\n\n return container", "has_branch": true, "total_branches": 2} {"prompt_id": 786, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "display", "focal_method_txt": " def display(self, msg=None, pos=None,\n # additional signals\n close=False, bar_style=None, check_delay=True):\n # Note: contrary to native tqdm, msg='' does NOT clear bar\n # goal is to keep all infos if error happens so user knows\n # at which iteration the loop failed.\n\n # Clear previous output (really necessary?)\n # clear_output(wait=1)\n\n if not msg and not close:\n d = self.format_dict\n # remove {bar}\n d['bar_format'] = (d['bar_format'] or \"{l_bar}{r_bar}\").replace(\n \"{bar}\", \"\")\n msg = self.format_meter(**d)\n\n ltext, pbar, rtext = self.container.children\n pbar.value = self.n\n\n if msg:\n # html escape special characters (like '&')\n if '' in msg:\n left, right = map(escape, re.split(r'\\|?\\|?', msg, 1))\n else:\n left, right = '', escape(msg)\n\n # Update description\n ltext.value = left\n # never clear the bar (signal: msg='')\n if right:\n rtext.value = right\n\n # Change bar style\n if bar_style:\n # Hack-ish way to avoid the danger bar_style being overridden by\n # success because the bar gets closed after the error...\n if pbar.bar_style != 'danger' or bar_style != 'success':\n pbar.bar_style = bar_style\n\n # Special signal to close the bar\n if close and pbar.bar_style != 'danger': # hide only if no error\n try:\n self.container.close()\n except AttributeError:\n self.container.visible = False\n\n if check_delay and self.delay > 0 and not self.displayed:\n display(self.container)\n self.displayed = True", "focal_method_lines": [148, 197], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def display(self, msg=None, pos=None,\n # additional signals\n close=False, bar_style=None, check_delay=True):\n # Note: contrary to native tqdm, msg='' does NOT clear bar\n # goal is to keep all infos if error happens so user knows\n # at which iteration the loop failed.\n\n # Clear previous output (really necessary?)\n # clear_output(wait=1)\n\n if not msg and not close:\n d = self.format_dict\n # remove {bar}\n d['bar_format'] = (d['bar_format'] or \"{l_bar}{r_bar}\").replace(\n \"{bar}\", \"\")\n msg = self.format_meter(**d)\n\n ltext, pbar, rtext = self.container.children\n pbar.value = self.n\n\n if msg:\n # html escape special characters (like '&')\n if '' in msg:\n left, right = map(escape, re.split(r'\\|?\\|?', msg, 1))\n else:\n left, right = '', escape(msg)\n\n # Update description\n ltext.value = left\n # never clear the bar (signal: msg='')\n if right:\n rtext.value = right\n\n # Change bar style\n if bar_style:\n # Hack-ish way to avoid the danger bar_style being overridden by\n # success because the bar gets closed after the error...\n if pbar.bar_style != 'danger' or bar_style != 'success':\n pbar.bar_style = bar_style\n\n # Special signal to close the bar\n if close and pbar.bar_style != 'danger': # hide only if no error\n try:\n self.container.close()\n except AttributeError:\n self.container.visible = False\n\n if check_delay and self.delay > 0 and not self.displayed:\n display(self.container)\n self.displayed = True", "has_branch": true, "total_branches": 2} {"prompt_id": 787, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "__init__", "focal_method_txt": " def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)", "focal_method_lines": [209, 252], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)", "has_branch": true, "total_branches": 2} {"prompt_id": 788, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "__iter__", "focal_method_txt": " def __iter__(self):\n try:\n for obj in super(tqdm_notebook, self).__iter__():\n # return super(tqdm...) will not catch exception\n yield obj\n # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\n except: # NOQA\n self.disp(bar_style='danger')\n raise\n # NB: don't `finally: close()`\n # since this could be a shared bar which the user will `reset()`", "focal_method_lines": [254, 262], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def __iter__(self):\n try:\n for obj in super(tqdm_notebook, self).__iter__():\n # return super(tqdm...) will not catch exception\n yield obj\n # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\n except: # NOQA\n self.disp(bar_style='danger')\n raise\n # NB: don't `finally: close()`\n # since this could be a shared bar which the user will `reset()`", "has_branch": true, "total_branches": 2} {"prompt_id": 789, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "update", "focal_method_txt": " def update(self, n=1):\n try:\n return super(tqdm_notebook, self).update(n=n)\n # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\n except: # NOQA\n # cannot catch KeyboardInterrupt when using manual tqdm\n # as the interrupt will most likely happen on another statement\n self.disp(bar_style='danger')\n raise\n # NB: don't `finally: close()`\n # since this could be a shared bar which the user will `reset()`", "focal_method_lines": [266, 274], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def update(self, n=1):\n try:\n return super(tqdm_notebook, self).update(n=n)\n # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt\n except: # NOQA\n # cannot catch KeyboardInterrupt when using manual tqdm\n # as the interrupt will most likely happen on another statement\n self.disp(bar_style='danger')\n raise\n # NB: don't `finally: close()`\n # since this could be a shared bar which the user will `reset()`", "has_branch": false, "total_branches": 0} {"prompt_id": 790, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "close", "focal_method_txt": " def close(self):\n if self.disable:\n return\n super(tqdm_notebook, self).close()\n # Try to detect if there was an error or KeyboardInterrupt\n # in manual mode: if n < total, things probably got wrong\n if self.total and self.n < self.total:\n self.disp(bar_style='danger', check_delay=False)\n else:\n if self.leave:\n self.disp(bar_style='success', check_delay=False)\n else:\n self.disp(close=True, check_delay=False)", "focal_method_lines": [278, 290], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def close(self):\n if self.disable:\n return\n super(tqdm_notebook, self).close()\n # Try to detect if there was an error or KeyboardInterrupt\n # in manual mode: if n < total, things probably got wrong\n if self.total and self.n < self.total:\n self.disp(bar_style='danger', check_delay=False)\n else:\n if self.leave:\n self.disp(bar_style='success', check_delay=False)\n else:\n self.disp(close=True, check_delay=False)", "has_branch": true, "total_branches": 2} {"prompt_id": 791, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "clear", "focal_method_txt": " def clear(self, *_, **__):\n pass", "focal_method_lines": [292, 293], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def clear(self, *_, **__):\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 792, "project": "tqdm", "module": "tqdm.notebook", "class": "tqdm_notebook", "method": "reset", "focal_method_txt": " def reset(self, total=None):\n \"\"\"\n Resets to 0 iterations for repeated use.\n\n Consider combining with `leave=True`.\n\n Parameters\n ----------\n total : int or float, optional. Total to use for the new bar.\n \"\"\"\n if self.disable:\n return super(tqdm_notebook, self).reset(total=total)\n _, pbar, _ = self.container.children\n pbar.bar_style = ''\n if total is not None:\n pbar.max = total\n if not self.total and self.ncols is None: # no longer unknown total\n pbar.layout.width = None # reset width\n return super(tqdm_notebook, self).reset(total=total)", "focal_method_lines": [295, 313], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "import re\nimport sys\nfrom weakref import proxy\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"lrq3000\", \"casperdcl\", \"alexanderkuk\"]}\n__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']\ntqdm = tqdm_notebook\ntrange = tnrange\n\nclass tqdm_notebook(std_tqdm):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Supports the usual `tqdm.tqdm` parameters as well as those listed below.\n\n Parameters\n ----------\n display : Whether to call `display(self.container)` immediately\n [default: True].\n \"\"\"\n kwargs = kwargs.copy()\n # Setup default output\n file_kwarg = kwargs.get('file', sys.stderr)\n if file_kwarg is sys.stderr or file_kwarg is None:\n kwargs['file'] = sys.stdout # avoid the red block in IPython\n\n # Initialize parent class + avoid printing by using gui=True\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n colour = kwargs.pop('colour', None)\n display_here = kwargs.pop('display', True)\n super(tqdm_notebook, self).__init__(*args, **kwargs)\n if self.disable or not kwargs['gui']:\n self.disp = lambda *_, **__: None\n return\n\n # Get bar width\n self.ncols = '100%' if self.dynamic_ncols else kwargs.get(\"ncols\", None)\n\n # Replace with IPython progress bar display (with correct total)\n unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1\n total = self.total * unit_scale if self.total else self.total\n self.container = self.status_printer(self.fp, total, self.desc, self.ncols)\n self.container.pbar = proxy(self)\n self.displayed = False\n if display_here and self.delay <= 0:\n display(self.container)\n self.displayed = True\n self.disp = self.display\n self.colour = colour\n\n # Print initial bar state\n if not self.disable:\n self.display(check_delay=False)\n\n def reset(self, total=None):\n \"\"\"\n Resets to 0 iterations for repeated use.\n\n Consider combining with `leave=True`.\n\n Parameters\n ----------\n total : int or float, optional. Total to use for the new bar.\n \"\"\"\n if self.disable:\n return super(tqdm_notebook, self).reset(total=total)\n _, pbar, _ = self.container.children\n pbar.bar_style = ''\n if total is not None:\n pbar.max = total\n if not self.total and self.ncols is None: # no longer unknown total\n pbar.layout.width = None # reset width\n return super(tqdm_notebook, self).reset(total=total)", "has_branch": true, "total_branches": 2} {"prompt_id": 793, "project": "tqdm", "module": "tqdm.rich", "class": "FractionColumn", "method": "render", "focal_method_txt": " def render(self, task):\n \"\"\"Calculate common unit for completed and total.\"\"\"\n completed = int(task.completed)\n total = int(task.total)\n if self.unit_scale:\n unit, suffix = filesize.pick_unit_and_suffix(\n total,\n [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"],\n self.unit_divisor,\n )\n else:\n unit, suffix = filesize.pick_unit_and_suffix(total, [\"\"], 1)\n precision = 0 if unit == 1 else 1\n return Text(\n f\"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}\",\n style=\"progress.download\")", "focal_method_lines": [30, 43], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass FractionColumn(ProgressColumn):\n\n def __init__(self, unit_scale=False, unit_divisor=1000):\n self.unit_scale = unit_scale\n self.unit_divisor = unit_divisor\n super().__init__()\n\n def render(self, task):\n \"\"\"Calculate common unit for completed and total.\"\"\"\n completed = int(task.completed)\n total = int(task.total)\n if self.unit_scale:\n unit, suffix = filesize.pick_unit_and_suffix(\n total,\n [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"],\n self.unit_divisor,\n )\n else:\n unit, suffix = filesize.pick_unit_and_suffix(total, [\"\"], 1)\n precision = 0 if unit == 1 else 1\n return Text(\n f\"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}\",\n style=\"progress.download\")", "has_branch": true, "total_branches": 2} {"prompt_id": 794, "project": "tqdm", "module": "tqdm.rich", "class": "RateColumn", "method": "render", "focal_method_txt": " def render(self, task):\n \"\"\"Show data transfer speed.\"\"\"\n speed = task.speed\n if speed is None:\n return Text(f\"? {self.unit}/s\", style=\"progress.data.speed\")\n if self.unit_scale:\n unit, suffix = filesize.pick_unit_and_suffix(\n speed,\n [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"],\n self.unit_divisor,\n )\n else:\n unit, suffix = filesize.pick_unit_and_suffix(speed, [\"\"], 1)\n precision = 0 if unit == 1 else 1\n return Text(f\"{speed/unit:,.{precision}f} {suffix}{self.unit}/s\",\n style=\"progress.data.speed\")", "focal_method_lines": [56, 70], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass RateColumn(ProgressColumn):\n\n def __init__(self, unit=\"\", unit_scale=False, unit_divisor=1000):\n self.unit = unit\n self.unit_scale = unit_scale\n self.unit_divisor = unit_divisor\n super().__init__()\n\n def render(self, task):\n \"\"\"Show data transfer speed.\"\"\"\n speed = task.speed\n if speed is None:\n return Text(f\"? {self.unit}/s\", style=\"progress.data.speed\")\n if self.unit_scale:\n unit, suffix = filesize.pick_unit_and_suffix(\n speed,\n [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"],\n self.unit_divisor,\n )\n else:\n unit, suffix = filesize.pick_unit_and_suffix(speed, [\"\"], 1)\n precision = 0 if unit == 1 else 1\n return Text(f\"{speed/unit:,.{precision}f} {suffix}{self.unit}/s\",\n style=\"progress.data.speed\")", "has_branch": true, "total_branches": 2} {"prompt_id": 795, "project": "tqdm", "module": "tqdm.rich", "class": "tqdm_rich", "method": "__init__", "focal_method_txt": " def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)", "focal_method_lines": [77, 112], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass FractionColumn(ProgressColumn):\n\n def __init__(self, unit_scale=False, unit_divisor=1000):\n self.unit_scale = unit_scale\n self.unit_divisor = unit_divisor\n super().__init__()\n\nclass RateColumn(ProgressColumn):\n\n def __init__(self, unit=\"\", unit_scale=False, unit_divisor=1000):\n self.unit = unit\n self.unit_scale = unit_scale\n self.unit_divisor = unit_divisor\n super().__init__()\n\nclass tqdm_rich(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)", "has_branch": false, "total_branches": 0} {"prompt_id": 796, "project": "tqdm", "module": "tqdm.rich", "class": "tqdm_rich", "method": "close", "focal_method_txt": " def close(self):\n if self.disable:\n return\n super(tqdm_rich, self).close()\n self._prog.__exit__(None, None, None)", "focal_method_lines": [114, 118], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass tqdm_rich(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)\n\n def close(self):\n if self.disable:\n return\n super(tqdm_rich, self).close()\n self._prog.__exit__(None, None, None)", "has_branch": false, "total_branches": 0} {"prompt_id": 797, "project": "tqdm", "module": "tqdm.rich", "class": "tqdm_rich", "method": "clear", "focal_method_txt": " def clear(self, *_, **__):\n pass", "focal_method_lines": [120, 121], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass tqdm_rich(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)\n\n def clear(self, *_, **__):\n pass", "has_branch": false, "total_branches": 0} {"prompt_id": 798, "project": "tqdm", "module": "tqdm.rich", "class": "tqdm_rich", "method": "display", "focal_method_txt": " def display(self, *_, **__):\n if not hasattr(self, '_prog'):\n return\n self._prog.update(self._task_id, completed=self.n, description=self.desc)", "focal_method_lines": [123, 126], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass tqdm_rich(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)\n\n def display(self, *_, **__):\n if not hasattr(self, '_prog'):\n return\n self._prog.update(self._task_id, completed=self.n, description=self.desc)", "has_branch": false, "total_branches": 0} {"prompt_id": 799, "project": "tqdm", "module": "tqdm.rich", "class": "tqdm_rich", "method": "reset", "focal_method_txt": " def reset(self, total=None):\n \"\"\"\n Resets to 0 iterations for repeated use.\n\n Parameters\n ----------\n total : int or float, optional. Total to use for the new bar.\n \"\"\"\n if hasattr(self, '_prog'):\n self._prog.reset(total=total)\n super(tqdm_rich, self).reset(total=total)", "focal_method_lines": [128, 138], "in_stack": false, "globals": ["__author__", "__all__", "tqdm", "trange"], "type_context": "from warnings import warn\nfrom rich.progress import (\n BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)\nfrom .std import TqdmExperimentalWarning\nfrom .std import tqdm as std_tqdm\nfrom .utils import _range\n\n__author__ = {\"github.com/\": [\"casperdcl\"]}\n__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']\ntqdm = tqdm_rich\ntrange = trrange\n\nclass tqdm_rich(std_tqdm): # pragma: no cover\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n This class accepts the following parameters *in addition* to\n the parameters accepted by `tqdm`.\n\n Parameters\n ----------\n progress : tuple, optional\n arguments for `rich.progress.Progress()`.\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['gui'] = True\n # convert disable = None to False\n kwargs['disable'] = bool(kwargs.get('disable', False))\n progress = kwargs.pop('progress', None)\n super(tqdm_rich, self).__init__(*args, **kwargs)\n\n if self.disable:\n return\n\n warn(\"rich is experimental/alpha\", TqdmExperimentalWarning, stacklevel=2)\n d = self.format_dict\n if progress is None:\n progress = (\n \"[progress.description]{task.description}\"\n \"[progress.percentage]{task.percentage:>4.0f}%\",\n BarColumn(bar_width=None),\n FractionColumn(\n unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),\n \"[\", TimeElapsedColumn(), \"<\", TimeRemainingColumn(),\n \",\", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],\n unit_divisor=d['unit_divisor']), \"]\"\n )\n self._prog = Progress(*progress, transient=not self.leave)\n self._prog.__enter__()\n self._task_id = self._prog.add_task(self.desc or \"\", **d)\n\n def reset(self, total=None):\n \"\"\"\n Resets to 0 iterations for repeated use.\n\n Parameters\n ----------\n total : int or float, optional. Total to use for the new bar.\n \"\"\"\n if hasattr(self, '_prog'):\n self._prog.reset(total=total)\n super(tqdm_rich, self).reset(total=total)", "has_branch": false, "total_branches": 0} {"prompt_id": 800, "project": "typesystem", "module": "typesystem.base", "class": "Position", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: typing.Any) -> bool:\n return (\n isinstance(other, Position)\n and self.line_no == other.line_no\n and self.column_no == other.column_no\n and self.char_index == other.char_index\n )", "focal_method_lines": [10, 11], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass Position:\n\n def __init__(self, line_no: int, column_no: int, char_index: int):\n self.line_no = line_no\n self.column_no = column_no\n self.char_index = char_index\n\n def __eq__(self, other: typing.Any) -> bool:\n return (\n isinstance(other, Position)\n and self.line_no == other.line_no\n and self.column_no == other.column_no\n and self.char_index == other.char_index\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 801, "project": "typesystem", "module": "typesystem.base", "class": "Message", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, Message) and (\n self.text == other.text\n and self.code == other.code\n and self.index == other.index\n and self.start_position == other.start_position\n and self.end_position == other.end_position\n )", "focal_method_lines": [71, 72], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass Message:\n\n def __init__(\n self,\n *,\n text: str,\n code: str = None,\n key: typing.Union[int, str] = None,\n index: typing.List[typing.Union[int, str]] = None,\n position: Position = None,\n start_position: Position = None,\n end_position: Position = None,\n ):\n \"\"\"\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n index - The index of the message within a nested object. eg. ['users', 3, 'username']\n\n Optionally either:\n\n position - The start and end position of the error message within the raw content.\n\n Or:\n\n start_position - The start position of the error message within the raw content.\n end_position - The end position of the error message within the raw content.\n \"\"\"\n self.text = text\n self.code = \"custom\" if code is None else code\n if key is not None:\n assert index is None\n self.index = [key]\n else:\n self.index = [] if index is None else index\n\n if position is None:\n self.start_position = start_position\n self.end_position = end_position\n else:\n assert start_position is None\n assert end_position is None\n self.start_position = position\n self.end_position = position\n\n def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, Message) and (\n self.text == other.text\n and self.code == other.code\n and self.index == other.index\n and self.start_position == other.start_position\n and self.end_position == other.end_position\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 802, "project": "typesystem", "module": "typesystem.base", "class": "BaseError", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n *,\n text: str = None,\n code: str = None,\n key: typing.Union[int, str] = None,\n position: Position = None,\n messages: typing.List[Message] = None,\n ):\n \"\"\"\n Either instantiated with a single message, like so:\n\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n\n Or instantiated with a list of error messages:\n\n messages - A list of all the messages in the error.\n \"\"\"\n if messages is None:\n # Instantiated as a ValidationError with a single error message.\n assert text is not None\n messages = [Message(text=text, code=code, key=key, position=position)]\n else:\n # Instantiated as a ValidationError with multiple error messages.\n assert text is None\n assert code is None\n assert key is None\n assert position is None\n assert len(messages)\n\n self._messages = messages\n self._message_dict: typing.Dict[\n typing.Union[int, str], typing.Union[str, dict]\n ] = {}\n\n # Populate 'self._message_dict'\n for message in messages:\n insert_into = self._message_dict\n for key in message.index[:-1]:\n insert_into = insert_into.setdefault(key, {}) # type: ignore\n insert_key = message.index[-1] if message.index else \"\"\n insert_into[insert_key] = message.text", "focal_method_lines": [111, 154], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass Position:\n\n def __init__(self, line_no: int, column_no: int, char_index: int):\n self.line_no = line_no\n self.column_no = column_no\n self.char_index = char_index\n\nclass Message:\n\n def __init__(\n self,\n *,\n text: str,\n code: str = None,\n key: typing.Union[int, str] = None,\n index: typing.List[typing.Union[int, str]] = None,\n position: Position = None,\n start_position: Position = None,\n end_position: Position = None,\n ):\n \"\"\"\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n index - The index of the message within a nested object. eg. ['users', 3, 'username']\n\n Optionally either:\n\n position - The start and end position of the error message within the raw content.\n\n Or:\n\n start_position - The start position of the error message within the raw content.\n end_position - The end position of the error message within the raw content.\n \"\"\"\n self.text = text\n self.code = \"custom\" if code is None else code\n if key is not None:\n assert index is None\n self.index = [key]\n else:\n self.index = [] if index is None else index\n\n if position is None:\n self.start_position = start_position\n self.end_position = end_position\n else:\n assert start_position is None\n assert end_position is None\n self.start_position = position\n self.end_position = position\n\nclass BaseError(Mapping, Exception):\n\n def __init__(\n self,\n *,\n text: str = None,\n code: str = None,\n key: typing.Union[int, str] = None,\n position: Position = None,\n messages: typing.List[Message] = None,\n ):\n \"\"\"\n Either instantiated with a single message, like so:\n\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n\n Or instantiated with a list of error messages:\n\n messages - A list of all the messages in the error.\n \"\"\"\n if messages is None:\n # Instantiated as a ValidationError with a single error message.\n assert text is not None\n messages = [Message(text=text, code=code, key=key, position=position)]\n else:\n # Instantiated as a ValidationError with multiple error messages.\n assert text is None\n assert code is None\n assert key is None\n assert position is None\n assert len(messages)\n\n self._messages = messages\n self._message_dict: typing.Dict[\n typing.Union[int, str], typing.Union[str, dict]\n ] = {}\n\n # Populate 'self._message_dict'\n for message in messages:\n insert_into = self._message_dict\n for key in message.index[:-1]:\n insert_into = insert_into.setdefault(key, {}) # type: ignore\n insert_key = message.index[-1] if message.index else \"\"\n insert_into[insert_key] = message.text", "has_branch": true, "total_branches": 2} {"prompt_id": 803, "project": "typesystem", "module": "typesystem.base", "class": "BaseError", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, ValidationError) and self._messages == other._messages", "focal_method_lines": [186, 187], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass BaseError(Mapping, Exception):\n\n def __init__(\n self,\n *,\n text: str = None,\n code: str = None,\n key: typing.Union[int, str] = None,\n position: Position = None,\n messages: typing.List[Message] = None,\n ):\n \"\"\"\n Either instantiated with a single message, like so:\n\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n\n Or instantiated with a list of error messages:\n\n messages - A list of all the messages in the error.\n \"\"\"\n if messages is None:\n # Instantiated as a ValidationError with a single error message.\n assert text is not None\n messages = [Message(text=text, code=code, key=key, position=position)]\n else:\n # Instantiated as a ValidationError with multiple error messages.\n assert text is None\n assert code is None\n assert key is None\n assert position is None\n assert len(messages)\n\n self._messages = messages\n self._message_dict: typing.Dict[\n typing.Union[int, str], typing.Union[str, dict]\n ] = {}\n\n # Populate 'self._message_dict'\n for message in messages:\n insert_into = self._message_dict\n for key in message.index[:-1]:\n insert_into = insert_into.setdefault(key, {}) # type: ignore\n insert_key = message.index[-1] if message.index else \"\"\n insert_into[insert_key] = message.text\n\n def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, ValidationError) and self._messages == other._messages", "has_branch": false, "total_branches": 0} {"prompt_id": 804, "project": "typesystem", "module": "typesystem.base", "class": "BaseError", "method": "__repr__", "focal_method_txt": " def __repr__(self) -> str:\n class_name = self.__class__.__name__\n if len(self._messages) == 1 and not self._messages[0].index:\n message = self._messages[0]\n return f\"{class_name}(text={message.text!r}, code={message.code!r})\"\n return f\"{class_name}({self._messages!r})\"", "focal_method_lines": [193, 198], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass BaseError(Mapping, Exception):\n\n def __init__(\n self,\n *,\n text: str = None,\n code: str = None,\n key: typing.Union[int, str] = None,\n position: Position = None,\n messages: typing.List[Message] = None,\n ):\n \"\"\"\n Either instantiated with a single message, like so:\n\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n\n Or instantiated with a list of error messages:\n\n messages - A list of all the messages in the error.\n \"\"\"\n if messages is None:\n # Instantiated as a ValidationError with a single error message.\n assert text is not None\n messages = [Message(text=text, code=code, key=key, position=position)]\n else:\n # Instantiated as a ValidationError with multiple error messages.\n assert text is None\n assert code is None\n assert key is None\n assert position is None\n assert len(messages)\n\n self._messages = messages\n self._message_dict: typing.Dict[\n typing.Union[int, str], typing.Union[str, dict]\n ] = {}\n\n # Populate 'self._message_dict'\n for message in messages:\n insert_into = self._message_dict\n for key in message.index[:-1]:\n insert_into = insert_into.setdefault(key, {}) # type: ignore\n insert_key = message.index[-1] if message.index else \"\"\n insert_into[insert_key] = message.text\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n if len(self._messages) == 1 and not self._messages[0].index:\n message = self._messages[0]\n return f\"{class_name}(text={message.text!r}, code={message.code!r})\"\n return f\"{class_name}({self._messages!r})\"", "has_branch": true, "total_branches": 2} {"prompt_id": 805, "project": "typesystem", "module": "typesystem.base", "class": "BaseError", "method": "__str__", "focal_method_txt": " def __str__(self) -> str:\n if len(self._messages) == 1 and not self._messages[0].index:\n return self._messages[0].text\n return str(dict(self))", "focal_method_lines": [200, 203], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass BaseError(Mapping, Exception):\n\n def __init__(\n self,\n *,\n text: str = None,\n code: str = None,\n key: typing.Union[int, str] = None,\n position: Position = None,\n messages: typing.List[Message] = None,\n ):\n \"\"\"\n Either instantiated with a single message, like so:\n\n text - The error message. 'May not have more than 100 characters'\n code - An optional error code, eg. 'max_length'\n key - An optional key of the message within a single parent. eg. 'username'\n\n Or instantiated with a list of error messages:\n\n messages - A list of all the messages in the error.\n \"\"\"\n if messages is None:\n # Instantiated as a ValidationError with a single error message.\n assert text is not None\n messages = [Message(text=text, code=code, key=key, position=position)]\n else:\n # Instantiated as a ValidationError with multiple error messages.\n assert text is None\n assert code is None\n assert key is None\n assert position is None\n assert len(messages)\n\n self._messages = messages\n self._message_dict: typing.Dict[\n typing.Union[int, str], typing.Union[str, dict]\n ] = {}\n\n # Populate 'self._message_dict'\n for message in messages:\n insert_into = self._message_dict\n for key in message.index[:-1]:\n insert_into = insert_into.setdefault(key, {}) # type: ignore\n insert_key = message.index[-1] if message.index else \"\"\n insert_into[insert_key] = message.text\n\n def __str__(self) -> str:\n if len(self._messages) == 1 and not self._messages[0].index:\n return self._messages[0].text\n return str(dict(self))", "has_branch": true, "total_branches": 2} {"prompt_id": 806, "project": "typesystem", "module": "typesystem.base", "class": "ValidationResult", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> typing.Iterator:\n yield self.value\n yield self.error", "focal_method_lines": [242, 244], "in_stack": false, "globals": [], "type_context": "import typing\nfrom collections.abc import Mapping\n\n\n\nclass ValidationResult:\n\n def __init__(\n self, *, value: typing.Any = None, error: ValidationError = None\n ) -> None:\n \"\"\"\n Either:\n\n value - The validated data.\n\n Or:\n\n error - The validation error.\n \"\"\"\n assert value is None or error is None\n self.value = value\n self.error = error\n\n def __iter__(self) -> typing.Iterator:\n yield self.value\n yield self.error", "has_branch": false, "total_branches": 0} {"prompt_id": 807, "project": "typesystem", "module": "typesystem.composites", "class": "NeverMatch", "method": "__init__", "focal_method_txt": " def __init__(self, **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)", "focal_method_lines": [14, 16], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass NeverMatch(Field):\n\n errors = {\"never\": \"This never validates.\"}\n\n def __init__(self, **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 808, "project": "typesystem", "module": "typesystem.composites", "class": "OneOf", "method": "__init__", "focal_method_txt": " def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.one_of = one_of", "focal_method_lines": [35, 38], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass OneOf(Field):\n\n errors = {\n \"no_match\": \"Did not match any valid type.\",\n \"multiple_matches\": \"Matched more than one type.\",\n }\n\n def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.one_of = one_of", "has_branch": false, "total_branches": 0} {"prompt_id": 809, "project": "typesystem", "module": "typesystem.composites", "class": "OneOf", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n candidate = None\n match_count = 0\n for child in self.one_of:\n validated, error = child.validate_or_error(value, strict=strict)\n if error is None:\n match_count += 1\n candidate = validated\n\n if match_count == 1:\n return candidate\n elif match_count > 1:\n raise self.validation_error(\"multiple_matches\")\n raise self.validation_error(\"no_match\")", "focal_method_lines": [40, 53], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass OneOf(Field):\n\n errors = {\n \"no_match\": \"Did not match any valid type.\",\n \"multiple_matches\": \"Matched more than one type.\",\n }\n\n def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.one_of = one_of\n\n def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n candidate = None\n match_count = 0\n for child in self.one_of:\n validated, error = child.validate_or_error(value, strict=strict)\n if error is None:\n match_count += 1\n candidate = validated\n\n if match_count == 1:\n return candidate\n elif match_count > 1:\n raise self.validation_error(\"multiple_matches\")\n raise self.validation_error(\"no_match\")", "has_branch": true, "total_branches": 2} {"prompt_id": 810, "project": "typesystem", "module": "typesystem.composites", "class": "AllOf", "method": "__init__", "focal_method_txt": " def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.all_of = all_of", "focal_method_lines": [64, 67], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass AllOf(Field):\n\n def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.all_of = all_of", "has_branch": false, "total_branches": 0} {"prompt_id": 811, "project": "typesystem", "module": "typesystem.composites", "class": "Not", "method": "__init__", "focal_method_txt": " def __init__(self, negated: Field, **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.negated = negated", "focal_method_lines": [84, 87], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass Not(Field):\n\n errors = {\"negated\": \"Must not match.\"}\n\n def __init__(self, negated: Field, **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.negated = negated", "has_branch": false, "total_branches": 0} {"prompt_id": 812, "project": "typesystem", "module": "typesystem.composites", "class": "Not", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n _, error = self.negated.validate_or_error(value, strict=strict)\n if error:\n return value\n raise self.validation_error(\"negated\")", "focal_method_lines": [89, 93], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass Not(Field):\n\n errors = {\"negated\": \"Must not match.\"}\n\n def __init__(self, negated: Field, **kwargs: typing.Any) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.negated = negated\n\n def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n _, error = self.negated.validate_or_error(value, strict=strict)\n if error:\n return value\n raise self.validation_error(\"negated\")", "has_branch": true, "total_branches": 2} {"prompt_id": 813, "project": "typesystem", "module": "typesystem.composites", "class": "IfThenElse", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n if_clause: Field,\n then_clause: Field = None,\n else_clause: Field = None,\n **kwargs: typing.Any\n ) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.if_clause = if_clause\n self.then_clause = Any() if then_clause is None else then_clause\n self.else_clause = Any() if else_clause is None else else_clause", "focal_method_lines": [103, 114], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass IfThenElse(Field):\n\n def __init__(\n self,\n if_clause: Field,\n then_clause: Field = None,\n else_clause: Field = None,\n **kwargs: typing.Any\n ) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.if_clause = if_clause\n self.then_clause = Any() if then_clause is None else then_clause\n self.else_clause = Any() if else_clause is None else else_clause", "has_branch": false, "total_branches": 0} {"prompt_id": 814, "project": "typesystem", "module": "typesystem.composites", "class": "IfThenElse", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n _, error = self.if_clause.validate_or_error(value, strict=strict)\n if error is None:\n return self.then_clause.validate(value, strict=strict)\n else:\n return self.else_clause.validate(value, strict=strict)", "focal_method_lines": [116, 121], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.fields import Any, Field\n\n\n\nclass IfThenElse(Field):\n\n def __init__(\n self,\n if_clause: Field,\n then_clause: Field = None,\n else_clause: Field = None,\n **kwargs: typing.Any\n ) -> None:\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.if_clause = if_clause\n self.then_clause = Any() if then_clause is None else then_clause\n self.else_clause = Any() if else_clause is None else else_clause\n\n def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n _, error = self.if_clause.validate_or_error(value, strict=strict)\n if error is None:\n return self.then_clause.validate(value, strict=strict)\n else:\n return self.else_clause.validate(value, strict=strict)", "has_branch": true, "total_branches": 2} {"prompt_id": 815, "project": "typesystem", "module": "typesystem.fields", "class": "Field", "method": "validate_or_error", "focal_method_txt": " def validate_or_error(\n self, value: typing.Any, *, strict: bool = False\n ) -> ValidationResult:\n try:\n value = self.validate(value, strict=strict)\n except ValidationError as error:\n return ValidationResult(value=None, error=error)\n return ValidationResult(value=value, error=None)", "focal_method_lines": [52, 59], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\n def validate_or_error(\n self, value: typing.Any, *, strict: bool = False\n ) -> ValidationResult:\n try:\n value = self.validate(value, strict=strict)\n except ValidationError as error:\n return ValidationResult(value=None, error=error)\n return ValidationResult(value=value, error=None)", "has_branch": false, "total_branches": 0} {"prompt_id": 816, "project": "typesystem", "module": "typesystem.fields", "class": "Field", "method": "get_default_value", "focal_method_txt": " def get_default_value(self) -> typing.Any:\n default = getattr(self, \"default\", None)\n if callable(default):\n return default()\n return default", "focal_method_lines": [67, 71], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\n def get_default_value(self) -> typing.Any:\n default = getattr(self, \"default\", None)\n if callable(default):\n return default()\n return default", "has_branch": true, "total_branches": 2} {"prompt_id": 817, "project": "typesystem", "module": "typesystem.fields", "class": "Field", "method": "__or__", "focal_method_txt": " def __or__(self, other: \"Field\") -> \"Union\":\n if isinstance(self, Union):\n any_of = self.any_of\n else:\n any_of = [self]\n\n if isinstance(other, Union):\n any_of += other.any_of\n else:\n any_of += [other]\n\n return Union(any_of=any_of)", "focal_method_lines": [80, 91], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Union(Field):\n\n errors = {\"null\": \"May not be null.\", \"union\": \"Did not match any valid type.\"}\n\n def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):\n super().__init__(**kwargs)\n\n self.any_of = any_of\n if any([child.allow_null for child in any_of]):\n self.allow_null = True\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\n def __or__(self, other: \"Field\") -> \"Union\":\n if isinstance(self, Union):\n any_of = self.any_of\n else:\n any_of = [self]\n\n if isinstance(other, Union):\n any_of += other.any_of\n else:\n any_of += [other]\n\n return Union(any_of=any_of)", "has_branch": true, "total_branches": 2} {"prompt_id": 818, "project": "typesystem", "module": "typesystem.fields", "class": "String", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n *,\n allow_blank: bool = False,\n trim_whitespace: bool = True,\n max_length: int = None,\n min_length: int = None,\n pattern: typing.Union[str, typing.Pattern] = None,\n format: str = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n assert max_length is None or isinstance(max_length, int)\n assert min_length is None or isinstance(min_length, int)\n assert pattern is None or isinstance(pattern, (str, typing.Pattern))\n assert format is None or isinstance(format, str)\n\n if allow_blank and not self.has_default():\n self.default = \"\"\n\n self.allow_blank = allow_blank\n self.trim_whitespace = trim_whitespace\n self.max_length = max_length\n self.min_length = min_length\n self.format = format\n\n if pattern is None:\n self.pattern = None\n self.pattern_regex = None\n elif isinstance(pattern, str):\n self.pattern = pattern\n self.pattern_regex = re.compile(pattern)\n else:\n self.pattern = pattern.pattern\n self.pattern_regex = pattern", "focal_method_lines": [105, 140], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Union(Field):\n\n errors = {\"null\": \"May not be null.\", \"union\": \"Did not match any valid type.\"}\n\n def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):\n super().__init__(**kwargs)\n\n self.any_of = any_of\n if any([child.allow_null for child in any_of]):\n self.allow_null = True\n\nclass String(Field):\n\n errors = {\n \"type\": \"Must be a string.\",\n \"null\": \"May not be null.\",\n \"blank\": \"Must not be blank.\",\n \"max_length\": \"Must have no more than {max_length} characters.\",\n \"min_length\": \"Must have at least {min_length} characters.\",\n \"pattern\": \"Must match the pattern /{pattern}/.\",\n \"format\": \"Must be a valid {format}.\",\n }\n\n def __init__(\n self,\n *,\n allow_blank: bool = False,\n trim_whitespace: bool = True,\n max_length: int = None,\n min_length: int = None,\n pattern: typing.Union[str, typing.Pattern] = None,\n format: str = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n assert max_length is None or isinstance(max_length, int)\n assert min_length is None or isinstance(min_length, int)\n assert pattern is None or isinstance(pattern, (str, typing.Pattern))\n assert format is None or isinstance(format, str)\n\n if allow_blank and not self.has_default():\n self.default = \"\"\n\n self.allow_blank = allow_blank\n self.trim_whitespace = trim_whitespace\n self.max_length = max_length\n self.min_length = min_length\n self.format = format\n\n if pattern is None:\n self.pattern = None\n self.pattern_regex = None\n elif isinstance(pattern, str):\n self.pattern = pattern\n self.pattern_regex = re.compile(pattern)\n else:\n self.pattern = pattern.pattern\n self.pattern_regex = pattern", "has_branch": true, "total_branches": 2} {"prompt_id": 819, "project": "typesystem", "module": "typesystem.fields", "class": "String", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None and self.allow_blank and not strict:\n # Leniently cast nulls to empty strings if allow_blank.\n return \"\"\n elif value is None:\n raise self.validation_error(\"null\")\n elif self.format in FORMATS and FORMATS[self.format].is_native_type(value):\n return value\n elif not isinstance(value, str):\n raise self.validation_error(\"type\")\n\n # The null character is always invalid.\n value = value.replace(\"\\0\", \"\")\n\n # Strip leading/trailing whitespace by default.\n if self.trim_whitespace:\n value = value.strip()\n\n if not self.allow_blank and not value:\n if self.allow_null and not strict:\n # Leniently cast empty strings (after trimming) to null if allow_null.\n return None\n raise self.validation_error(\"blank\")\n\n if self.min_length is not None:\n if len(value) < self.min_length:\n raise self.validation_error(\"min_length\")\n\n if self.max_length is not None:\n if len(value) > self.max_length:\n raise self.validation_error(\"max_length\")\n\n if self.pattern_regex is not None:\n if not self.pattern_regex.search(value):\n raise self.validation_error(\"pattern\")\n\n if self.format in FORMATS:\n return FORMATS[self.format].validate(value)\n\n return value", "focal_method_lines": [142, 183], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass String(Field):\n\n errors = {\n \"type\": \"Must be a string.\",\n \"null\": \"May not be null.\",\n \"blank\": \"Must not be blank.\",\n \"max_length\": \"Must have no more than {max_length} characters.\",\n \"min_length\": \"Must have at least {min_length} characters.\",\n \"pattern\": \"Must match the pattern /{pattern}/.\",\n \"format\": \"Must be a valid {format}.\",\n }\n\n def __init__(\n self,\n *,\n allow_blank: bool = False,\n trim_whitespace: bool = True,\n max_length: int = None,\n min_length: int = None,\n pattern: typing.Union[str, typing.Pattern] = None,\n format: str = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n assert max_length is None or isinstance(max_length, int)\n assert min_length is None or isinstance(min_length, int)\n assert pattern is None or isinstance(pattern, (str, typing.Pattern))\n assert format is None or isinstance(format, str)\n\n if allow_blank and not self.has_default():\n self.default = \"\"\n\n self.allow_blank = allow_blank\n self.trim_whitespace = trim_whitespace\n self.max_length = max_length\n self.min_length = min_length\n self.format = format\n\n if pattern is None:\n self.pattern = None\n self.pattern_regex = None\n elif isinstance(pattern, str):\n self.pattern = pattern\n self.pattern_regex = re.compile(pattern)\n else:\n self.pattern = pattern.pattern\n self.pattern_regex = pattern\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None and self.allow_blank and not strict:\n # Leniently cast nulls to empty strings if allow_blank.\n return \"\"\n elif value is None:\n raise self.validation_error(\"null\")\n elif self.format in FORMATS and FORMATS[self.format].is_native_type(value):\n return value\n elif not isinstance(value, str):\n raise self.validation_error(\"type\")\n\n # The null character is always invalid.\n value = value.replace(\"\\0\", \"\")\n\n # Strip leading/trailing whitespace by default.\n if self.trim_whitespace:\n value = value.strip()\n\n if not self.allow_blank and not value:\n if self.allow_null and not strict:\n # Leniently cast empty strings (after trimming) to null if allow_null.\n return None\n raise self.validation_error(\"blank\")\n\n if self.min_length is not None:\n if len(value) < self.min_length:\n raise self.validation_error(\"min_length\")\n\n if self.max_length is not None:\n if len(value) > self.max_length:\n raise self.validation_error(\"max_length\")\n\n if self.pattern_regex is not None:\n if not self.pattern_regex.search(value):\n raise self.validation_error(\"pattern\")\n\n if self.format in FORMATS:\n return FORMATS[self.format].validate(value)\n\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 820, "project": "typesystem", "module": "typesystem.fields", "class": "String", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Any:\n if self.format in FORMATS:\n return FORMATS[self.format].serialize(obj)\n return obj", "focal_method_lines": [185, 188], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass String(Field):\n\n errors = {\n \"type\": \"Must be a string.\",\n \"null\": \"May not be null.\",\n \"blank\": \"Must not be blank.\",\n \"max_length\": \"Must have no more than {max_length} characters.\",\n \"min_length\": \"Must have at least {min_length} characters.\",\n \"pattern\": \"Must match the pattern /{pattern}/.\",\n \"format\": \"Must be a valid {format}.\",\n }\n\n def __init__(\n self,\n *,\n allow_blank: bool = False,\n trim_whitespace: bool = True,\n max_length: int = None,\n min_length: int = None,\n pattern: typing.Union[str, typing.Pattern] = None,\n format: str = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n assert max_length is None or isinstance(max_length, int)\n assert min_length is None or isinstance(min_length, int)\n assert pattern is None or isinstance(pattern, (str, typing.Pattern))\n assert format is None or isinstance(format, str)\n\n if allow_blank and not self.has_default():\n self.default = \"\"\n\n self.allow_blank = allow_blank\n self.trim_whitespace = trim_whitespace\n self.max_length = max_length\n self.min_length = min_length\n self.format = format\n\n if pattern is None:\n self.pattern = None\n self.pattern_regex = None\n elif isinstance(pattern, str):\n self.pattern = pattern\n self.pattern_regex = re.compile(pattern)\n else:\n self.pattern = pattern.pattern\n self.pattern_regex = pattern\n\n def serialize(self, obj: typing.Any) -> typing.Any:\n if self.format in FORMATS:\n return FORMATS[self.format].serialize(obj)\n return obj", "has_branch": true, "total_branches": 2} {"prompt_id": 821, "project": "typesystem", "module": "typesystem.fields", "class": "Number", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value == \"\" and self.allow_null and not strict:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif isinstance(value, bool):\n raise self.validation_error(\"type\")\n elif (\n self.numeric_type is int\n and isinstance(value, float)\n and not value.is_integer()\n ):\n raise self.validation_error(\"integer\")\n elif not isinstance(value, (int, float)) and strict:\n raise self.validation_error(\"type\")\n\n try:\n if isinstance(value, str):\n # Casting to a decimal first gives more lenient parsing.\n value = decimal.Decimal(value)\n if self.numeric_type is not None:\n value = self.numeric_type(value)\n except (TypeError, ValueError, decimal.InvalidOperation):\n raise self.validation_error(\"type\")\n\n if not isfinite(value):\n # inf, -inf, nan, are all invalid.\n raise self.validation_error(\"finite\")\n\n if self.precision is not None:\n numeric_type = self.numeric_type or type(value)\n quantize_val = decimal.Decimal(self.precision)\n decimal_val = decimal.Decimal(value)\n decimal_val = decimal_val.quantize(\n quantize_val, rounding=decimal.ROUND_HALF_UP\n )\n value = numeric_type(decimal_val)\n\n if self.minimum is not None and value < self.minimum:\n raise self.validation_error(\"minimum\")\n\n if self.exclusive_minimum is not None and value <= self.exclusive_minimum:\n raise self.validation_error(\"exclusive_minimum\")\n\n if self.maximum is not None and value > self.maximum:\n raise self.validation_error(\"maximum\")\n\n if self.exclusive_maximum is not None and value >= self.exclusive_maximum:\n raise self.validation_error(\"exclusive_maximum\")\n\n if self.multiple_of is not None:\n if isinstance(self.multiple_of, int):\n if value % self.multiple_of:\n raise self.validation_error(\"multiple_of\")\n else:\n if not (value * (1 / self.multiple_of)).is_integer():\n raise self.validation_error(\"multiple_of\")\n\n return value", "focal_method_lines": [237, 297], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Number(Field):\n\n numeric_type: typing.Optional[type] = None\n\n errors = {\n \"type\": \"Must be a number.\",\n \"null\": \"May not be null.\",\n \"integer\": \"Must be an integer.\",\n \"finite\": \"Must be finite.\",\n \"minimum\": \"Must be greater than or equal to {minimum}.\",\n \"exclusive_minimum\": \"Must be greater than {exclusive_minimum}.\",\n \"maximum\": \"Must be less than or equal to {maximum}.\",\n \"exclusive_maximum\": \"Must be less than {exclusive_maximum}.\",\n \"multiple_of\": \"Must be a multiple of {multiple_of}.\",\n }\n\n def __init__(\n self,\n *,\n minimum: typing.Union[int, float, decimal.Decimal] = None,\n maximum: typing.Union[int, float, decimal.Decimal] = None,\n exclusive_minimum: typing.Union[int, float, decimal.Decimal] = None,\n exclusive_maximum: typing.Union[int, float, decimal.Decimal] = None,\n precision: str = None,\n multiple_of: typing.Union[int, float, decimal.Decimal] = None,\n **kwargs: typing.Any,\n ):\n super().__init__(**kwargs)\n\n assert minimum is None or isinstance(minimum, (int, float, decimal.Decimal))\n assert maximum is None or isinstance(maximum, (int, float, decimal.Decimal))\n assert exclusive_minimum is None or isinstance(\n exclusive_minimum, (int, float, decimal.Decimal)\n )\n assert exclusive_maximum is None or isinstance(\n exclusive_maximum, (int, float, decimal.Decimal)\n )\n assert multiple_of is None or isinstance(\n multiple_of, (int, float, decimal.Decimal)\n )\n\n self.minimum = minimum\n self.maximum = maximum\n self.exclusive_minimum = exclusive_minimum\n self.exclusive_maximum = exclusive_maximum\n self.multiple_of = multiple_of\n self.precision = precision\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value == \"\" and self.allow_null and not strict:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif isinstance(value, bool):\n raise self.validation_error(\"type\")\n elif (\n self.numeric_type is int\n and isinstance(value, float)\n and not value.is_integer()\n ):\n raise self.validation_error(\"integer\")\n elif not isinstance(value, (int, float)) and strict:\n raise self.validation_error(\"type\")\n\n try:\n if isinstance(value, str):\n # Casting to a decimal first gives more lenient parsing.\n value = decimal.Decimal(value)\n if self.numeric_type is not None:\n value = self.numeric_type(value)\n except (TypeError, ValueError, decimal.InvalidOperation):\n raise self.validation_error(\"type\")\n\n if not isfinite(value):\n # inf, -inf, nan, are all invalid.\n raise self.validation_error(\"finite\")\n\n if self.precision is not None:\n numeric_type = self.numeric_type or type(value)\n quantize_val = decimal.Decimal(self.precision)\n decimal_val = decimal.Decimal(value)\n decimal_val = decimal_val.quantize(\n quantize_val, rounding=decimal.ROUND_HALF_UP\n )\n value = numeric_type(decimal_val)\n\n if self.minimum is not None and value < self.minimum:\n raise self.validation_error(\"minimum\")\n\n if self.exclusive_minimum is not None and value <= self.exclusive_minimum:\n raise self.validation_error(\"exclusive_minimum\")\n\n if self.maximum is not None and value > self.maximum:\n raise self.validation_error(\"maximum\")\n\n if self.exclusive_maximum is not None and value >= self.exclusive_maximum:\n raise self.validation_error(\"exclusive_maximum\")\n\n if self.multiple_of is not None:\n if isinstance(self.multiple_of, int):\n if value % self.multiple_of:\n raise self.validation_error(\"multiple_of\")\n else:\n if not (value * (1 / self.multiple_of)).is_integer():\n raise self.validation_error(\"multiple_of\")\n\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 822, "project": "typesystem", "module": "typesystem.fields", "class": "Boolean", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n\n elif value is None:\n raise self.validation_error(\"null\")\n\n elif not isinstance(value, bool):\n if strict:\n raise self.validation_error(\"type\")\n\n if isinstance(value, str):\n value = value.lower()\n\n if self.allow_null and value in self.coerce_null_values:\n return None\n\n try:\n value = self.coerce_values[value]\n except (KeyError, TypeError):\n raise self.validation_error(\"type\")\n\n return value", "focal_method_lines": [330, 352], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Boolean(Field):\n\n errors = {\"type\": \"Must be a boolean.\", \"null\": \"May not be null.\"}\n\n coerce_values = {\n \"true\": True,\n \"false\": False,\n \"on\": True,\n \"off\": False,\n \"1\": True,\n \"0\": False,\n \"\": False,\n 1: True,\n 0: False,\n }\n\n coerce_null_values = {\"\", \"null\", \"none\"}\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n\n elif value is None:\n raise self.validation_error(\"null\")\n\n elif not isinstance(value, bool):\n if strict:\n raise self.validation_error(\"type\")\n\n if isinstance(value, str):\n value = value.lower()\n\n if self.allow_null and value in self.coerce_null_values:\n return None\n\n try:\n value = self.coerce_values[value]\n except (KeyError, TypeError):\n raise self.validation_error(\"type\")\n\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 823, "project": "typesystem", "module": "typesystem.fields", "class": "Choice", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n *,\n choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.choices = [\n (choice if isinstance(choice, (tuple, list)) else (choice, choice))\n for choice in choices or []\n ]\n assert all(len(choice) == 2 for choice in self.choices)", "focal_method_lines": [362, 373], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Union(Field):\n\n errors = {\"null\": \"May not be null.\", \"union\": \"Did not match any valid type.\"}\n\n def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):\n super().__init__(**kwargs)\n\n self.any_of = any_of\n if any([child.allow_null for child in any_of]):\n self.allow_null = True\n\nclass Choice(Field):\n\n errors = {\n \"null\": \"May not be null.\",\n \"required\": \"This field is required.\",\n \"choice\": \"Not a valid choice.\",\n }\n\n def __init__(\n self,\n *,\n choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.choices = [\n (choice if isinstance(choice, (tuple, list)) else (choice, choice))\n for choice in choices or []\n ]\n assert all(len(choice) == 2 for choice in self.choices)", "has_branch": false, "total_branches": 0} {"prompt_id": 824, "project": "typesystem", "module": "typesystem.fields", "class": "Choice", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif value not in Uniqueness([key for key, value in self.choices]):\n if value == \"\":\n if self.allow_null and not strict:\n return None\n raise self.validation_error(\"required\")\n raise self.validation_error(\"choice\")\n return value", "focal_method_lines": [375, 386], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Choice(Field):\n\n errors = {\n \"null\": \"May not be null.\",\n \"required\": \"This field is required.\",\n \"choice\": \"Not a valid choice.\",\n }\n\n def __init__(\n self,\n *,\n choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.choices = [\n (choice if isinstance(choice, (tuple, list)) else (choice, choice))\n for choice in choices or []\n ]\n assert all(len(choice) == 2 for choice in self.choices)\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif value not in Uniqueness([key for key, value in self.choices]):\n if value == \"\":\n if self.allow_null and not strict:\n return None\n raise self.validation_error(\"required\")\n raise self.validation_error(\"choice\")\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 825, "project": "typesystem", "module": "typesystem.fields", "class": "Object", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif not isinstance(value, (dict, typing.Mapping)):\n raise self.validation_error(\"type\")\n\n validated = {}\n error_messages = []\n\n # Ensure all property keys are strings.\n for key in value.keys():\n if not isinstance(key, str):\n text = self.get_error_text(\"invalid_key\")\n message = Message(text=text, code=\"invalid_key\", index=[key])\n error_messages.append(message)\n elif self.property_names is not None:\n _, error = self.property_names.validate_or_error(key)\n if error is not None:\n text = self.get_error_text(\"invalid_property\")\n message = Message(text=text, code=\"invalid_property\", index=[key])\n error_messages.append(message)\n\n # Min/Max properties\n if self.min_properties is not None:\n if len(value) < self.min_properties:\n if self.min_properties == 1:\n raise self.validation_error(\"empty\")\n else:\n raise self.validation_error(\"min_properties\")\n if self.max_properties is not None:\n if len(value) > self.max_properties:\n raise self.validation_error(\"max_properties\")\n\n # Required properties\n for key in self.required:\n if key not in value:\n text = self.get_error_text(\"required\")\n message = Message(text=text, code=\"required\", index=[key])\n error_messages.append(message)\n\n # Properties\n for key, child_schema in self.properties.items():\n if key not in value:\n if child_schema.has_default():\n validated[key] = child_schema.get_default_value()\n continue\n item = value[key]\n child_value, error = child_schema.validate_or_error(item, strict=strict)\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n # Pattern properties\n if self.pattern_properties:\n for key in list(value.keys()):\n for pattern, child_schema in self.pattern_properties.items():\n if isinstance(key, str) and re.search(pattern, key):\n item = value[key]\n child_value, error = child_schema.validate_or_error(\n item, strict=strict\n )\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n # Additional properties\n validated_keys = set(validated.keys())\n error_keys = set(\n [message.index[0] for message in error_messages if message.index]\n )\n\n remaining = [\n key for key in value.keys() if key not in validated_keys | error_keys\n ]\n\n if self.additional_properties is True:\n for key in remaining:\n validated[key] = value[key]\n elif self.additional_properties is False:\n for key in remaining:\n text = self.get_error_text(\"invalid_property\")\n message = Message(text=text, code=\"invalid_property\", key=key)\n error_messages.append(message)\n elif self.additional_properties is not None:\n assert isinstance(self.additional_properties, Field)\n child_schema = self.additional_properties\n for key in remaining:\n item = value[key]\n child_value, error = child_schema.validate_or_error(item, strict=strict)\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n if error_messages:\n raise ValidationError(messages=error_messages)\n\n return validated", "focal_method_lines": [445, 546], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\nclass Object(Field):\n\n errors = {\n \"type\": \"Must be an object.\",\n \"null\": \"May not be null.\",\n \"invalid_key\": \"All object keys must be strings.\",\n \"required\": \"This field is required.\",\n \"invalid_property\": \"Invalid property name.\",\n \"empty\": \"Must not be empty.\",\n \"max_properties\": \"Must have no more than {max_properties} properties.\",\n \"min_properties\": \"Must have at least {min_properties} properties.\",\n }\n\n def __init__(\n self,\n *,\n properties: typing.Dict[str, Field] = None,\n pattern_properties: typing.Dict[str, Field] = None,\n additional_properties: typing.Union[bool, None, Field] = True,\n property_names: Field = None,\n min_properties: int = None,\n max_properties: int = None,\n required: typing.Sequence[str] = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n if isinstance(properties, Field):\n additional_properties = properties\n properties = None\n\n properties = {} if (properties is None) else dict(properties)\n pattern_properties = (\n {} if (pattern_properties is None) else dict(pattern_properties)\n )\n required = list(required) if isinstance(required, (list, tuple)) else required\n required = [] if (required is None) else required\n\n assert all(isinstance(k, str) for k in properties.keys())\n assert all(isinstance(v, Field) for v in properties.values())\n assert all(isinstance(k, str) for k in pattern_properties.keys())\n assert all(isinstance(v, Field) for v in pattern_properties.values())\n assert additional_properties in (None, True, False) or isinstance(\n additional_properties, Field\n )\n assert min_properties is None or isinstance(min_properties, int)\n assert max_properties is None or isinstance(max_properties, int)\n assert all(isinstance(i, str) for i in required)\n\n self.properties = properties\n self.pattern_properties = pattern_properties\n self.additional_properties = additional_properties\n self.property_names = property_names\n self.min_properties = min_properties\n self.max_properties = max_properties\n self.required = required\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif not isinstance(value, (dict, typing.Mapping)):\n raise self.validation_error(\"type\")\n\n validated = {}\n error_messages = []\n\n # Ensure all property keys are strings.\n for key in value.keys():\n if not isinstance(key, str):\n text = self.get_error_text(\"invalid_key\")\n message = Message(text=text, code=\"invalid_key\", index=[key])\n error_messages.append(message)\n elif self.property_names is not None:\n _, error = self.property_names.validate_or_error(key)\n if error is not None:\n text = self.get_error_text(\"invalid_property\")\n message = Message(text=text, code=\"invalid_property\", index=[key])\n error_messages.append(message)\n\n # Min/Max properties\n if self.min_properties is not None:\n if len(value) < self.min_properties:\n if self.min_properties == 1:\n raise self.validation_error(\"empty\")\n else:\n raise self.validation_error(\"min_properties\")\n if self.max_properties is not None:\n if len(value) > self.max_properties:\n raise self.validation_error(\"max_properties\")\n\n # Required properties\n for key in self.required:\n if key not in value:\n text = self.get_error_text(\"required\")\n message = Message(text=text, code=\"required\", index=[key])\n error_messages.append(message)\n\n # Properties\n for key, child_schema in self.properties.items():\n if key not in value:\n if child_schema.has_default():\n validated[key] = child_schema.get_default_value()\n continue\n item = value[key]\n child_value, error = child_schema.validate_or_error(item, strict=strict)\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n # Pattern properties\n if self.pattern_properties:\n for key in list(value.keys()):\n for pattern, child_schema in self.pattern_properties.items():\n if isinstance(key, str) and re.search(pattern, key):\n item = value[key]\n child_value, error = child_schema.validate_or_error(\n item, strict=strict\n )\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n # Additional properties\n validated_keys = set(validated.keys())\n error_keys = set(\n [message.index[0] for message in error_messages if message.index]\n )\n\n remaining = [\n key for key in value.keys() if key not in validated_keys | error_keys\n ]\n\n if self.additional_properties is True:\n for key in remaining:\n validated[key] = value[key]\n elif self.additional_properties is False:\n for key in remaining:\n text = self.get_error_text(\"invalid_property\")\n message = Message(text=text, code=\"invalid_property\", key=key)\n error_messages.append(message)\n elif self.additional_properties is not None:\n assert isinstance(self.additional_properties, Field)\n child_schema = self.additional_properties\n for key in remaining:\n item = value[key]\n child_value, error = child_schema.validate_or_error(item, strict=strict)\n if not error:\n validated[key] = child_value\n else:\n error_messages += error.messages(add_prefix=key)\n\n if error_messages:\n raise ValidationError(messages=error_messages)\n\n return validated", "has_branch": true, "total_branches": 2} {"prompt_id": 826, "project": "typesystem", "module": "typesystem.fields", "class": "Array", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n items: typing.Union[Field, typing.Sequence[Field]] = None,\n additional_items: typing.Union[Field, bool] = False,\n min_items: int = None,\n max_items: int = None,\n exact_items: int = None,\n unique_items: bool = False,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n items = list(items) if isinstance(items, (list, tuple)) else items\n\n assert (\n items is None\n or isinstance(items, Field)\n or (isinstance(items, list) and all(isinstance(i, Field) for i in items))\n )\n assert isinstance(additional_items, bool) or isinstance(additional_items, Field)\n assert min_items is None or isinstance(min_items, int)\n assert max_items is None or isinstance(max_items, int)\n assert isinstance(unique_items, bool)\n\n if isinstance(items, list):\n if min_items is None:\n min_items = len(items)\n if max_items is None and (additional_items is False):\n max_items = len(items)\n\n if exact_items is not None:\n min_items = exact_items\n max_items = exact_items\n\n self.items = items\n self.additional_items = additional_items\n self.min_items = min_items\n self.max_items = max_items\n self.unique_items = unique_items", "focal_method_lines": [561, 599], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\nclass Union(Field):\n\n errors = {\"null\": \"May not be null.\", \"union\": \"Did not match any valid type.\"}\n\n def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):\n super().__init__(**kwargs)\n\n self.any_of = any_of\n if any([child.allow_null for child in any_of]):\n self.allow_null = True\n\nclass Array(Field):\n\n errors = {\n \"type\": \"Must be an array.\",\n \"null\": \"May not be null.\",\n \"empty\": \"Must not be empty.\",\n \"exact_items\": \"Must have {min_items} items.\",\n \"min_items\": \"Must have at least {min_items} items.\",\n \"max_items\": \"Must have no more than {max_items} items.\",\n \"additional_items\": \"May not contain additional items.\",\n \"unique_items\": \"Items must be unique.\",\n }\n\n def __init__(\n self,\n items: typing.Union[Field, typing.Sequence[Field]] = None,\n additional_items: typing.Union[Field, bool] = False,\n min_items: int = None,\n max_items: int = None,\n exact_items: int = None,\n unique_items: bool = False,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n items = list(items) if isinstance(items, (list, tuple)) else items\n\n assert (\n items is None\n or isinstance(items, Field)\n or (isinstance(items, list) and all(isinstance(i, Field) for i in items))\n )\n assert isinstance(additional_items, bool) or isinstance(additional_items, Field)\n assert min_items is None or isinstance(min_items, int)\n assert max_items is None or isinstance(max_items, int)\n assert isinstance(unique_items, bool)\n\n if isinstance(items, list):\n if min_items is None:\n min_items = len(items)\n if max_items is None and (additional_items is False):\n max_items = len(items)\n\n if exact_items is not None:\n min_items = exact_items\n max_items = exact_items\n\n self.items = items\n self.additional_items = additional_items\n self.min_items = min_items\n self.max_items = max_items\n self.unique_items = unique_items", "has_branch": true, "total_branches": 2} {"prompt_id": 827, "project": "typesystem", "module": "typesystem.fields", "class": "Array", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif not isinstance(value, list):\n raise self.validation_error(\"type\")\n\n if (\n self.min_items is not None\n and self.min_items == self.max_items\n and len(value) != self.min_items\n ):\n raise self.validation_error(\"exact_items\")\n if self.min_items is not None and len(value) < self.min_items:\n if self.min_items == 1:\n raise self.validation_error(\"empty\")\n raise self.validation_error(\"min_items\")\n elif self.max_items is not None and len(value) > self.max_items:\n raise self.validation_error(\"max_items\")\n\n # Ensure all items are of the right type.\n validated = []\n error_messages: typing.List[Message] = []\n if self.unique_items:\n seen_items = Uniqueness()\n\n for pos, item in enumerate(value):\n validator = None\n if isinstance(self.items, list):\n if pos < len(self.items):\n validator = self.items[pos]\n elif isinstance(self.additional_items, Field):\n validator = self.additional_items\n elif self.items is not None:\n validator = self.items\n\n if validator is None:\n validated.append(item)\n else:\n item, error = validator.validate_or_error(item, strict=strict)\n if error:\n error_messages += error.messages(add_prefix=pos)\n else:\n validated.append(item)\n\n if self.unique_items:\n if item in seen_items:\n text = self.get_error_text(\"unique_items\")\n message = Message(text=text, code=\"unique_items\", key=pos)\n error_messages.append(message)\n else:\n seen_items.add(item)\n\n if error_messages:\n raise ValidationError(messages=error_messages)\n\n return validated", "focal_method_lines": [601, 658], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Field:\n\n errors: typing.Dict[str, str] = {}\n\n _creation_counter = 0\n\n def __init__(\n self,\n *,\n title: str = \"\",\n description: str = \"\",\n default: typing.Any = NO_DEFAULT,\n allow_null: bool = False,\n ):\n assert isinstance(title, str)\n assert isinstance(description, str)\n\n if allow_null and default is NO_DEFAULT:\n default = None\n\n if default is not NO_DEFAULT:\n self.default = default\n\n self.title = title\n self.description = description\n self.allow_null = allow_null\n\n # We need this global counter to determine what order fields have\n # been declared in when used with `Schema`.\n self._creation_counter = Field._creation_counter\n Field._creation_counter += 1\n\nclass Array(Field):\n\n errors = {\n \"type\": \"Must be an array.\",\n \"null\": \"May not be null.\",\n \"empty\": \"Must not be empty.\",\n \"exact_items\": \"Must have {min_items} items.\",\n \"min_items\": \"Must have at least {min_items} items.\",\n \"max_items\": \"Must have no more than {max_items} items.\",\n \"additional_items\": \"May not contain additional items.\",\n \"unique_items\": \"Items must be unique.\",\n }\n\n def __init__(\n self,\n items: typing.Union[Field, typing.Sequence[Field]] = None,\n additional_items: typing.Union[Field, bool] = False,\n min_items: int = None,\n max_items: int = None,\n exact_items: int = None,\n unique_items: bool = False,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n items = list(items) if isinstance(items, (list, tuple)) else items\n\n assert (\n items is None\n or isinstance(items, Field)\n or (isinstance(items, list) and all(isinstance(i, Field) for i in items))\n )\n assert isinstance(additional_items, bool) or isinstance(additional_items, Field)\n assert min_items is None or isinstance(min_items, int)\n assert max_items is None or isinstance(max_items, int)\n assert isinstance(unique_items, bool)\n\n if isinstance(items, list):\n if min_items is None:\n min_items = len(items)\n if max_items is None and (additional_items is False):\n max_items = len(items)\n\n if exact_items is not None:\n min_items = exact_items\n max_items = exact_items\n\n self.items = items\n self.additional_items = additional_items\n self.min_items = min_items\n self.max_items = max_items\n self.unique_items = unique_items\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n elif not isinstance(value, list):\n raise self.validation_error(\"type\")\n\n if (\n self.min_items is not None\n and self.min_items == self.max_items\n and len(value) != self.min_items\n ):\n raise self.validation_error(\"exact_items\")\n if self.min_items is not None and len(value) < self.min_items:\n if self.min_items == 1:\n raise self.validation_error(\"empty\")\n raise self.validation_error(\"min_items\")\n elif self.max_items is not None and len(value) > self.max_items:\n raise self.validation_error(\"max_items\")\n\n # Ensure all items are of the right type.\n validated = []\n error_messages: typing.List[Message] = []\n if self.unique_items:\n seen_items = Uniqueness()\n\n for pos, item in enumerate(value):\n validator = None\n if isinstance(self.items, list):\n if pos < len(self.items):\n validator = self.items[pos]\n elif isinstance(self.additional_items, Field):\n validator = self.additional_items\n elif self.items is not None:\n validator = self.items\n\n if validator is None:\n validated.append(item)\n else:\n item, error = validator.validate_or_error(item, strict=strict)\n if error:\n error_messages += error.messages(add_prefix=pos)\n else:\n validated.append(item)\n\n if self.unique_items:\n if item in seen_items:\n text = self.get_error_text(\"unique_items\")\n message = Message(text=text, code=\"unique_items\", key=pos)\n error_messages.append(message)\n else:\n seen_items.add(item)\n\n if error_messages:\n raise ValidationError(messages=error_messages)\n\n return validated", "has_branch": true, "total_branches": 2} {"prompt_id": 828, "project": "typesystem", "module": "typesystem.fields", "class": "Array", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Any:\n if obj is None:\n return None\n\n if isinstance(self.items, list):\n return [\n serializer.serialize(value)\n for serializer, value in zip(self.items, obj)\n ]\n\n if self.items is None:\n return obj\n\n return [self.items.serialize(value) for value in obj]", "focal_method_lines": [660, 673], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Array(Field):\n\n errors = {\n \"type\": \"Must be an array.\",\n \"null\": \"May not be null.\",\n \"empty\": \"Must not be empty.\",\n \"exact_items\": \"Must have {min_items} items.\",\n \"min_items\": \"Must have at least {min_items} items.\",\n \"max_items\": \"Must have no more than {max_items} items.\",\n \"additional_items\": \"May not contain additional items.\",\n \"unique_items\": \"Items must be unique.\",\n }\n\n def __init__(\n self,\n items: typing.Union[Field, typing.Sequence[Field]] = None,\n additional_items: typing.Union[Field, bool] = False,\n min_items: int = None,\n max_items: int = None,\n exact_items: int = None,\n unique_items: bool = False,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n\n items = list(items) if isinstance(items, (list, tuple)) else items\n\n assert (\n items is None\n or isinstance(items, Field)\n or (isinstance(items, list) and all(isinstance(i, Field) for i in items))\n )\n assert isinstance(additional_items, bool) or isinstance(additional_items, Field)\n assert min_items is None or isinstance(min_items, int)\n assert max_items is None or isinstance(max_items, int)\n assert isinstance(unique_items, bool)\n\n if isinstance(items, list):\n if min_items is None:\n min_items = len(items)\n if max_items is None and (additional_items is False):\n max_items = len(items)\n\n if exact_items is not None:\n min_items = exact_items\n max_items = exact_items\n\n self.items = items\n self.additional_items = additional_items\n self.min_items = min_items\n self.max_items = max_items\n self.unique_items = unique_items\n\n def serialize(self, obj: typing.Any) -> typing.Any:\n if obj is None:\n return None\n\n if isinstance(self.items, list):\n return [\n serializer.serialize(value)\n for serializer, value in zip(self.items, obj)\n ]\n\n if self.items is None:\n return obj\n\n return [self.items.serialize(value) for value in obj]", "has_branch": true, "total_branches": 2} {"prompt_id": 829, "project": "typesystem", "module": "typesystem.fields", "class": "Union", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n\n candidate_errors = []\n for child in self.any_of:\n validated, error = child.validate_or_error(value, strict=strict)\n if error is None:\n return validated\n else:\n # If a child returned anything other than a type error, then\n # it is a candidate for returning as the primary error.\n messages = error.messages()\n if (\n len(messages) != 1\n or messages[0].code != \"type\"\n or messages[0].index\n ):\n candidate_errors.append(error)\n\n if len(candidate_errors) == 1:\n # If exactly one child was of the correct type, then we can use\n # the error from the child.\n raise candidate_errors[0]\n raise self.validation_error(\"union\")", "focal_method_lines": [706, 732], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Union(Field):\n\n errors = {\"null\": \"May not be null.\", \"union\": \"Did not match any valid type.\"}\n\n def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):\n super().__init__(**kwargs)\n\n self.any_of = any_of\n if any([child.allow_null for child in any_of]):\n self.allow_null = True\n\n def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n\n candidate_errors = []\n for child in self.any_of:\n validated, error = child.validate_or_error(value, strict=strict)\n if error is None:\n return validated\n else:\n # If a child returned anything other than a type error, then\n # it is a candidate for returning as the primary error.\n messages = error.messages()\n if (\n len(messages) != 1\n or messages[0].code != \"type\"\n or messages[0].index\n ):\n candidate_errors.append(error)\n\n if len(candidate_errors) == 1:\n # If exactly one child was of the correct type, then we can use\n # the error from the child.\n raise candidate_errors[0]\n raise self.validation_error(\"union\")", "has_branch": true, "total_branches": 2} {"prompt_id": 830, "project": "typesystem", "module": "typesystem.fields", "class": "Const", "method": "__init__", "focal_method_txt": " def __init__(self, const: typing.Any, **kwargs: typing.Any):\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.const = const", "focal_method_lines": [751, 754], "in_stack": false, "globals": ["NO_DEFAULT", "FORMATS"], "type_context": "import decimal\nimport re\nimport typing\nfrom math import isfinite\nfrom typesystem import formats\nfrom typesystem.base import Message, ValidationError, ValidationResult\nfrom typesystem.unique import Uniqueness\n\nNO_DEFAULT = object()\nFORMATS = {\n \"date\": formats.DateFormat(),\n \"time\": formats.TimeFormat(),\n \"datetime\": formats.DateTimeFormat(),\n \"uuid\": formats.UUIDFormat(),\n}\n\nclass Const(Field):\n\n errors = {\"only_null\": \"Must be null.\", \"const\": \"Must be the value '{const}'.\"}\n\n def __init__(self, const: typing.Any, **kwargs: typing.Any):\n assert \"allow_null\" not in kwargs\n super().__init__(**kwargs)\n self.const = const", "has_branch": false, "total_branches": 0} {"prompt_id": 831, "project": "typesystem", "module": "typesystem.formats", "class": "DateFormat", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any) -> datetime.date:\n match = DATE_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n kwargs = {k: int(v) for k, v in match.groupdict().items()}\n try:\n return datetime.date(**kwargs)\n except ValueError:\n raise self.validation_error(\"invalid\")", "focal_method_lines": [52, 61], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass DateFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid date format.\",\n \"invalid\": \"Must be a real date.\",\n }\n\n def validate(self, value: typing.Any) -> datetime.date:\n match = DATE_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n kwargs = {k: int(v) for k, v in match.groupdict().items()}\n try:\n return datetime.date(**kwargs)\n except ValueError:\n raise self.validation_error(\"invalid\")", "has_branch": true, "total_branches": 2} {"prompt_id": 832, "project": "typesystem", "module": "typesystem.formats", "class": "DateFormat", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.date)\n\n return obj.isoformat()", "focal_method_lines": [63, 69], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass DateFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid date format.\",\n \"invalid\": \"Must be a real date.\",\n }\n\n def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.date)\n\n return obj.isoformat()", "has_branch": true, "total_branches": 2} {"prompt_id": 833, "project": "typesystem", "module": "typesystem.formats", "class": "TimeFormat", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any) -> datetime.time:\n match = TIME_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n groups = match.groupdict()\n if groups[\"microsecond\"]:\n groups[\"microsecond\"] = groups[\"microsecond\"].ljust(6, \"0\")\n\n kwargs = {k: int(v) for k, v in groups.items() if v is not None}\n try:\n return datetime.time(tzinfo=None, **kwargs)\n except ValueError:\n raise self.validation_error(\"invalid\")", "focal_method_lines": [81, 94], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass TimeFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid time format.\",\n \"invalid\": \"Must be a real time.\",\n }\n\n def validate(self, value: typing.Any) -> datetime.time:\n match = TIME_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n groups = match.groupdict()\n if groups[\"microsecond\"]:\n groups[\"microsecond\"] = groups[\"microsecond\"].ljust(6, \"0\")\n\n kwargs = {k: int(v) for k, v in groups.items() if v is not None}\n try:\n return datetime.time(tzinfo=None, **kwargs)\n except ValueError:\n raise self.validation_error(\"invalid\")", "has_branch": true, "total_branches": 2} {"prompt_id": 834, "project": "typesystem", "module": "typesystem.formats", "class": "TimeFormat", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.time)\n\n return obj.isoformat()", "focal_method_lines": [96, 102], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass TimeFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid time format.\",\n \"invalid\": \"Must be a real time.\",\n }\n\n def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.time)\n\n return obj.isoformat()", "has_branch": true, "total_branches": 2} {"prompt_id": 835, "project": "typesystem", "module": "typesystem.formats", "class": "DateTimeFormat", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any) -> datetime.datetime:\n match = DATETIME_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n groups = match.groupdict()\n if groups[\"microsecond\"]:\n groups[\"microsecond\"] = groups[\"microsecond\"].ljust(6, \"0\")\n\n tzinfo_str = groups.pop(\"tzinfo\")\n if tzinfo_str == \"Z\":\n tzinfo = datetime.timezone.utc\n elif tzinfo_str is not None:\n offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0\n offset_hours = int(tzinfo_str[1:3])\n delta = datetime.timedelta(hours=offset_hours, minutes=offset_mins)\n if tzinfo_str[0] == \"-\":\n delta = -delta\n tzinfo = datetime.timezone(delta)\n else:\n tzinfo = None\n\n kwargs = {k: int(v) for k, v in groups.items() if v is not None}\n try:\n return datetime.datetime(**kwargs, tzinfo=tzinfo) # type: ignore\n except ValueError:\n raise self.validation_error(\"invalid\")", "focal_method_lines": [114, 140], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass DateTimeFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid datetime format.\",\n \"invalid\": \"Must be a real datetime.\",\n }\n\n def validate(self, value: typing.Any) -> datetime.datetime:\n match = DATETIME_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n groups = match.groupdict()\n if groups[\"microsecond\"]:\n groups[\"microsecond\"] = groups[\"microsecond\"].ljust(6, \"0\")\n\n tzinfo_str = groups.pop(\"tzinfo\")\n if tzinfo_str == \"Z\":\n tzinfo = datetime.timezone.utc\n elif tzinfo_str is not None:\n offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0\n offset_hours = int(tzinfo_str[1:3])\n delta = datetime.timedelta(hours=offset_hours, minutes=offset_mins)\n if tzinfo_str[0] == \"-\":\n delta = -delta\n tzinfo = datetime.timezone(delta)\n else:\n tzinfo = None\n\n kwargs = {k: int(v) for k, v in groups.items() if v is not None}\n try:\n return datetime.datetime(**kwargs, tzinfo=tzinfo) # type: ignore\n except ValueError:\n raise self.validation_error(\"invalid\")", "has_branch": true, "total_branches": 2} {"prompt_id": 836, "project": "typesystem", "module": "typesystem.formats", "class": "DateTimeFormat", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.datetime)\n\n value = obj.isoformat()\n\n if value.endswith(\"+00:00\"):\n value = value[:-6] + \"Z\"\n\n return value", "focal_method_lines": [142, 153], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass DateTimeFormat(BaseFormat):\n\n errors = {\n \"format\": \"Must be a valid datetime format.\",\n \"invalid\": \"Must be a real datetime.\",\n }\n\n def serialize(self, obj: typing.Any) -> typing.Union[str, None]:\n if obj is None:\n return None\n\n assert isinstance(obj, datetime.datetime)\n\n value = obj.isoformat()\n\n if value.endswith(\"+00:00\"):\n value = value[:-6] + \"Z\"\n\n return value", "has_branch": true, "total_branches": 2} {"prompt_id": 837, "project": "typesystem", "module": "typesystem.formats", "class": "UUIDFormat", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any) -> uuid.UUID:\n match = UUID_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n return uuid.UUID(value)", "focal_method_lines": [162, 167], "in_stack": false, "globals": ["DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX"], "type_context": "import datetime\nimport re\nimport typing\nimport uuid\nfrom typesystem.base import ValidationError\n\nDATE_REGEX = re.compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\nTIME_REGEX = re.compile(\n r\"(?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n)\nDATETIME_REGEX = re.compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"[T ](?P\\d{1,2}):(?P\\d{1,2})\"\n r\"(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?\"\n r\"(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\nUUID_REGEX = re.compile(\n r\"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\"\n)\n\nclass UUIDFormat(BaseFormat):\n\n errors = {\"format\": \"Must be valid UUID format.\"}\n\n def validate(self, value: typing.Any) -> uuid.UUID:\n match = UUID_REGEX.match(value)\n if not match:\n raise self.validation_error(\"format\")\n\n return uuid.UUID(value)", "has_branch": true, "total_branches": 2} {"prompt_id": 838, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "from_json_schema", "focal_method_txt": "def from_json_schema(\n data: typing.Union[bool, dict], definitions: SchemaDefinitions = None\n) -> Field:\n if isinstance(data, bool):\n return {True: Any(), False: NeverMatch()}[data]\n\n if definitions is None:\n definitions = SchemaDefinitions()\n for key, value in data.get(\"definitions\", {}).items():\n ref = f\"#/definitions/{key}\"\n definitions[ref] = from_json_schema(value, definitions=definitions)\n\n if \"$ref\" in data:\n return ref_from_json_schema(data, definitions=definitions)\n\n constraints = [] # typing.List[Field]\n if any([property_name in data for property_name in TYPE_CONSTRAINTS]):\n constraints.append(type_from_json_schema(data, definitions=definitions))\n if \"enum\" in data:\n constraints.append(enum_from_json_schema(data, definitions=definitions))\n if \"const\" in data:\n constraints.append(const_from_json_schema(data, definitions=definitions))\n if \"allOf\" in data:\n constraints.append(all_of_from_json_schema(data, definitions=definitions))\n if \"anyOf\" in data:\n constraints.append(any_of_from_json_schema(data, definitions=definitions))\n if \"oneOf\" in data:\n constraints.append(one_of_from_json_schema(data, definitions=definitions))\n if \"not\" in data:\n constraints.append(not_from_json_schema(data, definitions=definitions))\n if \"if\" in data:\n constraints.append(if_then_else_from_json_schema(data, definitions=definitions))\n\n if len(constraints) == 1:\n return constraints[0]\n elif len(constraints) > 1:\n return AllOf(constraints)\n return Any()", "focal_method_lines": [109, 146], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef from_json_schema(\n data: typing.Union[bool, dict], definitions: SchemaDefinitions = None\n) -> Field:\n if isinstance(data, bool):\n return {True: Any(), False: NeverMatch()}[data]\n\n if definitions is None:\n definitions = SchemaDefinitions()\n for key, value in data.get(\"definitions\", {}).items():\n ref = f\"#/definitions/{key}\"\n definitions[ref] = from_json_schema(value, definitions=definitions)\n\n if \"$ref\" in data:\n return ref_from_json_schema(data, definitions=definitions)\n\n constraints = [] # typing.List[Field]\n if any([property_name in data for property_name in TYPE_CONSTRAINTS]):\n constraints.append(type_from_json_schema(data, definitions=definitions))\n if \"enum\" in data:\n constraints.append(enum_from_json_schema(data, definitions=definitions))\n if \"const\" in data:\n constraints.append(const_from_json_schema(data, definitions=definitions))\n if \"allOf\" in data:\n constraints.append(all_of_from_json_schema(data, definitions=definitions))\n if \"anyOf\" in data:\n constraints.append(any_of_from_json_schema(data, definitions=definitions))\n if \"oneOf\" in data:\n constraints.append(one_of_from_json_schema(data, definitions=definitions))\n if \"not\" in data:\n constraints.append(not_from_json_schema(data, definitions=definitions))\n if \"if\" in data:\n constraints.append(if_then_else_from_json_schema(data, definitions=definitions))\n\n if len(constraints) == 1:\n return constraints[0]\n elif len(constraints) > 1:\n return AllOf(constraints)\n return Any()", "has_branch": true, "total_branches": 2} {"prompt_id": 839, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "type_from_json_schema", "focal_method_txt": "def type_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n \"\"\"\n Build a typed field or union of typed fields from a JSON schema object.\n \"\"\"\n type_strings, allow_null = get_valid_types(data)\n\n if len(type_strings) > 1:\n items = [\n from_json_schema_type(\n data, type_string=type_string, allow_null=False, definitions=definitions\n )\n for type_string in type_strings\n ]\n return Union(any_of=items, allow_null=allow_null)\n\n if len(type_strings) == 0:\n return {True: Const(None), False: NeverMatch()}[allow_null]\n\n type_string = type_strings.pop()\n return from_json_schema_type(\n data, type_string=type_string, allow_null=allow_null, definitions=definitions\n )", "focal_method_lines": [149, 168], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef type_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n \"\"\"\n Build a typed field or union of typed fields from a JSON schema object.\n \"\"\"\n type_strings, allow_null = get_valid_types(data)\n\n if len(type_strings) > 1:\n items = [\n from_json_schema_type(\n data, type_string=type_string, allow_null=False, definitions=definitions\n )\n for type_string in type_strings\n ]\n return Union(any_of=items, allow_null=allow_null)\n\n if len(type_strings) == 0:\n return {True: Const(None), False: NeverMatch()}[allow_null]\n\n type_string = type_strings.pop()\n return from_json_schema_type(\n data, type_string=type_string, allow_null=allow_null, definitions=definitions\n )", "has_branch": true, "total_branches": 2} {"prompt_id": 840, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "get_valid_types", "focal_method_txt": "def get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]:\n \"\"\"\n Returns a two-tuple of `(type_strings, allow_null)`.\n \"\"\"\n\n type_strings = data.get(\"type\", [])\n if isinstance(type_strings, str):\n type_strings = {type_strings}\n else:\n type_strings = set(type_strings)\n\n if not type_strings:\n type_strings = {\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"}\n\n if \"number\" in type_strings:\n type_strings.discard(\"integer\")\n\n allow_null = False\n if \"null\" in type_strings:\n allow_null = True\n type_strings.remove(\"null\")\n\n return (type_strings, allow_null)", "focal_method_lines": [173, 195], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]:\n \"\"\"\n Returns a two-tuple of `(type_strings, allow_null)`.\n \"\"\"\n\n type_strings = data.get(\"type\", [])\n if isinstance(type_strings, str):\n type_strings = {type_strings}\n else:\n type_strings = set(type_strings)\n\n if not type_strings:\n type_strings = {\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"}\n\n if \"number\" in type_strings:\n type_strings.discard(\"integer\")\n\n allow_null = False\n if \"null\" in type_strings:\n allow_null = True\n type_strings.remove(\"null\")\n\n return (type_strings, allow_null)", "has_branch": true, "total_branches": 2} {"prompt_id": 841, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "from_json_schema_type", "focal_method_txt": "def from_json_schema_type(\n data: dict, type_string: str, allow_null: bool, definitions: SchemaDefinitions\n) -> Field:\n \"\"\"\n Build a typed field from a JSON schema object.\n \"\"\"\n\n if type_string == \"number\":\n kwargs = {\n \"allow_null\": allow_null,\n \"minimum\": data.get(\"minimum\", None),\n \"maximum\": data.get(\"maximum\", None),\n \"exclusive_minimum\": data.get(\"exclusiveMinimum\", None),\n \"exclusive_maximum\": data.get(\"exclusiveMaximum\", None),\n \"multiple_of\": data.get(\"multipleOf\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Float(**kwargs)\n\n elif type_string == \"integer\":\n kwargs = {\n \"allow_null\": allow_null,\n \"minimum\": data.get(\"minimum\", None),\n \"maximum\": data.get(\"maximum\", None),\n \"exclusive_minimum\": data.get(\"exclusiveMinimum\", None),\n \"exclusive_maximum\": data.get(\"exclusiveMaximum\", None),\n \"multiple_of\": data.get(\"multipleOf\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Integer(**kwargs)\n\n elif type_string == \"string\":\n min_length = data.get(\"minLength\", 0)\n kwargs = {\n \"allow_null\": allow_null,\n \"allow_blank\": min_length == 0,\n \"min_length\": min_length if min_length > 1 else None,\n \"max_length\": data.get(\"maxLength\", None),\n \"format\": data.get(\"format\"),\n \"pattern\": data.get(\"pattern\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return String(**kwargs)\n\n elif type_string == \"boolean\":\n kwargs = {\"allow_null\": allow_null, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Boolean(**kwargs)\n\n elif type_string == \"array\":\n items = data.get(\"items\", None)\n if items is None:\n items_argument: typing.Union[None, Field, typing.List[Field]] = None\n elif isinstance(items, list):\n items_argument = [\n from_json_schema(item, definitions=definitions) for item in items\n ]\n else:\n items_argument = from_json_schema(items, definitions=definitions)\n\n additional_items = data.get(\"additionalItems\", None)\n if additional_items is None:\n additional_items_argument: typing.Union[bool, Field] = True\n elif isinstance(additional_items, bool):\n additional_items_argument = additional_items\n else:\n additional_items_argument = from_json_schema(\n additional_items, definitions=definitions\n )\n\n kwargs = {\n \"allow_null\": allow_null,\n \"min_items\": data.get(\"minItems\", 0),\n \"max_items\": data.get(\"maxItems\", None),\n \"additional_items\": additional_items_argument,\n \"items\": items_argument,\n \"unique_items\": data.get(\"uniqueItems\", False),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Array(**kwargs)\n\n elif type_string == \"object\":\n properties = data.get(\"properties\", None)\n if properties is None:\n properties_argument: typing.Optional[typing.Dict[str, Field]] = None\n else:\n properties_argument = {\n key: from_json_schema(value, definitions=definitions)\n for key, value in properties.items()\n }\n\n pattern_properties = data.get(\"patternProperties\", None)\n if pattern_properties is None:\n pattern_properties_argument: typing.Optional[typing.Dict[str, Field]] = (\n None\n )\n else:\n pattern_properties_argument = {\n key: from_json_schema(value, definitions=definitions)\n for key, value in pattern_properties.items()\n }\n\n additional_properties = data.get(\"additionalProperties\", None)\n if additional_properties is None:\n additional_properties_argument: typing.Union[None, bool, Field] = (None)\n elif isinstance(additional_properties, bool):\n additional_properties_argument = additional_properties\n else:\n additional_properties_argument = from_json_schema(\n additional_properties, definitions=definitions\n )\n\n property_names = data.get(\"propertyNames\", None)\n if property_names is None:\n property_names_argument: typing.Optional[Field] = None\n else:\n property_names_argument = from_json_schema(\n property_names, definitions=definitions\n )\n\n kwargs = {\n \"allow_null\": allow_null,\n \"properties\": properties_argument,\n \"pattern_properties\": pattern_properties_argument,\n \"additional_properties\": additional_properties_argument,\n \"property_names\": property_names_argument,\n \"min_properties\": data.get(\"minProperties\", None),\n \"max_properties\": data.get(\"maxProperties\", None),\n \"required\": data.get(\"required\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Object(**kwargs)\n\n assert False, f\"Invalid argument type_string={type_string!r}\"", "focal_method_lines": [198, 328], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef from_json_schema_type(\n data: dict, type_string: str, allow_null: bool, definitions: SchemaDefinitions\n) -> Field:\n \"\"\"\n Build a typed field from a JSON schema object.\n \"\"\"\n\n if type_string == \"number\":\n kwargs = {\n \"allow_null\": allow_null,\n \"minimum\": data.get(\"minimum\", None),\n \"maximum\": data.get(\"maximum\", None),\n \"exclusive_minimum\": data.get(\"exclusiveMinimum\", None),\n \"exclusive_maximum\": data.get(\"exclusiveMaximum\", None),\n \"multiple_of\": data.get(\"multipleOf\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Float(**kwargs)\n\n elif type_string == \"integer\":\n kwargs = {\n \"allow_null\": allow_null,\n \"minimum\": data.get(\"minimum\", None),\n \"maximum\": data.get(\"maximum\", None),\n \"exclusive_minimum\": data.get(\"exclusiveMinimum\", None),\n \"exclusive_maximum\": data.get(\"exclusiveMaximum\", None),\n \"multiple_of\": data.get(\"multipleOf\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Integer(**kwargs)\n\n elif type_string == \"string\":\n min_length = data.get(\"minLength\", 0)\n kwargs = {\n \"allow_null\": allow_null,\n \"allow_blank\": min_length == 0,\n \"min_length\": min_length if min_length > 1 else None,\n \"max_length\": data.get(\"maxLength\", None),\n \"format\": data.get(\"format\"),\n \"pattern\": data.get(\"pattern\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return String(**kwargs)\n\n elif type_string == \"boolean\":\n kwargs = {\"allow_null\": allow_null, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Boolean(**kwargs)\n\n elif type_string == \"array\":\n items = data.get(\"items\", None)\n if items is None:\n items_argument: typing.Union[None, Field, typing.List[Field]] = None\n elif isinstance(items, list):\n items_argument = [\n from_json_schema(item, definitions=definitions) for item in items\n ]\n else:\n items_argument = from_json_schema(items, definitions=definitions)\n\n additional_items = data.get(\"additionalItems\", None)\n if additional_items is None:\n additional_items_argument: typing.Union[bool, Field] = True\n elif isinstance(additional_items, bool):\n additional_items_argument = additional_items\n else:\n additional_items_argument = from_json_schema(\n additional_items, definitions=definitions\n )\n\n kwargs = {\n \"allow_null\": allow_null,\n \"min_items\": data.get(\"minItems\", 0),\n \"max_items\": data.get(\"maxItems\", None),\n \"additional_items\": additional_items_argument,\n \"items\": items_argument,\n \"unique_items\": data.get(\"uniqueItems\", False),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Array(**kwargs)\n\n elif type_string == \"object\":\n properties = data.get(\"properties\", None)\n if properties is None:\n properties_argument: typing.Optional[typing.Dict[str, Field]] = None\n else:\n properties_argument = {\n key: from_json_schema(value, definitions=definitions)\n for key, value in properties.items()\n }\n\n pattern_properties = data.get(\"patternProperties\", None)\n if pattern_properties is None:\n pattern_properties_argument: typing.Optional[typing.Dict[str, Field]] = (\n None\n )\n else:\n pattern_properties_argument = {\n key: from_json_schema(value, definitions=definitions)\n for key, value in pattern_properties.items()\n }\n\n additional_properties = data.get(\"additionalProperties\", None)\n if additional_properties is None:\n additional_properties_argument: typing.Union[None, bool, Field] = (None)\n elif isinstance(additional_properties, bool):\n additional_properties_argument = additional_properties\n else:\n additional_properties_argument = from_json_schema(\n additional_properties, definitions=definitions\n )\n\n property_names = data.get(\"propertyNames\", None)\n if property_names is None:\n property_names_argument: typing.Optional[Field] = None\n else:\n property_names_argument = from_json_schema(\n property_names, definitions=definitions\n )\n\n kwargs = {\n \"allow_null\": allow_null,\n \"properties\": properties_argument,\n \"pattern_properties\": pattern_properties_argument,\n \"additional_properties\": additional_properties_argument,\n \"property_names\": property_names_argument,\n \"min_properties\": data.get(\"minProperties\", None),\n \"max_properties\": data.get(\"maxProperties\", None),\n \"required\": data.get(\"required\", None),\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return Object(**kwargs)\n\n assert False, f\"Invalid argument type_string={type_string!r}\"", "has_branch": true, "total_branches": 2} {"prompt_id": 842, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "ref_from_json_schema", "focal_method_txt": "def ref_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n reference_string = data[\"$ref\"]\n assert reference_string.startswith(\"#/\"), \"Unsupported $ref style in document.\"\n return Reference(to=reference_string, definitions=definitions)", "focal_method_lines": [333, 336], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef ref_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n reference_string = data[\"$ref\"]\n assert reference_string.startswith(\"#/\"), \"Unsupported $ref style in document.\"\n return Reference(to=reference_string, definitions=definitions)", "has_branch": false, "total_branches": 0} {"prompt_id": 843, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "enum_from_json_schema", "focal_method_txt": "def enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n choices = [(item, item) for item in data[\"enum\"]]\n kwargs = {\"choices\": choices, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Choice(**kwargs)", "focal_method_lines": [339, 342], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n choices = [(item, item) for item in data[\"enum\"]]\n kwargs = {\"choices\": choices, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Choice(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 844, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "const_from_json_schema", "focal_method_txt": "def const_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n const = data[\"const\"]\n kwargs = {\"const\": const, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Const(**kwargs)", "focal_method_lines": [345, 348], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef const_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n const = data[\"const\"]\n kwargs = {\"const\": const, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Const(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 845, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "all_of_from_json_schema", "focal_method_txt": "def all_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n all_of = [from_json_schema(item, definitions=definitions) for item in data[\"allOf\"]]\n kwargs = {\"all_of\": all_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return AllOf(**kwargs)", "focal_method_lines": [351, 354], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef all_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n all_of = [from_json_schema(item, definitions=definitions) for item in data[\"allOf\"]]\n kwargs = {\"all_of\": all_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return AllOf(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 846, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "any_of_from_json_schema", "focal_method_txt": "def any_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n any_of = [from_json_schema(item, definitions=definitions) for item in data[\"anyOf\"]]\n kwargs = {\"any_of\": any_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Union(**kwargs)", "focal_method_lines": [357, 360], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef any_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n any_of = [from_json_schema(item, definitions=definitions) for item in data[\"anyOf\"]]\n kwargs = {\"any_of\": any_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Union(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 847, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "one_of_from_json_schema", "focal_method_txt": "def one_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n one_of = [from_json_schema(item, definitions=definitions) for item in data[\"oneOf\"]]\n kwargs = {\"one_of\": one_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return OneOf(**kwargs)", "focal_method_lines": [363, 366], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef one_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n one_of = [from_json_schema(item, definitions=definitions) for item in data[\"oneOf\"]]\n kwargs = {\"one_of\": one_of, \"default\": data.get(\"default\", NO_DEFAULT)}\n return OneOf(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 848, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "not_from_json_schema", "focal_method_txt": "def not_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n negated = from_json_schema(data[\"not\"], definitions=definitions)\n kwargs = {\"negated\": negated, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Not(**kwargs)", "focal_method_lines": [369, 372], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef not_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n negated = from_json_schema(data[\"not\"], definitions=definitions)\n kwargs = {\"negated\": negated, \"default\": data.get(\"default\", NO_DEFAULT)}\n return Not(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 849, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "if_then_else_from_json_schema", "focal_method_txt": "def if_then_else_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n if_clause = from_json_schema(data[\"if\"], definitions=definitions)\n then_clause = (\n from_json_schema(data[\"then\"], definitions=definitions)\n if \"then\" in data\n else None\n )\n else_clause = (\n from_json_schema(data[\"else\"], definitions=definitions)\n if \"else\" in data\n else None\n )\n kwargs = {\n \"if_clause\": if_clause,\n \"then_clause\": then_clause,\n \"else_clause\": else_clause,\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return IfThenElse(**kwargs)", "focal_method_lines": [375, 393], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef if_then_else_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:\n if_clause = from_json_schema(data[\"if\"], definitions=definitions)\n then_clause = (\n from_json_schema(data[\"then\"], definitions=definitions)\n if \"then\" in data\n else None\n )\n else_clause = (\n from_json_schema(data[\"else\"], definitions=definitions)\n if \"else\" in data\n else None\n )\n kwargs = {\n \"if_clause\": if_clause,\n \"then_clause\": then_clause,\n \"else_clause\": else_clause,\n \"default\": data.get(\"default\", NO_DEFAULT),\n }\n return IfThenElse(**kwargs)", "has_branch": false, "total_branches": 0} {"prompt_id": 850, "project": "typesystem", "module": "typesystem.json_schema", "class": "", "method": "to_json_schema", "focal_method_txt": "def to_json_schema(\n arg: typing.Union[Field, typing.Type[Schema]], _definitions: dict = None\n) -> typing.Union[bool, dict]:\n\n if isinstance(arg, Any):\n return True\n elif isinstance(arg, NeverMatch):\n return False\n\n data: dict = {}\n is_root = _definitions is None\n definitions = {} if _definitions is None else _definitions\n\n if isinstance(arg, Field):\n field = arg\n elif isinstance(arg, SchemaDefinitions):\n field = None\n for key, value in arg.items():\n definitions[key] = to_json_schema(value, _definitions=definitions)\n else:\n field = arg.make_validator()\n\n if isinstance(field, Reference):\n data[\"$ref\"] = f\"#/definitions/{field.target_string}\"\n definitions[field.target_string] = to_json_schema(\n field.target, _definitions=definitions\n )\n\n elif isinstance(field, String):\n data[\"type\"] = [\"string\", \"null\"] if field.allow_null else \"string\"\n data.update(get_standard_properties(field))\n if field.min_length is not None or not field.allow_blank:\n data[\"minLength\"] = field.min_length or 1\n if field.max_length is not None:\n data[\"maxLength\"] = field.max_length\n if field.pattern_regex is not None:\n if field.pattern_regex.flags != re.RegexFlag.UNICODE:\n flags = re.RegexFlag(field.pattern_regex.flags)\n raise ValueError(\n f\"Cannot convert regular expression with non-standard flags \"\n f\"to JSON schema: {flags!s}\"\n )\n data[\"pattern\"] = field.pattern_regex.pattern\n if field.format is not None:\n data[\"format\"] = field.format\n\n elif isinstance(field, (Integer, Float, Decimal)):\n base_type = \"integer\" if isinstance(field, Integer) else \"number\"\n data[\"type\"] = [base_type, \"null\"] if field.allow_null else base_type\n data.update(get_standard_properties(field))\n if field.minimum is not None:\n data[\"minimum\"] = field.minimum\n if field.maximum is not None:\n data[\"maximum\"] = field.maximum\n if field.exclusive_minimum is not None:\n data[\"exclusiveMinimum\"] = field.exclusive_minimum\n if field.exclusive_maximum is not None:\n data[\"exclusiveMaximum\"] = field.exclusive_maximum\n if field.multiple_of is not None:\n data[\"multipleOf\"] = field.multiple_of\n\n elif isinstance(field, Boolean):\n data[\"type\"] = [\"boolean\", \"null\"] if field.allow_null else \"boolean\"\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Array):\n data[\"type\"] = [\"array\", \"null\"] if field.allow_null else \"array\"\n data.update(get_standard_properties(field))\n if field.min_items is not None:\n data[\"minItems\"] = field.min_items\n if field.max_items is not None:\n data[\"maxItems\"] = field.max_items\n if field.items is not None:\n if isinstance(field.items, (list, tuple)):\n data[\"items\"] = [\n to_json_schema(item, _definitions=definitions)\n for item in field.items\n ]\n else:\n data[\"items\"] = to_json_schema(field.items, _definitions=definitions)\n if field.additional_items is not None:\n if isinstance(field.additional_items, bool):\n data[\"additionalItems\"] = field.additional_items\n else:\n data[\"additionalItems\"] = to_json_schema(\n field.additional_items, _definitions=definitions\n )\n if field.unique_items is not False:\n data[\"uniqueItems\"] = True\n\n elif isinstance(field, Object):\n data[\"type\"] = [\"object\", \"null\"] if field.allow_null else \"object\"\n data.update(get_standard_properties(field))\n if field.properties:\n data[\"properties\"] = {\n key: to_json_schema(value, _definitions=definitions)\n for key, value in field.properties.items()\n }\n if field.pattern_properties:\n data[\"patternProperties\"] = {\n key: to_json_schema(value, _definitions=definitions)\n for key, value in field.pattern_properties.items()\n }\n if field.additional_properties is not None:\n if isinstance(field.additional_properties, bool):\n data[\"additionalProperties\"] = field.additional_properties\n else:\n data[\"additionalProperties\"] = to_json_schema(\n field.additional_properties, _definitions=definitions\n )\n if field.property_names is not None:\n data[\"propertyNames\"] = to_json_schema(\n field.property_names, _definitions=definitions\n )\n if field.max_properties is not None:\n data[\"maxProperties\"] = field.max_properties\n if field.min_properties is not None:\n data[\"minProperties\"] = field.min_properties\n if field.required:\n data[\"required\"] = field.required\n\n elif isinstance(field, Choice):\n data[\"enum\"] = [key for key, value in field.choices]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Const):\n data[\"const\"] = field.const\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Union):\n data[\"anyOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.any_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, OneOf):\n data[\"oneOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.one_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, AllOf):\n data[\"allOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.all_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, IfThenElse):\n data[\"if\"] = to_json_schema(field.if_clause, _definitions=definitions)\n if field.then_clause is not None:\n data[\"then\"] = to_json_schema(field.then_clause, _definitions=definitions)\n if field.else_clause is not None:\n data[\"else\"] = to_json_schema(field.else_clause, _definitions=definitions)\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Not):\n data[\"not\"] = to_json_schema(field.negated, _definitions=definitions)\n data.update(get_standard_properties(field))\n\n elif field is not None:\n name = type(field).__qualname__\n raise ValueError(f\"Cannot convert field type {name!r} to JSON Schema\")\n\n if is_root and definitions:\n data[\"definitions\"] = definitions\n return data", "focal_method_lines": [396, 561], "in_stack": false, "globals": ["TYPE_CONSTRAINTS", "definitions", "JSONSchema"], "type_context": "import re\nimport typing\nfrom typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf\nfrom typesystem.fields import (\n NO_DEFAULT,\n Any,\n Array,\n Boolean,\n Choice,\n Const,\n Decimal,\n Field,\n Float,\n Integer,\n Number,\n Object,\n String,\n Union,\n)\nfrom typesystem.schemas import Reference, Schema, SchemaDefinitions\n\nTYPE_CONSTRAINTS = {\n \"additionalItems\",\n \"additionalProperties\",\n \"boolean_schema\",\n \"contains\",\n \"dependencies\",\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"items\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"properties\",\n \"propertyNames\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n}\ndefinitions[\"JSONSchema\"] = JSONSchema\nJSONSchema = (\n Object(\n properties={\n \"$ref\": String(),\n \"type\": String() | Array(items=String()),\n \"enum\": Array(unique_items=True, min_items=1),\n \"definitions\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n # String\n \"minLength\": Integer(minimum=0),\n \"maxLength\": Integer(minimum=0),\n \"pattern\": String(format=\"regex\"),\n \"format\": String(),\n # Numeric\n \"minimum\": Number(),\n \"maximum\": Number(),\n \"exclusiveMinimum\": Number(),\n \"exclusiveMaximum\": Number(),\n \"multipleOf\": Number(exclusive_minimum=0),\n # Object\n \"properties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"minProperties\": Integer(minimum=0),\n \"maxProperties\": Integer(minimum=0),\n \"patternProperties\": Object(\n additional_properties=Reference(\"JSONSchema\", definitions=definitions)\n ),\n \"additionalProperties\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"required\": Array(items=String(), unique_items=True),\n # Array\n \"items\": (\n Reference(\"JSONSchema\", definitions=definitions)\n | Array(\n items=Reference(\"JSONSchema\", definitions=definitions), min_items=1\n )\n ),\n \"additionalItems\": (\n Reference(\"JSONSchema\", definitions=definitions) | Boolean()\n ),\n \"minItems\": Integer(minimum=0),\n \"maxItems\": Integer(minimum=0),\n \"uniqueItems\": Boolean(),\n }\n )\n | Boolean()\n)\n\ndef to_json_schema(\n arg: typing.Union[Field, typing.Type[Schema]], _definitions: dict = None\n) -> typing.Union[bool, dict]:\n\n if isinstance(arg, Any):\n return True\n elif isinstance(arg, NeverMatch):\n return False\n\n data: dict = {}\n is_root = _definitions is None\n definitions = {} if _definitions is None else _definitions\n\n if isinstance(arg, Field):\n field = arg\n elif isinstance(arg, SchemaDefinitions):\n field = None\n for key, value in arg.items():\n definitions[key] = to_json_schema(value, _definitions=definitions)\n else:\n field = arg.make_validator()\n\n if isinstance(field, Reference):\n data[\"$ref\"] = f\"#/definitions/{field.target_string}\"\n definitions[field.target_string] = to_json_schema(\n field.target, _definitions=definitions\n )\n\n elif isinstance(field, String):\n data[\"type\"] = [\"string\", \"null\"] if field.allow_null else \"string\"\n data.update(get_standard_properties(field))\n if field.min_length is not None or not field.allow_blank:\n data[\"minLength\"] = field.min_length or 1\n if field.max_length is not None:\n data[\"maxLength\"] = field.max_length\n if field.pattern_regex is not None:\n if field.pattern_regex.flags != re.RegexFlag.UNICODE:\n flags = re.RegexFlag(field.pattern_regex.flags)\n raise ValueError(\n f\"Cannot convert regular expression with non-standard flags \"\n f\"to JSON schema: {flags!s}\"\n )\n data[\"pattern\"] = field.pattern_regex.pattern\n if field.format is not None:\n data[\"format\"] = field.format\n\n elif isinstance(field, (Integer, Float, Decimal)):\n base_type = \"integer\" if isinstance(field, Integer) else \"number\"\n data[\"type\"] = [base_type, \"null\"] if field.allow_null else base_type\n data.update(get_standard_properties(field))\n if field.minimum is not None:\n data[\"minimum\"] = field.minimum\n if field.maximum is not None:\n data[\"maximum\"] = field.maximum\n if field.exclusive_minimum is not None:\n data[\"exclusiveMinimum\"] = field.exclusive_minimum\n if field.exclusive_maximum is not None:\n data[\"exclusiveMaximum\"] = field.exclusive_maximum\n if field.multiple_of is not None:\n data[\"multipleOf\"] = field.multiple_of\n\n elif isinstance(field, Boolean):\n data[\"type\"] = [\"boolean\", \"null\"] if field.allow_null else \"boolean\"\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Array):\n data[\"type\"] = [\"array\", \"null\"] if field.allow_null else \"array\"\n data.update(get_standard_properties(field))\n if field.min_items is not None:\n data[\"minItems\"] = field.min_items\n if field.max_items is not None:\n data[\"maxItems\"] = field.max_items\n if field.items is not None:\n if isinstance(field.items, (list, tuple)):\n data[\"items\"] = [\n to_json_schema(item, _definitions=definitions)\n for item in field.items\n ]\n else:\n data[\"items\"] = to_json_schema(field.items, _definitions=definitions)\n if field.additional_items is not None:\n if isinstance(field.additional_items, bool):\n data[\"additionalItems\"] = field.additional_items\n else:\n data[\"additionalItems\"] = to_json_schema(\n field.additional_items, _definitions=definitions\n )\n if field.unique_items is not False:\n data[\"uniqueItems\"] = True\n\n elif isinstance(field, Object):\n data[\"type\"] = [\"object\", \"null\"] if field.allow_null else \"object\"\n data.update(get_standard_properties(field))\n if field.properties:\n data[\"properties\"] = {\n key: to_json_schema(value, _definitions=definitions)\n for key, value in field.properties.items()\n }\n if field.pattern_properties:\n data[\"patternProperties\"] = {\n key: to_json_schema(value, _definitions=definitions)\n for key, value in field.pattern_properties.items()\n }\n if field.additional_properties is not None:\n if isinstance(field.additional_properties, bool):\n data[\"additionalProperties\"] = field.additional_properties\n else:\n data[\"additionalProperties\"] = to_json_schema(\n field.additional_properties, _definitions=definitions\n )\n if field.property_names is not None:\n data[\"propertyNames\"] = to_json_schema(\n field.property_names, _definitions=definitions\n )\n if field.max_properties is not None:\n data[\"maxProperties\"] = field.max_properties\n if field.min_properties is not None:\n data[\"minProperties\"] = field.min_properties\n if field.required:\n data[\"required\"] = field.required\n\n elif isinstance(field, Choice):\n data[\"enum\"] = [key for key, value in field.choices]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Const):\n data[\"const\"] = field.const\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Union):\n data[\"anyOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.any_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, OneOf):\n data[\"oneOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.one_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, AllOf):\n data[\"allOf\"] = [\n to_json_schema(item, _definitions=definitions) for item in field.all_of\n ]\n data.update(get_standard_properties(field))\n\n elif isinstance(field, IfThenElse):\n data[\"if\"] = to_json_schema(field.if_clause, _definitions=definitions)\n if field.then_clause is not None:\n data[\"then\"] = to_json_schema(field.then_clause, _definitions=definitions)\n if field.else_clause is not None:\n data[\"else\"] = to_json_schema(field.else_clause, _definitions=definitions)\n data.update(get_standard_properties(field))\n\n elif isinstance(field, Not):\n data[\"not\"] = to_json_schema(field.negated, _definitions=definitions)\n data.update(get_standard_properties(field))\n\n elif field is not None:\n name = type(field).__qualname__\n raise ValueError(f\"Cannot convert field type {name!r} to JSON Schema\")\n\n if is_root and definitions:\n data[\"definitions\"] = definitions\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 851, "project": "typesystem", "module": "typesystem.schemas", "class": "", "method": "set_definitions", "focal_method_txt": "def set_definitions(field: Field, definitions: SchemaDefinitions) -> None:\n \"\"\"\n Recursively set the definitions that string-referenced `Reference` fields\n should use.\n \"\"\"\n if isinstance(field, Reference) and field.definitions is None:\n field.definitions = definitions\n elif isinstance(field, Array):\n if field.items is not None:\n if isinstance(field.items, (tuple, list)):\n for child in field.items:\n set_definitions(child, definitions)\n else:\n set_definitions(field.items, definitions)\n elif isinstance(field, Object):\n for child in field.properties.values():\n set_definitions(child, definitions)", "focal_method_lines": [31, 47], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass SchemaDefinitions(MutableMapping):\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n self._definitions = dict(*args, **kwargs)\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\nclass Reference(Field):\n\n errors = {\"null\": \"May not be null.\"}\n\n def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to\n\ndef set_definitions(field: Field, definitions: SchemaDefinitions) -> None:\n \"\"\"\n Recursively set the definitions that string-referenced `Reference` fields\n should use.\n \"\"\"\n if isinstance(field, Reference) and field.definitions is None:\n field.definitions = definitions\n elif isinstance(field, Array):\n if field.items is not None:\n if isinstance(field.items, (tuple, list)):\n for child in field.items:\n set_definitions(child, definitions)\n else:\n set_definitions(field.items, definitions)\n elif isinstance(field, Object):\n for child in field.properties.values():\n set_definitions(child, definitions)", "has_branch": true, "total_branches": 2} {"prompt_id": 852, "project": "typesystem", "module": "typesystem.schemas", "class": "SchemaDefinitions", "method": "__setitem__", "focal_method_txt": " def __setitem__(self, key: typing.Any, value: typing.Any) -> None:\n assert (\n key not in self._definitions\n ), r\"Definition for {key!r} has already been set.\"\n self._definitions[key] = value", "focal_method_lines": [21, 25], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass SchemaDefinitions(MutableMapping):\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n self._definitions = dict(*args, **kwargs)\n\n def __setitem__(self, key: typing.Any, value: typing.Any) -> None:\n assert (\n key not in self._definitions\n ), r\"Definition for {key!r} has already been set.\"\n self._definitions[key] = value", "has_branch": false, "total_branches": 0} {"prompt_id": 853, "project": "typesystem", "module": "typesystem.schemas", "class": "SchemaMetaclass", "method": "__new__", "focal_method_txt": " def __new__(\n cls: type,\n name: str,\n bases: typing.Sequence[type],\n attrs: dict,\n definitions: SchemaDefinitions = None,\n ) -> type:\n fields: typing.Dict[str, Field] = {}\n\n for key, value in list(attrs.items()):\n if isinstance(value, Field):\n attrs.pop(key)\n fields[key] = value\n\n # If this class is subclassing other Schema classes, add their fields.\n for base in reversed(bases):\n base_fields = getattr(base, \"fields\", {})\n for key, value in base_fields.items():\n if isinstance(value, Field) and key not in fields:\n fields[key] = value\n\n # Add the definitions to any `Reference` fields that we're including.\n if definitions is not None:\n for field in fields.values():\n set_definitions(field, definitions)\n\n #  Sort fields by their actual position in the source code,\n # using `Field._creation_counter`\n attrs[\"fields\"] = dict(\n sorted(fields.items(), key=lambda item: item[1]._creation_counter)\n )\n\n new_type = super(SchemaMetaclass, cls).__new__( # type: ignore\n cls, name, bases, attrs\n )\n if definitions is not None:\n definitions[name] = new_type\n return new_type", "focal_method_lines": [51, 88], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass SchemaDefinitions(MutableMapping):\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n self._definitions = dict(*args, **kwargs)\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\nclass Reference(Field):\n\n errors = {\"null\": \"May not be null.\"}\n\n def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to\n\nclass SchemaMetaclass(ABCMeta):\n\n def __new__(\n cls: type,\n name: str,\n bases: typing.Sequence[type],\n attrs: dict,\n definitions: SchemaDefinitions = None,\n ) -> type:\n fields: typing.Dict[str, Field] = {}\n\n for key, value in list(attrs.items()):\n if isinstance(value, Field):\n attrs.pop(key)\n fields[key] = value\n\n # If this class is subclassing other Schema classes, add their fields.\n for base in reversed(bases):\n base_fields = getattr(base, \"fields\", {})\n for key, value in base_fields.items():\n if isinstance(value, Field) and key not in fields:\n fields[key] = value\n\n # Add the definitions to any `Reference` fields that we're including.\n if definitions is not None:\n for field in fields.values():\n set_definitions(field, definitions)\n\n #  Sort fields by their actual position in the source code,\n # using `Field._creation_counter`\n attrs[\"fields\"] = dict(\n sorted(fields.items(), key=lambda item: item[1]._creation_counter)\n )\n\n new_type = super(SchemaMetaclass, cls).__new__( # type: ignore\n cls, name, bases, attrs\n )\n if definitions is not None:\n definitions[name] = new_type\n return new_type", "has_branch": true, "total_branches": 2} {"prompt_id": 854, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__init__", "focal_method_txt": " def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)", "focal_method_lines": [94, 130], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)", "has_branch": true, "total_branches": 2} {"prompt_id": 855, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: typing.Any) -> bool:\n if not isinstance(other, self.__class__):\n return False\n\n for key in self.fields.keys():\n if getattr(self, key) != getattr(other, key):\n return False\n return True", "focal_method_lines": [165, 172], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\n def __eq__(self, other: typing.Any) -> bool:\n if not isinstance(other, self.__class__):\n return False\n\n for key in self.fields.keys():\n if getattr(self, key) != getattr(other, key):\n return False\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 856, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__getitem__", "focal_method_txt": " def __getitem__(self, key: typing.Any) -> typing.Any:\n try:\n field = self.fields[key]\n value = getattr(self, key)\n except (KeyError, AttributeError):\n raise KeyError(key) from None\n else:\n return field.serialize(value)", "focal_method_lines": [174, 181], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\n def __getitem__(self, key: typing.Any) -> typing.Any:\n try:\n field = self.fields[key]\n value = getattr(self, key)\n except (KeyError, AttributeError):\n raise KeyError(key) from None\n else:\n return field.serialize(value)", "has_branch": false, "total_branches": 0} {"prompt_id": 857, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__iter__", "focal_method_txt": " def __iter__(self) -> typing.Iterator[str]:\n for key in self.fields:\n if hasattr(self, key):\n yield key", "focal_method_lines": [183, 186], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\n def __iter__(self) -> typing.Iterator[str]:\n for key in self.fields:\n if hasattr(self, key):\n yield key", "has_branch": true, "total_branches": 2} {"prompt_id": 858, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__len__", "focal_method_txt": " def __len__(self) -> int:\n return len([key for key in self.fields if hasattr(self, key)])", "focal_method_lines": [188, 189], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\n def __len__(self) -> int:\n return len([key for key in self.fields if hasattr(self, key)])", "has_branch": false, "total_branches": 0} {"prompt_id": 859, "project": "typesystem", "module": "typesystem.schemas", "class": "Schema", "method": "__repr__", "focal_method_txt": " def __repr__(self) -> str:\n class_name = self.__class__.__name__\n arguments = {\n key: getattr(self, key) for key in self.fields.keys() if hasattr(self, key)\n }\n argument_str = \", \".join(\n [f\"{key}={value!r}\" for key, value in arguments.items()]\n )\n sparse_indicator = \" [sparse]\" if self.is_sparse else \"\"\n return f\"{class_name}({argument_str}){sparse_indicator}\"", "focal_method_lines": [191, 200], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n arguments = {\n key: getattr(self, key) for key in self.fields.keys() if hasattr(self, key)\n }\n argument_str = \", \".join(\n [f\"{key}={value!r}\" for key, value in arguments.items()]\n )\n sparse_indicator = \" [sparse]\" if self.is_sparse else \"\"\n return f\"{class_name}({argument_str}){sparse_indicator}\"", "has_branch": false, "total_branches": 0} {"prompt_id": 860, "project": "typesystem", "module": "typesystem.schemas", "class": "Reference", "method": "__init__", "focal_method_txt": " def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to", "focal_method_lines": [206, 219], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Schema(Mapping, metaclass=SchemaMetaclass):\n\n fields: typing.Dict[str, Field] = {}\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n if args:\n assert len(args) == 1\n assert not kwargs\n item = args[0]\n if isinstance(item, dict):\n for key in self.fields.keys():\n if key in item:\n setattr(self, key, item[key])\n else:\n for key in self.fields.keys():\n if hasattr(item, key):\n setattr(self, key, getattr(item, key))\n return\n\n for key, schema in self.fields.items():\n if key in kwargs:\n value = kwargs.pop(key)\n value, error = schema.validate_or_error(value)\n if error:\n class_name = self.__class__.__name__\n error_text = \" \".join(\n [message.text for message in error.messages()]\n )\n message = (\n f\"Invalid argument {key!r} for {class_name}(). {error_text}\"\n )\n raise TypeError(message)\n setattr(self, key, value)\n elif schema.has_default():\n setattr(self, key, schema.get_default_value())\n\n if kwargs:\n key = list(kwargs.keys())[0]\n class_name = self.__class__.__name__\n message = f\"{key!r} is an invalid keyword argument for {class_name}().\"\n raise TypeError(message)\n\nclass Reference(Field):\n\n errors = {\"null\": \"May not be null.\"}\n\n def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to", "has_branch": true, "total_branches": 2} {"prompt_id": 861, "project": "typesystem", "module": "typesystem.schemas", "class": "Reference", "method": "validate", "focal_method_txt": " def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n return self.target.validate(value, strict=strict)", "focal_method_lines": [236, 241], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Reference(Field):\n\n errors = {\"null\": \"May not be null.\"}\n\n def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to\n\n def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:\n if value is None and self.allow_null:\n return None\n elif value is None:\n raise self.validation_error(\"null\")\n return self.target.validate(value, strict=strict)", "has_branch": true, "total_branches": 2} {"prompt_id": 862, "project": "typesystem", "module": "typesystem.schemas", "class": "Reference", "method": "serialize", "focal_method_txt": " def serialize(self, obj: typing.Any) -> typing.Any:\n if obj is None:\n return None\n return dict(obj)", "focal_method_lines": [243, 246], "in_stack": false, "globals": [], "type_context": "import typing\nfrom abc import ABCMeta\nfrom collections.abc import Mapping, MutableMapping\nfrom typesystem.base import ValidationError, ValidationResult\nfrom typesystem.fields import Array, Field, Object\n\n\n\nclass Reference(Field):\n\n errors = {\"null\": \"May not be null.\"}\n\n def __init__(\n self,\n to: typing.Union[str, typing.Type[Schema]],\n definitions: typing.Mapping = None,\n **kwargs: typing.Any,\n ) -> None:\n super().__init__(**kwargs)\n self.to = to\n self.definitions = definitions\n if isinstance(to, str):\n self._target_string = to\n else:\n assert issubclass(to, Schema)\n self._target = to\n\n def serialize(self, obj: typing.Any) -> typing.Any:\n if obj is None:\n return None\n return dict(obj)", "has_branch": true, "total_branches": 2} {"prompt_id": 863, "project": "typesystem", "module": "typesystem.tokenize.positional_validation", "class": "", "method": "validate_with_positions", "focal_method_txt": "def validate_with_positions(\n *, token: Token, validator: typing.Union[Field, typing.Type[Schema]]\n) -> typing.Any:\n try:\n return validator.validate(token.value)\n except ValidationError as error:\n messages = []\n for message in error.messages():\n if message.code == \"required\":\n field = message.index[-1]\n token = token.lookup(message.index[:-1])\n text = f\"The field {field!r} is required.\"\n else:\n token = token.lookup(message.index)\n text = message.text\n\n positional_message = Message(\n text=text,\n code=message.code,\n index=message.index,\n start_position=token.start,\n end_position=token.end,\n )\n messages.append(positional_message)\n messages = sorted(\n messages, key=lambda m: m.start_position.char_index # type: ignore\n )\n raise ValidationError(messages=messages)", "focal_method_lines": [8, 35], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Message, ValidationError\nfrom typesystem.fields import Field\nfrom typesystem.schemas import Schema\nfrom typesystem.tokenize.tokens import Token\n\n\n\ndef validate_with_positions(\n *, token: Token, validator: typing.Union[Field, typing.Type[Schema]]\n) -> typing.Any:\n try:\n return validator.validate(token.value)\n except ValidationError as error:\n messages = []\n for message in error.messages():\n if message.code == \"required\":\n field = message.index[-1]\n token = token.lookup(message.index[:-1])\n text = f\"The field {field!r} is required.\"\n else:\n token = token.lookup(message.index)\n text = message.text\n\n positional_message = Message(\n text=text,\n code=message.code,\n index=message.index,\n start_position=token.start,\n end_position=token.end,\n )\n messages.append(positional_message)\n messages = sorted(\n messages, key=lambda m: m.start_position.char_index # type: ignore\n )\n raise ValidationError(messages=messages)", "has_branch": true, "total_branches": 2} {"prompt_id": 864, "project": "typesystem", "module": "typesystem.tokenize.tokenize_json", "class": "", "method": "tokenize_json", "focal_method_txt": "def tokenize_json(content: typing.Union[str, bytes]) -> Token:\n if isinstance(content, bytes):\n content = content.decode(\"utf-8\", \"ignore\")\n\n if not content.strip():\n # Handle the empty string case explicitly for clear error messaging.\n position = Position(column_no=1, line_no=1, char_index=0)\n raise ParseError(text=\"No content.\", code=\"no_content\", position=position)\n\n decoder = _TokenizingDecoder(content=content)\n try:\n return decoder.decode(content)\n except JSONDecodeError as exc:\n # Handle cases that result in a JSON parse error.\n position = Position(column_no=exc.colno, line_no=exc.lineno, char_index=exc.pos)\n raise ParseError(text=exc.msg + \".\", code=\"parse_error\", position=position)", "focal_method_lines": [164, 179], "in_stack": false, "globals": ["FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE"], "type_context": "import re\nimport typing\nfrom json.decoder import JSONDecodeError, JSONDecoder, scanstring\nfrom typesystem.base import Message, ParseError, Position, ValidationError\nfrom typesystem.fields import Field\nfrom typesystem.schemas import Schema\nfrom typesystem.tokenize.positional_validation import validate_with_positions\nfrom typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token\n\nFLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL\nWHITESPACE = re.compile(r\"[ \\t\\n\\r]*\", FLAGS)\nWHITESPACE_STR = \" \\t\\n\\r\"\nNUMBER_RE = re.compile(\n r\"(-?(?:0|[1-9]\\d*))(\\.\\d+)?([eE][-+]?\\d+)?\",\n (re.VERBOSE | re.MULTILINE | re.DOTALL),\n)\n\nclass _TokenizingDecoder(JSONDecoder):\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n content = kwargs.pop(\"content\")\n super().__init__(*args, **kwargs)\n self.scan_once = _make_scanner(self, content)\n\ndef tokenize_json(content: typing.Union[str, bytes]) -> Token:\n if isinstance(content, bytes):\n content = content.decode(\"utf-8\", \"ignore\")\n\n if not content.strip():\n # Handle the empty string case explicitly for clear error messaging.\n position = Position(column_no=1, line_no=1, char_index=0)\n raise ParseError(text=\"No content.\", code=\"no_content\", position=position)\n\n decoder = _TokenizingDecoder(content=content)\n try:\n return decoder.decode(content)\n except JSONDecodeError as exc:\n # Handle cases that result in a JSON parse error.\n position = Position(column_no=exc.colno, line_no=exc.lineno, char_index=exc.pos)\n raise ParseError(text=exc.msg + \".\", code=\"parse_error\", position=position)", "has_branch": true, "total_branches": 2} {"prompt_id": 865, "project": "typesystem", "module": "typesystem.tokenize.tokenize_json", "class": "", "method": "validate_json", "focal_method_txt": "def validate_json(\n content: typing.Union[str, bytes],\n validator: typing.Union[Field, typing.Type[Schema]],\n) -> typing.Any:\n \"\"\"\n Parse and validate a JSON string, returning positionally marked error\n messages on parse or validation failures.\n\n content - A JSON string or bytestring.\n validator - A Field instance or Schema class to validate against.\n\n Returns a two-tuple of (value, error_messages)\n \"\"\"\n token = tokenize_json(content)\n return validate_with_positions(token=token, validator=validator)", "focal_method_lines": [182, 196], "in_stack": false, "globals": ["FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE"], "type_context": "import re\nimport typing\nfrom json.decoder import JSONDecodeError, JSONDecoder, scanstring\nfrom typesystem.base import Message, ParseError, Position, ValidationError\nfrom typesystem.fields import Field\nfrom typesystem.schemas import Schema\nfrom typesystem.tokenize.positional_validation import validate_with_positions\nfrom typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token\n\nFLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL\nWHITESPACE = re.compile(r\"[ \\t\\n\\r]*\", FLAGS)\nWHITESPACE_STR = \" \\t\\n\\r\"\nNUMBER_RE = re.compile(\n r\"(-?(?:0|[1-9]\\d*))(\\.\\d+)?([eE][-+]?\\d+)?\",\n (re.VERBOSE | re.MULTILINE | re.DOTALL),\n)\n\ndef validate_json(\n content: typing.Union[str, bytes],\n validator: typing.Union[Field, typing.Type[Schema]],\n) -> typing.Any:\n \"\"\"\n Parse and validate a JSON string, returning positionally marked error\n messages on parse or validation failures.\n\n content - A JSON string or bytestring.\n validator - A Field instance or Schema class to validate against.\n\n Returns a two-tuple of (value, error_messages)\n \"\"\"\n token = tokenize_json(content)\n return validate_with_positions(token=token, validator=validator)", "has_branch": false, "total_branches": 0} {"prompt_id": 866, "project": "typesystem", "module": "typesystem.tokenize.tokenize_yaml", "class": "", "method": "tokenize_yaml", "focal_method_txt": "def tokenize_yaml(content: typing.Union[str, bytes]) -> Token:\n assert yaml is not None, \"'pyyaml' must be installed.\"\n\n if isinstance(content, bytes):\n str_content = content.decode(\"utf-8\", \"ignore\")\n else:\n str_content = content\n\n if not str_content.strip():\n # Handle the empty string case explicitly for clear error messaging.\n position = Position(column_no=1, line_no=1, char_index=0)\n raise ParseError(text=\"No content.\", code=\"no_content\", position=position)\n\n class CustomSafeLoader(SafeLoader):\n pass\n\n def construct_mapping(loader: \"yaml.Loader\", node: \"yaml.Node\") -> DictToken:\n start = node.start_mark.index\n end = node.end_mark.index\n mapping = loader.construct_mapping(node)\n return DictToken(mapping, start, end - 1, content=str_content)\n\n def construct_sequence(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ListToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_sequence(node)\n return ListToken(value, start, end - 1, content=str_content)\n\n def construct_scalar(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_scalar(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_int(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_int(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_float(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_float(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_bool(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_bool(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_null(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_null(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping\n )\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_SEQUENCE_TAG, construct_sequence\n )\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, construct_scalar\n )\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:int\", construct_int)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:float\", construct_float)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:bool\", construct_bool)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:null\", construct_null)\n\n try:\n return yaml.load(str_content, CustomSafeLoader)\n except (yaml.scanner.ScannerError, yaml.parser.ParserError) as exc: # type: ignore\n # Handle cases that result in a YAML parse error.\n text = exc.problem + \".\"\n position = _get_position(str_content, index=exc.problem_mark.index)\n raise ParseError(text=text, code=\"parse_error\", position=position)", "focal_method_lines": [24, 108], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Message, ParseError, Position, ValidationError\nfrom typesystem.fields import Field\nfrom typesystem.schemas import Schema\nfrom typesystem.tokenize.positional_validation import validate_with_positions\nfrom typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token\n\n\n\ndef tokenize_yaml(content: typing.Union[str, bytes]) -> Token:\n assert yaml is not None, \"'pyyaml' must be installed.\"\n\n if isinstance(content, bytes):\n str_content = content.decode(\"utf-8\", \"ignore\")\n else:\n str_content = content\n\n if not str_content.strip():\n # Handle the empty string case explicitly for clear error messaging.\n position = Position(column_no=1, line_no=1, char_index=0)\n raise ParseError(text=\"No content.\", code=\"no_content\", position=position)\n\n class CustomSafeLoader(SafeLoader):\n pass\n\n def construct_mapping(loader: \"yaml.Loader\", node: \"yaml.Node\") -> DictToken:\n start = node.start_mark.index\n end = node.end_mark.index\n mapping = loader.construct_mapping(node)\n return DictToken(mapping, start, end - 1, content=str_content)\n\n def construct_sequence(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ListToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_sequence(node)\n return ListToken(value, start, end - 1, content=str_content)\n\n def construct_scalar(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_scalar(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_int(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_int(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_float(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_float(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_bool(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_bool(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n def construct_null(loader: \"yaml.Loader\", node: \"yaml.Node\") -> ScalarToken:\n start = node.start_mark.index\n end = node.end_mark.index\n value = loader.construct_yaml_null(node)\n return ScalarToken(value, start, end - 1, content=str_content)\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping\n )\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_SEQUENCE_TAG, construct_sequence\n )\n\n CustomSafeLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, construct_scalar\n )\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:int\", construct_int)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:float\", construct_float)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:bool\", construct_bool)\n\n CustomSafeLoader.add_constructor(\"tag:yaml.org,2002:null\", construct_null)\n\n try:\n return yaml.load(str_content, CustomSafeLoader)\n except (yaml.scanner.ScannerError, yaml.parser.ParserError) as exc: # type: ignore\n # Handle cases that result in a YAML parse error.\n text = exc.problem + \".\"\n position = _get_position(str_content, index=exc.problem_mark.index)\n raise ParseError(text=text, code=\"parse_error\", position=position)", "has_branch": true, "total_branches": 2} {"prompt_id": 867, "project": "typesystem", "module": "typesystem.tokenize.tokenize_yaml", "class": "", "method": "validate_yaml", "focal_method_txt": "def validate_yaml(\n content: typing.Union[str, bytes],\n validator: typing.Union[Field, typing.Type[Schema]],\n) -> typing.Any:\n \"\"\"\n Parse and validate a YAML string, returning positionally marked error\n messages on parse or validation failures.\n\n content - A YAML string or bytestring.\n validator - A Field instance or Schema class to validate against.\n\n Returns a two-tuple of (value, error_messages)\n \"\"\"\n assert yaml is not None, \"'pyyaml' must be installed.\"\n\n token = tokenize_yaml(content)\n return validate_with_positions(token=token, validator=validator)", "focal_method_lines": [111, 127], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Message, ParseError, Position, ValidationError\nfrom typesystem.fields import Field\nfrom typesystem.schemas import Schema\nfrom typesystem.tokenize.positional_validation import validate_with_positions\nfrom typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token\n\n\n\ndef validate_yaml(\n content: typing.Union[str, bytes],\n validator: typing.Union[Field, typing.Type[Schema]],\n) -> typing.Any:\n \"\"\"\n Parse and validate a YAML string, returning positionally marked error\n messages on parse or validation failures.\n\n content - A YAML string or bytestring.\n validator - A Field instance or Schema class to validate against.\n\n Returns a two-tuple of (value, error_messages)\n \"\"\"\n assert yaml is not None, \"'pyyaml' must be installed.\"\n\n token = tokenize_yaml(content)\n return validate_with_positions(token=token, validator=validator)", "has_branch": false, "total_branches": 0} {"prompt_id": 868, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "Token", "method": "__init__", "focal_method_txt": " def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content", "focal_method_lines": [6, 12], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass Token:\n\n def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content", "has_branch": false, "total_branches": 0} {"prompt_id": 869, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "Token", "method": "lookup", "focal_method_txt": " def lookup(self, index: list) -> \"Token\":\n \"\"\"\n Given an index, lookup a child token within this structure.\n \"\"\"\n token = self\n for key in index:\n token = token._get_child_token(key)\n return token", "focal_method_lines": [39, 46], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass Token:\n\n def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content\n\n def lookup(self, index: list) -> \"Token\":\n \"\"\"\n Given an index, lookup a child token within this structure.\n \"\"\"\n token = self\n for key in index:\n token = token._get_child_token(key)\n return token", "has_branch": true, "total_branches": 2} {"prompt_id": 870, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "Token", "method": "lookup_key", "focal_method_txt": " def lookup_key(self, index: list) -> \"Token\":\n \"\"\"\n Given an index, lookup a token for a dictionary key within this structure.\n \"\"\"\n token = self.lookup(index[:-1])\n return token._get_key_token(index[-1])", "focal_method_lines": [48, 53], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass Token:\n\n def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content\n\n def lookup_key(self, index: list) -> \"Token\":\n \"\"\"\n Given an index, lookup a token for a dictionary key within this structure.\n \"\"\"\n token = self.lookup(index[:-1])\n return token._get_key_token(index[-1])", "has_branch": false, "total_branches": 0} {"prompt_id": 871, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "Token", "method": "__repr__", "focal_method_txt": " def __repr__(self) -> str:\n return \"%s(%s)\" % (self.__class__.__name__, repr(self.string))", "focal_method_lines": [62, 63], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass Token:\n\n def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content\n\n def __repr__(self) -> str:\n return \"%s(%s)\" % (self.__class__.__name__, repr(self.string))", "has_branch": false, "total_branches": 0} {"prompt_id": 872, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "Token", "method": "__eq__", "focal_method_txt": " def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, Token) and (\n self._get_value() == other._get_value()\n and self._start_index == other._start_index\n and self._end_index == other._end_index\n )", "focal_method_lines": [65, 66], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass Token:\n\n def __init__(\n self, value: typing.Any, start_index: int, end_index: int, content: str = \"\"\n ) -> None:\n self._value = value\n self._start_index = start_index\n self._end_index = end_index\n self._content = content\n\n def __eq__(self, other: typing.Any) -> bool:\n return isinstance(other, Token) and (\n self._get_value() == other._get_value()\n and self._start_index == other._start_index\n and self._end_index == other._end_index\n )", "has_branch": false, "total_branches": 0} {"prompt_id": 873, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "ScalarToken", "method": "__hash__", "focal_method_txt": " def __hash__(self) -> typing.Any:\n return hash(self._value)", "focal_method_lines": [74, 75], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass ScalarToken(Token):\n\n def __hash__(self) -> typing.Any:\n return hash(self._value)", "has_branch": false, "total_branches": 0} {"prompt_id": 874, "project": "typesystem", "module": "typesystem.tokenize.tokens", "class": "DictToken", "method": "__init__", "focal_method_txt": " def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n super().__init__(*args, **kwargs)\n self._child_keys = {k._value: k for k in self._value.keys()}\n self._child_tokens = {k._value: v for k, v in self._value.items()}", "focal_method_lines": [82, 85], "in_stack": false, "globals": [], "type_context": "import typing\nfrom typesystem.base import Position\n\n\n\nclass DictToken(Token):\n\n def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:\n super().__init__(*args, **kwargs)\n self._child_keys = {k._value: k for k in self._value.keys()}\n self._child_tokens = {k._value: v for k, v in self._value.items()}", "has_branch": false, "total_branches": 0} {"prompt_id": 875, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_ctr_decrypt", "focal_method_txt": "def aes_ctr_decrypt(data, key, counter):\n \"\"\"\n Decrypt with aes in counter mode\n\n @param {int[]} data cipher\n @param {int[]} key 16/24/32-Byte cipher key\n @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block)\n returns the next counter block\n @returns {int[]} decrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n decrypted_data = []\n for i in range(block_count):\n counter_block = counter.next_value()\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n block += [0] * (BLOCK_SIZE_BYTES - len(block))\n\n cipher_counter_block = aes_encrypt(counter_block, expanded_key)\n decrypted_data += xor(block, cipher_counter_block)\n decrypted_data = decrypted_data[:len(data)]\n\n return decrypted_data", "focal_method_lines": [10, 33], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_ctr_decrypt(data, key, counter):\n \"\"\"\n Decrypt with aes in counter mode\n\n @param {int[]} data cipher\n @param {int[]} key 16/24/32-Byte cipher key\n @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block)\n returns the next counter block\n @returns {int[]} decrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n decrypted_data = []\n for i in range(block_count):\n counter_block = counter.next_value()\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n block += [0] * (BLOCK_SIZE_BYTES - len(block))\n\n cipher_counter_block = aes_encrypt(counter_block, expanded_key)\n decrypted_data += xor(block, cipher_counter_block)\n decrypted_data = decrypted_data[:len(data)]\n\n return decrypted_data", "has_branch": true, "total_branches": 2} {"prompt_id": 876, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_cbc_decrypt", "focal_method_txt": "def aes_cbc_decrypt(data, key, iv):\n \"\"\"\n Decrypt with aes in CBC mode\n\n @param {int[]} data cipher\n @param {int[]} key 16/24/32-Byte cipher key\n @param {int[]} iv 16-Byte IV\n @returns {int[]} decrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n decrypted_data = []\n previous_cipher_block = iv\n for i in range(block_count):\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n block += [0] * (BLOCK_SIZE_BYTES - len(block))\n\n decrypted_block = aes_decrypt(block, expanded_key)\n decrypted_data += xor(decrypted_block, previous_cipher_block)\n previous_cipher_block = block\n decrypted_data = decrypted_data[:len(data)]\n\n return decrypted_data", "focal_method_lines": [36, 59], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_cbc_decrypt(data, key, iv):\n \"\"\"\n Decrypt with aes in CBC mode\n\n @param {int[]} data cipher\n @param {int[]} key 16/24/32-Byte cipher key\n @param {int[]} iv 16-Byte IV\n @returns {int[]} decrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n decrypted_data = []\n previous_cipher_block = iv\n for i in range(block_count):\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n block += [0] * (BLOCK_SIZE_BYTES - len(block))\n\n decrypted_block = aes_decrypt(block, expanded_key)\n decrypted_data += xor(decrypted_block, previous_cipher_block)\n previous_cipher_block = block\n decrypted_data = decrypted_data[:len(data)]\n\n return decrypted_data", "has_branch": true, "total_branches": 2} {"prompt_id": 877, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_cbc_encrypt", "focal_method_txt": "def aes_cbc_encrypt(data, key, iv):\n \"\"\"\n Encrypt with aes in CBC mode. Using PKCS#7 padding\n\n @param {int[]} data cleartext\n @param {int[]} key 16/24/32-Byte cipher key\n @param {int[]} iv 16-Byte IV\n @returns {int[]} encrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n encrypted_data = []\n previous_cipher_block = iv\n for i in range(block_count):\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n remaining_length = BLOCK_SIZE_BYTES - len(block)\n block += [remaining_length] * remaining_length\n mixed_block = xor(block, previous_cipher_block)\n\n encrypted_block = aes_encrypt(mixed_block, expanded_key)\n encrypted_data += encrypted_block\n\n previous_cipher_block = encrypted_block\n\n return encrypted_data", "focal_method_lines": [62, 87], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_cbc_encrypt(data, key, iv):\n \"\"\"\n Encrypt with aes in CBC mode. Using PKCS#7 padding\n\n @param {int[]} data cleartext\n @param {int[]} key 16/24/32-Byte cipher key\n @param {int[]} iv 16-Byte IV\n @returns {int[]} encrypted data\n \"\"\"\n expanded_key = key_expansion(key)\n block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))\n\n encrypted_data = []\n previous_cipher_block = iv\n for i in range(block_count):\n block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]\n remaining_length = BLOCK_SIZE_BYTES - len(block)\n block += [remaining_length] * remaining_length\n mixed_block = xor(block, previous_cipher_block)\n\n encrypted_block = aes_encrypt(mixed_block, expanded_key)\n encrypted_data += encrypted_block\n\n previous_cipher_block = encrypted_block\n\n return encrypted_data", "has_branch": true, "total_branches": 2} {"prompt_id": 878, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "key_expansion", "focal_method_txt": "def key_expansion(data):\n \"\"\"\n Generate key schedule\n\n @param {int[]} data 16/24/32-Byte cipher key\n @returns {int[]} 176/208/240-Byte expanded key\n \"\"\"\n data = data[:] # copy\n rcon_iteration = 1\n key_size_bytes = len(data)\n expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES\n\n while len(data) < expanded_key_size_bytes:\n temp = data[-4:]\n temp = key_schedule_core(temp, rcon_iteration)\n rcon_iteration += 1\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n for _ in range(3):\n temp = data[-4:]\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n if key_size_bytes == 32:\n temp = data[-4:]\n temp = sub_bytes(temp)\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0):\n temp = data[-4:]\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n data = data[:expanded_key_size_bytes]\n\n return data", "focal_method_lines": [90, 122], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef key_expansion(data):\n \"\"\"\n Generate key schedule\n\n @param {int[]} data 16/24/32-Byte cipher key\n @returns {int[]} 176/208/240-Byte expanded key\n \"\"\"\n data = data[:] # copy\n rcon_iteration = 1\n key_size_bytes = len(data)\n expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES\n\n while len(data) < expanded_key_size_bytes:\n temp = data[-4:]\n temp = key_schedule_core(temp, rcon_iteration)\n rcon_iteration += 1\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n for _ in range(3):\n temp = data[-4:]\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n if key_size_bytes == 32:\n temp = data[-4:]\n temp = sub_bytes(temp)\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n\n for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0):\n temp = data[-4:]\n data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])\n data = data[:expanded_key_size_bytes]\n\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 879, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_encrypt", "focal_method_txt": "def aes_encrypt(data, expanded_key):\n \"\"\"\n Encrypt one block with aes\n\n @param {int[]} data 16-Byte state\n @param {int[]} expanded_key 176/208/240-Byte expanded key\n @returns {int[]} 16-Byte cipher\n \"\"\"\n rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1\n\n data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])\n for i in range(1, rounds + 1):\n data = sub_bytes(data)\n data = shift_rows(data)\n if i != rounds:\n data = mix_columns(data)\n data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])\n\n return data", "focal_method_lines": [125, 143], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_encrypt(data, expanded_key):\n \"\"\"\n Encrypt one block with aes\n\n @param {int[]} data 16-Byte state\n @param {int[]} expanded_key 176/208/240-Byte expanded key\n @returns {int[]} 16-Byte cipher\n \"\"\"\n rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1\n\n data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])\n for i in range(1, rounds + 1):\n data = sub_bytes(data)\n data = shift_rows(data)\n if i != rounds:\n data = mix_columns(data)\n data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])\n\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 880, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_decrypt", "focal_method_txt": "def aes_decrypt(data, expanded_key):\n \"\"\"\n Decrypt one block with aes\n\n @param {int[]} data 16-Byte cipher\n @param {int[]} expanded_key 176/208/240-Byte expanded key\n @returns {int[]} 16-Byte state\n \"\"\"\n rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1\n\n for i in range(rounds, 0, -1):\n data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])\n if i != rounds:\n data = mix_columns_inv(data)\n data = shift_rows_inv(data)\n data = sub_bytes_inv(data)\n data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])\n\n return data", "focal_method_lines": [146, 164], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_decrypt(data, expanded_key):\n \"\"\"\n Decrypt one block with aes\n\n @param {int[]} data 16-Byte cipher\n @param {int[]} expanded_key 176/208/240-Byte expanded key\n @returns {int[]} 16-Byte state\n \"\"\"\n rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1\n\n for i in range(rounds, 0, -1):\n data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])\n if i != rounds:\n data = mix_columns_inv(data)\n data = shift_rows_inv(data)\n data = sub_bytes_inv(data)\n data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])\n\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 881, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "aes_decrypt_text", "focal_method_txt": "def aes_decrypt_text(data, password, key_size_bytes):\n \"\"\"\n Decrypt text\n - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter\n - The cipher key is retrieved by encrypting the first 16 Byte of 'password'\n with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's)\n - Mode of operation is 'counter'\n\n @param {str} data Base64 encoded string\n @param {str,unicode} password Password (will be encoded with utf-8)\n @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit\n @returns {str} Decrypted data\n \"\"\"\n NONCE_LENGTH_BYTES = 8\n\n data = bytes_to_intlist(compat_b64decode(data))\n password = bytes_to_intlist(password.encode('utf-8'))\n\n key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password))\n key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES)\n\n nonce = data[:NONCE_LENGTH_BYTES]\n cipher = data[NONCE_LENGTH_BYTES:]\n\n class Counter(object):\n __value = nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES)\n\n def next_value(self):\n temp = self.__value\n self.__value = inc(self.__value)\n return temp\n\n decrypted_data = aes_ctr_decrypt(cipher, key, Counter())\n plaintext = intlist_to_bytes(decrypted_data)\n\n return plaintext", "focal_method_lines": [167, 202], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef aes_decrypt_text(data, password, key_size_bytes):\n \"\"\"\n Decrypt text\n - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter\n - The cipher key is retrieved by encrypting the first 16 Byte of 'password'\n with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's)\n - Mode of operation is 'counter'\n\n @param {str} data Base64 encoded string\n @param {str,unicode} password Password (will be encoded with utf-8)\n @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit\n @returns {str} Decrypted data\n \"\"\"\n NONCE_LENGTH_BYTES = 8\n\n data = bytes_to_intlist(compat_b64decode(data))\n password = bytes_to_intlist(password.encode('utf-8'))\n\n key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password))\n key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES)\n\n nonce = data[:NONCE_LENGTH_BYTES]\n cipher = data[NONCE_LENGTH_BYTES:]\n\n class Counter(object):\n __value = nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES)\n\n def next_value(self):\n temp = self.__value\n self.__value = inc(self.__value)\n return temp\n\n decrypted_data = aes_ctr_decrypt(cipher, key, Counter())\n plaintext = intlist_to_bytes(decrypted_data)\n\n return plaintext", "has_branch": false, "total_branches": 0} {"prompt_id": 882, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "key_schedule_core", "focal_method_txt": "def key_schedule_core(data, rcon_iteration):\n data = rotate(data)\n data = sub_bytes(data)\n data[0] = data[0] ^ RCON[rcon_iteration]\n\n return data", "focal_method_lines": [292, 297], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef key_schedule_core(data, rcon_iteration):\n data = rotate(data)\n data = sub_bytes(data)\n data[0] = data[0] ^ RCON[rcon_iteration]\n\n return data", "has_branch": false, "total_branches": 0} {"prompt_id": 883, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "rijndael_mul", "focal_method_txt": "def rijndael_mul(a, b):\n if(a == 0 or b == 0):\n return 0\n return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]", "focal_method_lines": [304, 307], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef rijndael_mul(a, b):\n if(a == 0 or b == 0):\n return 0\n return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]", "has_branch": true, "total_branches": 2} {"prompt_id": 884, "project": "youtube_dl", "module": "youtube_dl.aes", "class": "", "method": "inc", "focal_method_txt": "def inc(data):\n data = data[:] # copy\n for i in range(len(data) - 1, -1, -1):\n if data[i] == 255:\n data[i] = 0\n else:\n data[i] = data[i] + 1\n break\n return data", "focal_method_lines": [349, 357], "in_stack": false, "globals": ["BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__"], "type_context": "from math import ceil\nfrom .compat import compat_b64decode\nfrom .utils import bytes_to_intlist, intlist_to_bytes\n\nBLOCK_SIZE_BYTES = 16\nRCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)\nSBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)\nSBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,\n 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,\n 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,\n 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,\n 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,\n 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,\n 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,\n 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,\n 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,\n 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,\n 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,\n 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,\n 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,\n 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,\n 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,\n 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)\nMIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),\n (0x1, 0x2, 0x3, 0x1),\n (0x1, 0x1, 0x2, 0x3),\n (0x3, 0x1, 0x1, 0x2))\nMIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),\n (0x9, 0xE, 0xB, 0xD),\n (0xD, 0x9, 0xE, 0xB),\n (0xB, 0xD, 0x9, 0xE))\nRIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,\n 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,\n 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,\n 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,\n 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,\n 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,\n 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,\n 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,\n 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,\n 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,\n 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,\n 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,\n 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,\n 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,\n 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,\n 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)\nRIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,\n 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,\n 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,\n 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,\n 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,\n 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,\n 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,\n 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,\n 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,\n 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,\n 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,\n 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,\n 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,\n 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,\n 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,\n 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)\n__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']\n\ndef inc(data):\n data = data[:] # copy\n for i in range(len(data) - 1, -1, -1):\n if data[i] == 255:\n data[i] = 0\n else:\n data[i] = data[i] + 1\n break\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 885, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "format_seconds", "focal_method_txt": " @staticmethod\n def format_seconds(seconds):\n (mins, secs) = divmod(seconds, 60)\n (hours, mins) = divmod(mins, 60)\n if hours > 99:\n return '--:--:--'\n if hours == 0:\n return '%02d:%02d' % (mins, secs)\n else:\n return '%02d:%02d:%02d' % (hours, mins, secs)", "focal_method_lines": [68, 76], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def format_seconds(seconds):\n (mins, secs) = divmod(seconds, 60)\n (hours, mins) = divmod(mins, 60)\n if hours > 99:\n return '--:--:--'\n if hours == 0:\n return '%02d:%02d' % (mins, secs)\n else:\n return '%02d:%02d:%02d' % (hours, mins, secs)", "has_branch": true, "total_branches": 2} {"prompt_id": 886, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "calc_percent", "focal_method_txt": " @staticmethod\n def calc_percent(byte_counter, data_len):\n if data_len is None:\n return None\n return float(byte_counter) / float(data_len) * 100.0", "focal_method_lines": [79, 82], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def calc_percent(byte_counter, data_len):\n if data_len is None:\n return None\n return float(byte_counter) / float(data_len) * 100.0", "has_branch": true, "total_branches": 2} {"prompt_id": 887, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "format_percent", "focal_method_txt": " @staticmethod\n def format_percent(percent):\n if percent is None:\n return '---.-%'\n return '%6s' % ('%3.1f%%' % percent)", "focal_method_lines": [85, 88], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def format_percent(percent):\n if percent is None:\n return '---.-%'\n return '%6s' % ('%3.1f%%' % percent)", "has_branch": true, "total_branches": 2} {"prompt_id": 888, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "calc_eta", "focal_method_txt": " @staticmethod\n def calc_eta(start, now, total, current):\n if total is None:\n return None\n if now is None:\n now = time.time()\n dif = now - start\n if current == 0 or dif < 0.001: # One millisecond\n return None\n rate = float(current) / dif\n return int((float(total) - float(current)) / rate)", "focal_method_lines": [91, 100], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def calc_eta(start, now, total, current):\n if total is None:\n return None\n if now is None:\n now = time.time()\n dif = now - start\n if current == 0 or dif < 0.001: # One millisecond\n return None\n rate = float(current) / dif\n return int((float(total) - float(current)) / rate)", "has_branch": true, "total_branches": 2} {"prompt_id": 889, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "calc_speed", "focal_method_txt": " @staticmethod\n def calc_speed(start, now, bytes):\n dif = now - start\n if bytes == 0 or dif < 0.001: # One millisecond\n return None\n return float(bytes) / dif", "focal_method_lines": [109, 113], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def calc_speed(start, now, bytes):\n dif = now - start\n if bytes == 0 or dif < 0.001: # One millisecond\n return None\n return float(bytes) / dif", "has_branch": true, "total_branches": 2} {"prompt_id": 890, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "format_retries", "focal_method_txt": " @staticmethod\n def format_retries(retries):\n return 'inf' if retries == float('inf') else '%.0f' % retries", "focal_method_lines": [122, 123], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def format_retries(retries):\n return 'inf' if retries == float('inf') else '%.0f' % retries", "has_branch": false, "total_branches": 0} {"prompt_id": 891, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "best_block_size", "focal_method_txt": " @staticmethod\n def best_block_size(elapsed_time, bytes):\n new_min = max(bytes / 2.0, 1.0)\n new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB\n if elapsed_time < 0.001:\n return int(new_max)\n rate = bytes / elapsed_time\n if rate > new_max:\n return int(new_max)\n if rate < new_min:\n return int(new_min)\n return int(rate)", "focal_method_lines": [126, 136], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def best_block_size(elapsed_time, bytes):\n new_min = max(bytes / 2.0, 1.0)\n new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB\n if elapsed_time < 0.001:\n return int(new_max)\n rate = bytes / elapsed_time\n if rate > new_max:\n return int(new_max)\n if rate < new_min:\n return int(new_min)\n return int(rate)", "has_branch": true, "total_branches": 2} {"prompt_id": 892, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "parse_bytes", "focal_method_txt": " @staticmethod\n def parse_bytes(bytestr):\n \"\"\"Parse a string indicating a byte quantity into an integer.\"\"\"\n matchobj = re.match(r'(?i)^(\\d+(?:\\.\\d+)?)([kMGTPEZY]?)$', bytestr)\n if matchobj is None:\n return None\n number = float(matchobj.group(1))\n multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())\n return int(round(number * multiplier))", "focal_method_lines": [139, 146], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n @staticmethod\n def parse_bytes(bytestr):\n \"\"\"Parse a string indicating a byte quantity into an integer.\"\"\"\n matchobj = re.match(r'(?i)^(\\d+(?:\\.\\d+)?)([kMGTPEZY]?)$', bytestr)\n if matchobj is None:\n return None\n number = float(matchobj.group(1))\n multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())\n return int(round(number * multiplier))", "has_branch": true, "total_branches": 2} {"prompt_id": 893, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "slow_down", "focal_method_txt": " def slow_down(self, start_time, now, byte_counter):\n \"\"\"Sleep if the download speed is over the rate limit.\"\"\"\n rate_limit = self.params.get('ratelimit')\n if rate_limit is None or byte_counter == 0:\n return\n if now is None:\n now = time.time()\n elapsed = now - start_time\n if elapsed <= 0.0:\n return\n speed = float(byte_counter) / elapsed\n if speed > rate_limit:\n sleep_time = float(byte_counter) / rate_limit - elapsed\n if sleep_time > 0:\n time.sleep(sleep_time)", "focal_method_lines": [166, 180], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def slow_down(self, start_time, now, byte_counter):\n \"\"\"Sleep if the download speed is over the rate limit.\"\"\"\n rate_limit = self.params.get('ratelimit')\n if rate_limit is None or byte_counter == 0:\n return\n if now is None:\n now = time.time()\n elapsed = now - start_time\n if elapsed <= 0.0:\n return\n speed = float(byte_counter) / elapsed\n if speed > rate_limit:\n sleep_time = float(byte_counter) / rate_limit - elapsed\n if sleep_time > 0:\n time.sleep(sleep_time)", "has_branch": true, "total_branches": 2} {"prompt_id": 894, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "temp_name", "focal_method_txt": " def temp_name(self, filename):\n \"\"\"Returns a temporary filename for the given filename.\"\"\"\n if self.params.get('nopart', False) or filename == '-' or \\\n (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):\n return filename\n return filename + '.part'", "focal_method_lines": [182, 187], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def temp_name(self, filename):\n \"\"\"Returns a temporary filename for the given filename.\"\"\"\n if self.params.get('nopart', False) or filename == '-' or \\\n (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):\n return filename\n return filename + '.part'", "has_branch": true, "total_branches": 2} {"prompt_id": 895, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "undo_temp_name", "focal_method_txt": " def undo_temp_name(self, filename):\n if filename.endswith('.part'):\n return filename[:-len('.part')]\n return filename", "focal_method_lines": [189, 192], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def undo_temp_name(self, filename):\n if filename.endswith('.part'):\n return filename[:-len('.part')]\n return filename", "has_branch": true, "total_branches": 2} {"prompt_id": 896, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "try_rename", "focal_method_txt": " def try_rename(self, old_filename, new_filename):\n try:\n if old_filename == new_filename:\n return\n os.rename(encodeFilename(old_filename), encodeFilename(new_filename))\n except (IOError, OSError) as err:\n self.report_error('unable to rename file: %s' % error_to_compat_str(err))", "focal_method_lines": [197, 203], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def try_rename(self, old_filename, new_filename):\n try:\n if old_filename == new_filename:\n return\n os.rename(encodeFilename(old_filename), encodeFilename(new_filename))\n except (IOError, OSError) as err:\n self.report_error('unable to rename file: %s' % error_to_compat_str(err))", "has_branch": true, "total_branches": 2} {"prompt_id": 897, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "try_utime", "focal_method_txt": " def try_utime(self, filename, last_modified_hdr):\n \"\"\"Try to set the last-modified time of the given file.\"\"\"\n if last_modified_hdr is None:\n return\n if not os.path.isfile(encodeFilename(filename)):\n return\n timestr = last_modified_hdr\n if timestr is None:\n return\n filetime = timeconvert(timestr)\n if filetime is None:\n return filetime\n # Ignore obviously invalid dates\n if filetime == 0:\n return\n try:\n os.utime(filename, (time.time(), filetime))\n except Exception:\n pass\n return filetime", "focal_method_lines": [205, 224], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def try_utime(self, filename, last_modified_hdr):\n \"\"\"Try to set the last-modified time of the given file.\"\"\"\n if last_modified_hdr is None:\n return\n if not os.path.isfile(encodeFilename(filename)):\n return\n timestr = last_modified_hdr\n if timestr is None:\n return\n filetime = timeconvert(timestr)\n if filetime is None:\n return filetime\n # Ignore obviously invalid dates\n if filetime == 0:\n return\n try:\n os.utime(filename, (time.time(), filetime))\n except Exception:\n pass\n return filetime", "has_branch": true, "total_branches": 2} {"prompt_id": 898, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "report_progress", "focal_method_txt": " def report_progress(self, s):\n if s['status'] == 'finished':\n if self.params.get('noprogress', False):\n self.to_screen('[download] Download completed')\n else:\n msg_template = '100%%'\n if s.get('total_bytes') is not None:\n s['_total_bytes_str'] = format_bytes(s['total_bytes'])\n msg_template += ' of %(_total_bytes_str)s'\n if s.get('elapsed') is not None:\n s['_elapsed_str'] = self.format_seconds(s['elapsed'])\n msg_template += ' in %(_elapsed_str)s'\n self._report_progress_status(\n msg_template % s, is_last_line=True)\n\n if self.params.get('noprogress'):\n return\n\n if s['status'] != 'downloading':\n return\n\n if s.get('eta') is not None:\n s['_eta_str'] = self.format_eta(s['eta'])\n else:\n s['_eta_str'] = 'Unknown ETA'\n\n if s.get('total_bytes') and s.get('downloaded_bytes') is not None:\n s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])\n elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:\n s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])\n else:\n if s.get('downloaded_bytes') == 0:\n s['_percent_str'] = self.format_percent(0)\n else:\n s['_percent_str'] = 'Unknown %'\n\n if s.get('speed') is not None:\n s['_speed_str'] = self.format_speed(s['speed'])\n else:\n s['_speed_str'] = 'Unknown speed'\n\n if s.get('total_bytes') is not None:\n s['_total_bytes_str'] = format_bytes(s['total_bytes'])\n msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'\n elif s.get('total_bytes_estimate') is not None:\n s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])\n msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'\n else:\n if s.get('downloaded_bytes') is not None:\n s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])\n if s.get('elapsed'):\n s['_elapsed_str'] = self.format_seconds(s['elapsed'])\n msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'\n else:\n msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'\n else:\n msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'\n\n self._report_progress_status(msg_template % s)", "focal_method_lines": [247, 305], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def report_progress(self, s):\n if s['status'] == 'finished':\n if self.params.get('noprogress', False):\n self.to_screen('[download] Download completed')\n else:\n msg_template = '100%%'\n if s.get('total_bytes') is not None:\n s['_total_bytes_str'] = format_bytes(s['total_bytes'])\n msg_template += ' of %(_total_bytes_str)s'\n if s.get('elapsed') is not None:\n s['_elapsed_str'] = self.format_seconds(s['elapsed'])\n msg_template += ' in %(_elapsed_str)s'\n self._report_progress_status(\n msg_template % s, is_last_line=True)\n\n if self.params.get('noprogress'):\n return\n\n if s['status'] != 'downloading':\n return\n\n if s.get('eta') is not None:\n s['_eta_str'] = self.format_eta(s['eta'])\n else:\n s['_eta_str'] = 'Unknown ETA'\n\n if s.get('total_bytes') and s.get('downloaded_bytes') is not None:\n s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])\n elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:\n s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])\n else:\n if s.get('downloaded_bytes') == 0:\n s['_percent_str'] = self.format_percent(0)\n else:\n s['_percent_str'] = 'Unknown %'\n\n if s.get('speed') is not None:\n s['_speed_str'] = self.format_speed(s['speed'])\n else:\n s['_speed_str'] = 'Unknown speed'\n\n if s.get('total_bytes') is not None:\n s['_total_bytes_str'] = format_bytes(s['total_bytes'])\n msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'\n elif s.get('total_bytes_estimate') is not None:\n s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])\n msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'\n else:\n if s.get('downloaded_bytes') is not None:\n s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])\n if s.get('elapsed'):\n s['_elapsed_str'] = self.format_seconds(s['elapsed'])\n msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'\n else:\n msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'\n else:\n msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'\n\n self._report_progress_status(msg_template % s)", "has_branch": true, "total_branches": 2} {"prompt_id": 899, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "report_file_already_downloaded", "focal_method_txt": " def report_file_already_downloaded(self, file_name):\n \"\"\"Report file has already been fully downloaded.\"\"\"\n try:\n self.to_screen('[download] %s has already been downloaded' % file_name)\n except UnicodeEncodeError:\n self.to_screen('[download] The file has already been downloaded')", "focal_method_lines": [317, 322], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def report_file_already_downloaded(self, file_name):\n \"\"\"Report file has already been fully downloaded.\"\"\"\n try:\n self.to_screen('[download] %s has already been downloaded' % file_name)\n except UnicodeEncodeError:\n self.to_screen('[download] The file has already been downloaded')", "has_branch": false, "total_branches": 0} {"prompt_id": 900, "project": "youtube_dl", "module": "youtube_dl.downloader.common", "class": "FileDownloader", "method": "download", "focal_method_txt": " def download(self, filename, info_dict):\n \"\"\"Download to a filename using the info from info_dict\n Return True on success and False otherwise\n \"\"\"\n\n nooverwrites_and_exists = (\n self.params.get('nooverwrites', False)\n and os.path.exists(encodeFilename(filename))\n )\n\n if not hasattr(filename, 'write'):\n continuedl_and_exists = (\n self.params.get('continuedl', True)\n and os.path.isfile(encodeFilename(filename))\n and not self.params.get('nopart', False)\n )\n\n # Check file already present\n if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):\n self.report_file_already_downloaded(filename)\n self._hook_progress({\n 'filename': filename,\n 'status': 'finished',\n 'total_bytes': os.path.getsize(encodeFilename(filename)),\n })\n return True\n\n min_sleep_interval = self.params.get('sleep_interval')\n if min_sleep_interval:\n max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval)\n sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval)\n self.to_screen(\n '[download] Sleeping %s seconds...' % (\n int(sleep_interval) if sleep_interval.is_integer()\n else '%.2f' % sleep_interval))\n time.sleep(sleep_interval)\n\n return self.real_download(filename, info_dict)", "focal_method_lines": [328, 365], "in_stack": false, "globals": [], "type_context": "import os\nimport re\nimport sys\nimport time\nimport random\nfrom ..compat import compat_os_name\nfrom ..utils import (\n decodeArgument,\n encodeFilename,\n error_to_compat_str,\n format_bytes,\n shell_quote,\n timeconvert,\n)\n\n\n\nclass FileDownloader(object):\n\n _TEST_FILE_SIZE = 10241\n\n params = None\n\n def __init__(self, ydl, params):\n \"\"\"Create a FileDownloader object with the given options.\"\"\"\n self.ydl = ydl\n self._progress_hooks = []\n self.params = params\n self.add_progress_hook(self.report_progress)\n\n def download(self, filename, info_dict):\n \"\"\"Download to a filename using the info from info_dict\n Return True on success and False otherwise\n \"\"\"\n\n nooverwrites_and_exists = (\n self.params.get('nooverwrites', False)\n and os.path.exists(encodeFilename(filename))\n )\n\n if not hasattr(filename, 'write'):\n continuedl_and_exists = (\n self.params.get('continuedl', True)\n and os.path.isfile(encodeFilename(filename))\n and not self.params.get('nopart', False)\n )\n\n # Check file already present\n if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):\n self.report_file_already_downloaded(filename)\n self._hook_progress({\n 'filename': filename,\n 'status': 'finished',\n 'total_bytes': os.path.getsize(encodeFilename(filename)),\n })\n return True\n\n min_sleep_interval = self.params.get('sleep_interval')\n if min_sleep_interval:\n max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval)\n sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval)\n self.to_screen(\n '[download] Sleeping %s seconds...' % (\n int(sleep_interval) if sleep_interval.is_integer()\n else '%.2f' % sleep_interval))\n time.sleep(sleep_interval)\n\n return self.real_download(filename, info_dict)", "has_branch": true, "total_branches": 2} {"prompt_id": 901, "project": "youtube_dl", "module": "youtube_dl.downloader.dash", "class": "DashSegmentsFD", "method": "real_download", "focal_method_txt": " def real_download(self, filename, info_dict):\n fragment_base_url = info_dict.get('fragment_base_url')\n fragments = info_dict['fragments'][:1] if self.params.get(\n 'test', False) else info_dict['fragments']\n\n ctx = {\n 'filename': filename,\n 'total_frags': len(fragments),\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n\n frag_index = 0\n for i, fragment in enumerate(fragments):\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n # In DASH, the first segment contains necessary headers to\n # generate a valid MP4 file, so always abort for the first segment\n fatal = i == 0 or not skip_unavailable_fragments\n count = 0\n while count <= fragment_retries:\n try:\n fragment_url = fragment.get('url')\n if not fragment_url:\n assert fragment_base_url\n fragment_url = urljoin(fragment_base_url, fragment['path'])\n success, frag_content = self._download_fragment(ctx, fragment_url, info_dict)\n if not success:\n return False\n self._append_fragment(ctx, frag_content)\n break\n except compat_urllib_error.HTTPError as err:\n # YouTube may often return 404 HTTP error for a fragment causing the\n # whole download to fail. However if the same fragment is immediately\n # retried with the same request data this usually succeeds (1-2 attempts\n # is usually enough) thus allowing to download the whole file successfully.\n # To be future-proof we will retry all fragments that fail with any\n # HTTP error.\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n except DownloadError:\n # Don't retry fragment if error occurred during HTTP downloading\n # itself since it has own retry settings\n if not fatal:\n self.report_skip_fragment(frag_index)\n break\n raise\n\n if count > fragment_retries:\n if not fatal:\n self.report_skip_fragment(frag_index)\n continue\n self.report_error('giving up after %s fragment retries' % fragment_retries)\n return False\n\n self._finish_frag_download(ctx)\n\n return True", "focal_method_lines": [17, 79], "in_stack": false, "globals": [], "type_context": "from .fragment import FragmentFD\nfrom ..compat import compat_urllib_error\nfrom ..utils import (\n DownloadError,\n urljoin,\n)\n\n\n\nclass DashSegmentsFD(FragmentFD):\n\n FD_NAME = 'dashsegments'\n\n def real_download(self, filename, info_dict):\n fragment_base_url = info_dict.get('fragment_base_url')\n fragments = info_dict['fragments'][:1] if self.params.get(\n 'test', False) else info_dict['fragments']\n\n ctx = {\n 'filename': filename,\n 'total_frags': len(fragments),\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n\n frag_index = 0\n for i, fragment in enumerate(fragments):\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n # In DASH, the first segment contains necessary headers to\n # generate a valid MP4 file, so always abort for the first segment\n fatal = i == 0 or not skip_unavailable_fragments\n count = 0\n while count <= fragment_retries:\n try:\n fragment_url = fragment.get('url')\n if not fragment_url:\n assert fragment_base_url\n fragment_url = urljoin(fragment_base_url, fragment['path'])\n success, frag_content = self._download_fragment(ctx, fragment_url, info_dict)\n if not success:\n return False\n self._append_fragment(ctx, frag_content)\n break\n except compat_urllib_error.HTTPError as err:\n # YouTube may often return 404 HTTP error for a fragment causing the\n # whole download to fail. However if the same fragment is immediately\n # retried with the same request data this usually succeeds (1-2 attempts\n # is usually enough) thus allowing to download the whole file successfully.\n # To be future-proof we will retry all fragments that fail with any\n # HTTP error.\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n except DownloadError:\n # Don't retry fragment if error occurred during HTTP downloading\n # itself since it has own retry settings\n if not fatal:\n self.report_skip_fragment(frag_index)\n break\n raise\n\n if count > fragment_retries:\n if not fatal:\n self.report_skip_fragment(frag_index)\n continue\n self.report_error('giving up after %s fragment retries' % fragment_retries)\n return False\n\n self._finish_frag_download(ctx)\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 902, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "", "method": "build_fragments_list", "focal_method_txt": "def build_fragments_list(boot_info):\n \"\"\" Return a list of (segment, fragment) for each fragment in the video \"\"\"\n res = []\n segment_run_table = boot_info['segments'][0]\n fragment_run_entry_table = boot_info['fragments'][0]['fragments']\n first_frag_number = fragment_run_entry_table[0]['first']\n fragments_counter = itertools.count(first_frag_number)\n for segment, fragments_count in segment_run_table['segment_run']:\n # In some live HDS streams (for example Rai), `fragments_count` is\n # abnormal and causing out-of-memory errors. It's OK to change the\n # number of fragments for live streams as they are updated periodically\n if fragments_count == 4294967295 and boot_info['live']:\n fragments_count = 2\n for _ in range(fragments_count):\n res.append((segment, next(fragments_counter)))\n\n if boot_info['live']:\n res = res[-2:]\n\n return res", "focal_method_lines": [187, 206], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\ndef build_fragments_list(boot_info):\n \"\"\" Return a list of (segment, fragment) for each fragment in the video \"\"\"\n res = []\n segment_run_table = boot_info['segments'][0]\n fragment_run_entry_table = boot_info['fragments'][0]['fragments']\n first_frag_number = fragment_run_entry_table[0]['first']\n fragments_counter = itertools.count(first_frag_number)\n for segment, fragments_count in segment_run_table['segment_run']:\n # In some live HDS streams (for example Rai), `fragments_count` is\n # abnormal and causing out-of-memory errors. It's OK to change the\n # number of fragments for live streams as they are updated periodically\n if fragments_count == 4294967295 and boot_info['live']:\n fragments_count = 2\n for _ in range(fragments_count):\n res.append((segment, next(fragments_counter)))\n\n if boot_info['live']:\n res = res[-2:]\n\n return res", "has_branch": true, "total_branches": 2} {"prompt_id": 903, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "", "method": "write_flv_header", "focal_method_txt": "def write_flv_header(stream):\n \"\"\"Writes the FLV header to stream\"\"\"\n # FLV header\n stream.write(b'FLV\\x01')\n stream.write(b'\\x05')\n stream.write(b'\\x00\\x00\\x00\\x09')\n stream.write(b'\\x00\\x00\\x00\\x00')", "focal_method_lines": [217, 223], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\ndef write_flv_header(stream):\n \"\"\"Writes the FLV header to stream\"\"\"\n # FLV header\n stream.write(b'FLV\\x01')\n stream.write(b'\\x05')\n stream.write(b'\\x00\\x00\\x00\\x09')\n stream.write(b'\\x00\\x00\\x00\\x00')", "has_branch": false, "total_branches": 0} {"prompt_id": 904, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "", "method": "write_metadata_tag", "focal_method_txt": "def write_metadata_tag(stream, metadata):\n \"\"\"Writes optional metadata tag to stream\"\"\"\n SCRIPT_TAG = b'\\x12'\n FLV_TAG_HEADER_LEN = 11\n\n if metadata:\n stream.write(SCRIPT_TAG)\n write_unsigned_int_24(stream, len(metadata))\n stream.write(b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n stream.write(metadata)\n write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))", "focal_method_lines": [226, 236], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\ndef write_metadata_tag(stream, metadata):\n \"\"\"Writes optional metadata tag to stream\"\"\"\n SCRIPT_TAG = b'\\x12'\n FLV_TAG_HEADER_LEN = 11\n\n if metadata:\n stream.write(SCRIPT_TAG)\n write_unsigned_int_24(stream, len(metadata))\n stream.write(b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n stream.write(metadata)\n write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))", "has_branch": true, "total_branches": 2} {"prompt_id": 905, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "", "method": "remove_encrypted_media", "focal_method_txt": "def remove_encrypted_media(media):\n return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib\n and 'drmAdditionalHeaderSetId' not in e.attrib,\n media))", "focal_method_lines": [239, 240], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\ndef remove_encrypted_media(media):\n return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib\n and 'drmAdditionalHeaderSetId' not in e.attrib,\n media))", "has_branch": false, "total_branches": 0} {"prompt_id": 906, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "", "method": "get_base_url", "focal_method_txt": "def get_base_url(manifest):\n base_url = xpath_text(\n manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)],\n 'base URL', default=None)\n if base_url:\n base_url = base_url.strip()\n return base_url", "focal_method_lines": [249, 255], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\ndef get_base_url(manifest):\n base_url = xpath_text(\n manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)],\n 'base URL', default=None)\n if base_url:\n base_url = base_url.strip()\n return base_url", "has_branch": true, "total_branches": 2} {"prompt_id": 907, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_string", "focal_method_txt": " def read_string(self):\n res = b''\n while True:\n char = self.read_bytes(1)\n if char == b'\\x00':\n break\n res += char\n return res", "focal_method_lines": [50, 57], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_string(self):\n res = b''\n while True:\n char = self.read_bytes(1)\n if char == b'\\x00':\n break\n res += char\n return res", "has_branch": true, "total_branches": 2} {"prompt_id": 908, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_box_info", "focal_method_txt": " def read_box_info(self):\n \"\"\"\n Read a box and return the info as a tuple: (box_size, box_type, box_data)\n \"\"\"\n real_size = size = self.read_unsigned_int()\n box_type = self.read_bytes(4)\n header_end = 8\n if size == 1:\n real_size = self.read_unsigned_long_long()\n header_end = 16\n return real_size, box_type, self.read_bytes(real_size - header_end)", "focal_method_lines": [59, 69], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_box_info(self):\n \"\"\"\n Read a box and return the info as a tuple: (box_size, box_type, box_data)\n \"\"\"\n real_size = size = self.read_unsigned_int()\n box_type = self.read_bytes(4)\n header_end = 8\n if size == 1:\n real_size = self.read_unsigned_long_long()\n header_end = 16\n return real_size, box_type, self.read_bytes(real_size - header_end)", "has_branch": true, "total_branches": 2} {"prompt_id": 909, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_asrt", "focal_method_txt": " def read_asrt(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n quality_entry_count = self.read_unsigned_char()\n # QualityEntryCount\n for i in range(quality_entry_count):\n self.read_string()\n\n segment_run_count = self.read_unsigned_int()\n segments = []\n for i in range(segment_run_count):\n first_segment = self.read_unsigned_int()\n fragments_per_segment = self.read_unsigned_int()\n segments.append((first_segment, fragments_per_segment))\n\n return {\n 'segment_run': segments,\n }", "focal_method_lines": [71, 88], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_asrt(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n quality_entry_count = self.read_unsigned_char()\n # QualityEntryCount\n for i in range(quality_entry_count):\n self.read_string()\n\n segment_run_count = self.read_unsigned_int()\n segments = []\n for i in range(segment_run_count):\n first_segment = self.read_unsigned_int()\n fragments_per_segment = self.read_unsigned_int()\n segments.append((first_segment, fragments_per_segment))\n\n return {\n 'segment_run': segments,\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 910, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_afrt", "focal_method_txt": " def read_afrt(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n # time scale\n self.read_unsigned_int()\n\n quality_entry_count = self.read_unsigned_char()\n # QualitySegmentUrlModifiers\n for i in range(quality_entry_count):\n self.read_string()\n\n fragments_count = self.read_unsigned_int()\n fragments = []\n for i in range(fragments_count):\n first = self.read_unsigned_int()\n first_ts = self.read_unsigned_long_long()\n duration = self.read_unsigned_int()\n if duration == 0:\n discontinuity_indicator = self.read_unsigned_char()\n else:\n discontinuity_indicator = None\n fragments.append({\n 'first': first,\n 'ts': first_ts,\n 'duration': duration,\n 'discontinuity_indicator': discontinuity_indicator,\n })\n\n return {\n 'fragments': fragments,\n }", "focal_method_lines": [92, 122], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_afrt(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n # time scale\n self.read_unsigned_int()\n\n quality_entry_count = self.read_unsigned_char()\n # QualitySegmentUrlModifiers\n for i in range(quality_entry_count):\n self.read_string()\n\n fragments_count = self.read_unsigned_int()\n fragments = []\n for i in range(fragments_count):\n first = self.read_unsigned_int()\n first_ts = self.read_unsigned_long_long()\n duration = self.read_unsigned_int()\n if duration == 0:\n discontinuity_indicator = self.read_unsigned_char()\n else:\n discontinuity_indicator = None\n fragments.append({\n 'first': first,\n 'ts': first_ts,\n 'duration': duration,\n 'discontinuity_indicator': discontinuity_indicator,\n })\n\n return {\n 'fragments': fragments,\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 911, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_abst", "focal_method_txt": " def read_abst(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n\n self.read_unsigned_int() # BootstrapinfoVersion\n # Profile,Live,Update,Reserved\n flags = self.read_unsigned_char()\n live = flags & 0x20 != 0\n # time scale\n self.read_unsigned_int()\n # CurrentMediaTime\n self.read_unsigned_long_long()\n # SmpteTimeCodeOffset\n self.read_unsigned_long_long()\n\n self.read_string() # MovieIdentifier\n server_count = self.read_unsigned_char()\n # ServerEntryTable\n for i in range(server_count):\n self.read_string()\n quality_count = self.read_unsigned_char()\n # QualityEntryTable\n for i in range(quality_count):\n self.read_string()\n # DrmData\n self.read_string()\n # MetaData\n self.read_string()\n\n segments_count = self.read_unsigned_char()\n segments = []\n for i in range(segments_count):\n box_size, box_type, box_data = self.read_box_info()\n assert box_type == b'asrt'\n segment = FlvReader(box_data).read_asrt()\n segments.append(segment)\n fragments_run_count = self.read_unsigned_char()\n fragments = []\n for i in range(fragments_run_count):\n box_size, box_type, box_data = self.read_box_info()\n assert box_type == b'afrt'\n fragments.append(FlvReader(box_data).read_afrt())\n\n return {\n 'segments': segments,\n 'fragments': fragments,\n 'live': live,\n }", "focal_method_lines": [126, 171], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_abst(self):\n # version\n self.read_unsigned_char()\n # flags\n self.read_bytes(3)\n\n self.read_unsigned_int() # BootstrapinfoVersion\n # Profile,Live,Update,Reserved\n flags = self.read_unsigned_char()\n live = flags & 0x20 != 0\n # time scale\n self.read_unsigned_int()\n # CurrentMediaTime\n self.read_unsigned_long_long()\n # SmpteTimeCodeOffset\n self.read_unsigned_long_long()\n\n self.read_string() # MovieIdentifier\n server_count = self.read_unsigned_char()\n # ServerEntryTable\n for i in range(server_count):\n self.read_string()\n quality_count = self.read_unsigned_char()\n # QualityEntryTable\n for i in range(quality_count):\n self.read_string()\n # DrmData\n self.read_string()\n # MetaData\n self.read_string()\n\n segments_count = self.read_unsigned_char()\n segments = []\n for i in range(segments_count):\n box_size, box_type, box_data = self.read_box_info()\n assert box_type == b'asrt'\n segment = FlvReader(box_data).read_asrt()\n segments.append(segment)\n fragments_run_count = self.read_unsigned_char()\n fragments = []\n for i in range(fragments_run_count):\n box_size, box_type, box_data = self.read_box_info()\n assert box_type == b'afrt'\n fragments.append(FlvReader(box_data).read_afrt())\n\n return {\n 'segments': segments,\n 'fragments': fragments,\n 'live': live,\n }", "has_branch": true, "total_branches": 2} {"prompt_id": 912, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "FlvReader", "method": "read_bootstrap_info", "focal_method_txt": " def read_bootstrap_info(self):\n total_size, box_type, box_data = self.read_box_info()\n assert box_type == b'abst'\n return FlvReader(box_data).read_abst()", "focal_method_lines": [177, 180], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass FlvReader(io.BytesIO):\n\n def read_bootstrap_info(self):\n total_size, box_type, box_data = self.read_box_info()\n assert box_type == b'abst'\n return FlvReader(box_data).read_abst()", "has_branch": false, "total_branches": 0} {"prompt_id": 913, "project": "youtube_dl", "module": "youtube_dl.downloader.f4m", "class": "F4mFD", "method": "real_download", "focal_method_txt": " def real_download(self, filename, info_dict):\n man_url = info_dict['url']\n requested_bitrate = info_dict.get('tbr')\n self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)\n\n urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))\n man_url = urlh.geturl()\n # Some manifests may be malformed, e.g. prosiebensat1 generated manifests\n # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244\n # and https://github.com/ytdl-org/youtube-dl/issues/7823)\n manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()\n\n doc = compat_etree_fromstring(manifest)\n formats = [(int(f.attrib.get('bitrate', -1)), f)\n for f in self._get_unencrypted_media(doc)]\n if requested_bitrate is None or len(formats) == 1:\n # get the best format\n formats = sorted(formats, key=lambda f: f[0])\n rate, media = formats[-1]\n else:\n rate, media = list(filter(\n lambda f: int(f[0]) == requested_bitrate, formats))[0]\n\n # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec.\n man_base_url = get_base_url(doc) or man_url\n\n base_url = compat_urlparse.urljoin(man_base_url, media.attrib['url'])\n bootstrap_node = doc.find(_add_ns('bootstrapInfo'))\n boot_info, bootstrap_url = self._parse_bootstrap_node(\n bootstrap_node, man_base_url)\n live = boot_info['live']\n metadata_node = media.find(_add_ns('metadata'))\n if metadata_node is not None:\n metadata = compat_b64decode(metadata_node.text)\n else:\n metadata = None\n\n fragments_list = build_fragments_list(boot_info)\n test = self.params.get('test', False)\n if test:\n # We only download the first fragment\n fragments_list = fragments_list[:1]\n total_frags = len(fragments_list)\n # For some akamai manifests we'll need to add a query to the fragment url\n akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))\n\n ctx = {\n 'filename': filename,\n 'total_frags': total_frags,\n 'live': live,\n }\n\n self._prepare_frag_download(ctx)\n\n dest_stream = ctx['dest_stream']\n\n if ctx['complete_frags_downloaded_bytes'] == 0:\n write_flv_header(dest_stream)\n if not live:\n write_metadata_tag(dest_stream, metadata)\n\n base_url_parsed = compat_urllib_parse_urlparse(base_url)\n\n self._start_frag_download(ctx)\n\n frag_index = 0\n while fragments_list:\n seg_i, frag_i = fragments_list.pop(0)\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n name = 'Seg%d-Frag%d' % (seg_i, frag_i)\n query = []\n if base_url_parsed.query:\n query.append(base_url_parsed.query)\n if akamai_pv:\n query.append(akamai_pv.strip(';'))\n if info_dict.get('extra_param_to_segment_url'):\n query.append(info_dict['extra_param_to_segment_url'])\n url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))\n try:\n success, down_data = self._download_fragment(ctx, url_parsed.geturl(), info_dict)\n if not success:\n return False\n reader = FlvReader(down_data)\n while True:\n try:\n _, box_type, box_data = reader.read_box_info()\n except DataTruncatedError:\n if test:\n # In tests, segments may be truncated, and thus\n # FlvReader may not be able to parse the whole\n # chunk. If so, write the segment as is\n # See https://github.com/ytdl-org/youtube-dl/issues/9214\n dest_stream.write(down_data)\n break\n raise\n if box_type == b'mdat':\n self._append_fragment(ctx, box_data)\n break\n except (compat_urllib_error.HTTPError, ) as err:\n if live and (err.code == 404 or err.code == 410):\n # We didn't keep up with the live window. Continue\n # with the next available fragment.\n msg = 'Fragment %d unavailable' % frag_i\n self.report_warning(msg)\n fragments_list = []\n else:\n raise\n\n if not fragments_list and not test and live and bootstrap_url:\n fragments_list = self._update_live_fragments(bootstrap_url, frag_i)\n total_frags += len(fragments_list)\n if fragments_list and (fragments_list[0][1] > frag_i + 1):\n msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))\n self.report_warning(msg)\n\n self._finish_frag_download(ctx)\n\n return True", "focal_method_lines": [318, 437], "in_stack": false, "globals": [], "type_context": "import io\nimport itertools\nimport time\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_b64decode,\n compat_etree_fromstring,\n compat_urlparse,\n compat_urllib_error,\n compat_urllib_parse_urlparse,\n compat_struct_pack,\n compat_struct_unpack,\n)\nfrom ..utils import (\n fix_xml_ampersands,\n xpath_text,\n)\n\n\n\nclass F4mFD(FragmentFD):\n\n FD_NAME = 'f4m'\n\n def real_download(self, filename, info_dict):\n man_url = info_dict['url']\n requested_bitrate = info_dict.get('tbr')\n self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)\n\n urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))\n man_url = urlh.geturl()\n # Some manifests may be malformed, e.g. prosiebensat1 generated manifests\n # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244\n # and https://github.com/ytdl-org/youtube-dl/issues/7823)\n manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()\n\n doc = compat_etree_fromstring(manifest)\n formats = [(int(f.attrib.get('bitrate', -1)), f)\n for f in self._get_unencrypted_media(doc)]\n if requested_bitrate is None or len(formats) == 1:\n # get the best format\n formats = sorted(formats, key=lambda f: f[0])\n rate, media = formats[-1]\n else:\n rate, media = list(filter(\n lambda f: int(f[0]) == requested_bitrate, formats))[0]\n\n # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec.\n man_base_url = get_base_url(doc) or man_url\n\n base_url = compat_urlparse.urljoin(man_base_url, media.attrib['url'])\n bootstrap_node = doc.find(_add_ns('bootstrapInfo'))\n boot_info, bootstrap_url = self._parse_bootstrap_node(\n bootstrap_node, man_base_url)\n live = boot_info['live']\n metadata_node = media.find(_add_ns('metadata'))\n if metadata_node is not None:\n metadata = compat_b64decode(metadata_node.text)\n else:\n metadata = None\n\n fragments_list = build_fragments_list(boot_info)\n test = self.params.get('test', False)\n if test:\n # We only download the first fragment\n fragments_list = fragments_list[:1]\n total_frags = len(fragments_list)\n # For some akamai manifests we'll need to add a query to the fragment url\n akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))\n\n ctx = {\n 'filename': filename,\n 'total_frags': total_frags,\n 'live': live,\n }\n\n self._prepare_frag_download(ctx)\n\n dest_stream = ctx['dest_stream']\n\n if ctx['complete_frags_downloaded_bytes'] == 0:\n write_flv_header(dest_stream)\n if not live:\n write_metadata_tag(dest_stream, metadata)\n\n base_url_parsed = compat_urllib_parse_urlparse(base_url)\n\n self._start_frag_download(ctx)\n\n frag_index = 0\n while fragments_list:\n seg_i, frag_i = fragments_list.pop(0)\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n name = 'Seg%d-Frag%d' % (seg_i, frag_i)\n query = []\n if base_url_parsed.query:\n query.append(base_url_parsed.query)\n if akamai_pv:\n query.append(akamai_pv.strip(';'))\n if info_dict.get('extra_param_to_segment_url'):\n query.append(info_dict['extra_param_to_segment_url'])\n url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))\n try:\n success, down_data = self._download_fragment(ctx, url_parsed.geturl(), info_dict)\n if not success:\n return False\n reader = FlvReader(down_data)\n while True:\n try:\n _, box_type, box_data = reader.read_box_info()\n except DataTruncatedError:\n if test:\n # In tests, segments may be truncated, and thus\n # FlvReader may not be able to parse the whole\n # chunk. If so, write the segment as is\n # See https://github.com/ytdl-org/youtube-dl/issues/9214\n dest_stream.write(down_data)\n break\n raise\n if box_type == b'mdat':\n self._append_fragment(ctx, box_data)\n break\n except (compat_urllib_error.HTTPError, ) as err:\n if live and (err.code == 404 or err.code == 410):\n # We didn't keep up with the live window. Continue\n # with the next available fragment.\n msg = 'Fragment %d unavailable' % frag_i\n self.report_warning(msg)\n fragments_list = []\n else:\n raise\n\n if not fragments_list and not test and live and bootstrap_url:\n fragments_list = self._update_live_fragments(bootstrap_url, frag_i)\n total_frags += len(fragments_list)\n if fragments_list and (fragments_list[0][1] > frag_i + 1):\n msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))\n self.report_warning(msg)\n\n self._finish_frag_download(ctx)\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 914, "project": "youtube_dl", "module": "youtube_dl.downloader.hls", "class": "HlsFD", "method": "can_download", "focal_method_txt": " @staticmethod\n def can_download(manifest, info_dict):\n UNSUPPORTED_FEATURES = (\n r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]\n # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]\n\n # Live streams heuristic does not always work (e.g. geo restricted to Germany\n # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0)\n # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]\n\n # This heuristic also is not correct since segments may not be appended as well.\n # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite\n # no segments will definitely be appended to the end of the playlist.\n # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of\n # # event media playlists [4]\n r'#EXT-X-MAP:', # media initialization [5]\n\n # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4\n # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2\n # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2\n # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5\n # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5\n )\n check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]\n is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest\n check_results.append(can_decrypt_frag or not is_aes128_enc)\n check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest))\n check_results.append(not info_dict.get('is_live'))\n return all(check_results)", "focal_method_lines": [30, 57], "in_stack": false, "globals": [], "type_context": "import re\nimport binascii\nfrom .fragment import FragmentFD\nfrom .external import FFmpegFD\nfrom ..compat import (\n compat_urllib_error,\n compat_urlparse,\n compat_struct_pack,\n)\nfrom ..utils import (\n parse_m3u8_attributes,\n update_url_query,\n)\n\n\n\nclass HlsFD(FragmentFD):\n\n FD_NAME = 'hlsnative'\n\n @staticmethod\n def can_download(manifest, info_dict):\n UNSUPPORTED_FEATURES = (\n r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]\n # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]\n\n # Live streams heuristic does not always work (e.g. geo restricted to Germany\n # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0)\n # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]\n\n # This heuristic also is not correct since segments may not be appended as well.\n # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite\n # no segments will definitely be appended to the end of the playlist.\n # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of\n # # event media playlists [4]\n r'#EXT-X-MAP:', # media initialization [5]\n\n # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4\n # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2\n # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2\n # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5\n # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5\n )\n check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]\n is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest\n check_results.append(can_decrypt_frag or not is_aes128_enc)\n check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest))\n check_results.append(not info_dict.get('is_live'))\n return all(check_results)", "has_branch": false, "total_branches": 0} {"prompt_id": 915, "project": "youtube_dl", "module": "youtube_dl.downloader.hls", "class": "HlsFD", "method": "real_download", "focal_method_txt": " def real_download(self, filename, info_dict):\n man_url = info_dict['url']\n self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)\n\n urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))\n man_url = urlh.geturl()\n s = urlh.read().decode('utf-8', 'ignore')\n\n if not self.can_download(s, info_dict):\n if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'):\n self.report_error('pycrypto not found. Please install it.')\n return False\n self.report_warning(\n 'hlsnative has detected features it does not support, '\n 'extraction will be delegated to ffmpeg')\n fd = FFmpegFD(self.ydl, self.params)\n for ph in self._progress_hooks:\n fd.add_progress_hook(ph)\n return fd.real_download(filename, info_dict)\n\n def is_ad_fragment_start(s):\n return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s\n or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad'))\n\n def is_ad_fragment_end(s):\n return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s\n or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment'))\n\n media_frags = 0\n ad_frags = 0\n ad_frag_next = False\n for line in s.splitlines():\n line = line.strip()\n if not line:\n continue\n if line.startswith('#'):\n if is_ad_fragment_start(line):\n ad_frag_next = True\n elif is_ad_fragment_end(line):\n ad_frag_next = False\n continue\n if ad_frag_next:\n ad_frags += 1\n continue\n media_frags += 1\n\n ctx = {\n 'filename': filename,\n 'total_frags': media_frags,\n 'ad_frags': ad_frags,\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n test = self.params.get('test', False)\n\n extra_query = None\n extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')\n if extra_param_to_segment_url:\n extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)\n i = 0\n media_sequence = 0\n decrypt_info = {'METHOD': 'NONE'}\n byte_range = {}\n frag_index = 0\n ad_frag_next = False\n for line in s.splitlines():\n line = line.strip()\n if line:\n if not line.startswith('#'):\n if ad_frag_next:\n continue\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n frag_url = (\n line\n if re.match(r'^https?://', line)\n else compat_urlparse.urljoin(man_url, line))\n if extra_query:\n frag_url = update_url_query(frag_url, extra_query)\n count = 0\n headers = info_dict.get('http_headers', {})\n if byte_range:\n headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)\n while count <= fragment_retries:\n try:\n success, frag_content = self._download_fragment(\n ctx, frag_url, info_dict, headers)\n if not success:\n return False\n break\n except compat_urllib_error.HTTPError as err:\n # Unavailable (possibly temporary) fragments may be served.\n # First we try to retry then either skip or abort.\n # See https://github.com/ytdl-org/youtube-dl/issues/10165,\n # https://github.com/ytdl-org/youtube-dl/issues/10448).\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n if count > fragment_retries:\n if skip_unavailable_fragments:\n i += 1\n media_sequence += 1\n self.report_skip_fragment(frag_index)\n continue\n self.report_error(\n 'giving up after %s fragment retries' % fragment_retries)\n return False\n if decrypt_info['METHOD'] == 'AES-128':\n iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)\n decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(\n self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()\n # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block\n # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,\n # not what it decrypts to.\n if not test:\n frag_content = AES.new(\n decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)\n self._append_fragment(ctx, frag_content)\n # We only download the first fragment during the test\n if test:\n break\n i += 1\n media_sequence += 1\n elif line.startswith('#EXT-X-KEY'):\n decrypt_url = decrypt_info.get('URI')\n decrypt_info = parse_m3u8_attributes(line[11:])\n if decrypt_info['METHOD'] == 'AES-128':\n if 'IV' in decrypt_info:\n decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))\n if not re.match(r'^https?://', decrypt_info['URI']):\n decrypt_info['URI'] = compat_urlparse.urljoin(\n man_url, decrypt_info['URI'])\n if extra_query:\n decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)\n if decrypt_url != decrypt_info['URI']:\n decrypt_info['KEY'] = None\n elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):\n media_sequence = int(line[22:])\n elif line.startswith('#EXT-X-BYTERANGE'):\n splitted_byte_range = line[17:].split('@')\n sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']\n byte_range = {\n 'start': sub_range_start,\n 'end': sub_range_start + int(splitted_byte_range[0]),\n }\n elif is_ad_fragment_start(line):\n ad_frag_next = True\n elif is_ad_fragment_end(line):\n ad_frag_next = False\n\n self._finish_frag_download(ctx)\n\n return True", "focal_method_lines": [59, 215], "in_stack": false, "globals": [], "type_context": "import re\nimport binascii\nfrom .fragment import FragmentFD\nfrom .external import FFmpegFD\nfrom ..compat import (\n compat_urllib_error,\n compat_urlparse,\n compat_struct_pack,\n)\nfrom ..utils import (\n parse_m3u8_attributes,\n update_url_query,\n)\n\n\n\nclass HlsFD(FragmentFD):\n\n FD_NAME = 'hlsnative'\n\n def real_download(self, filename, info_dict):\n man_url = info_dict['url']\n self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)\n\n urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))\n man_url = urlh.geturl()\n s = urlh.read().decode('utf-8', 'ignore')\n\n if not self.can_download(s, info_dict):\n if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'):\n self.report_error('pycrypto not found. Please install it.')\n return False\n self.report_warning(\n 'hlsnative has detected features it does not support, '\n 'extraction will be delegated to ffmpeg')\n fd = FFmpegFD(self.ydl, self.params)\n for ph in self._progress_hooks:\n fd.add_progress_hook(ph)\n return fd.real_download(filename, info_dict)\n\n def is_ad_fragment_start(s):\n return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s\n or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad'))\n\n def is_ad_fragment_end(s):\n return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s\n or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment'))\n\n media_frags = 0\n ad_frags = 0\n ad_frag_next = False\n for line in s.splitlines():\n line = line.strip()\n if not line:\n continue\n if line.startswith('#'):\n if is_ad_fragment_start(line):\n ad_frag_next = True\n elif is_ad_fragment_end(line):\n ad_frag_next = False\n continue\n if ad_frag_next:\n ad_frags += 1\n continue\n media_frags += 1\n\n ctx = {\n 'filename': filename,\n 'total_frags': media_frags,\n 'ad_frags': ad_frags,\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n test = self.params.get('test', False)\n\n extra_query = None\n extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')\n if extra_param_to_segment_url:\n extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)\n i = 0\n media_sequence = 0\n decrypt_info = {'METHOD': 'NONE'}\n byte_range = {}\n frag_index = 0\n ad_frag_next = False\n for line in s.splitlines():\n line = line.strip()\n if line:\n if not line.startswith('#'):\n if ad_frag_next:\n continue\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n frag_url = (\n line\n if re.match(r'^https?://', line)\n else compat_urlparse.urljoin(man_url, line))\n if extra_query:\n frag_url = update_url_query(frag_url, extra_query)\n count = 0\n headers = info_dict.get('http_headers', {})\n if byte_range:\n headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)\n while count <= fragment_retries:\n try:\n success, frag_content = self._download_fragment(\n ctx, frag_url, info_dict, headers)\n if not success:\n return False\n break\n except compat_urllib_error.HTTPError as err:\n # Unavailable (possibly temporary) fragments may be served.\n # First we try to retry then either skip or abort.\n # See https://github.com/ytdl-org/youtube-dl/issues/10165,\n # https://github.com/ytdl-org/youtube-dl/issues/10448).\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n if count > fragment_retries:\n if skip_unavailable_fragments:\n i += 1\n media_sequence += 1\n self.report_skip_fragment(frag_index)\n continue\n self.report_error(\n 'giving up after %s fragment retries' % fragment_retries)\n return False\n if decrypt_info['METHOD'] == 'AES-128':\n iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)\n decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(\n self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()\n # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block\n # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,\n # not what it decrypts to.\n if not test:\n frag_content = AES.new(\n decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)\n self._append_fragment(ctx, frag_content)\n # We only download the first fragment during the test\n if test:\n break\n i += 1\n media_sequence += 1\n elif line.startswith('#EXT-X-KEY'):\n decrypt_url = decrypt_info.get('URI')\n decrypt_info = parse_m3u8_attributes(line[11:])\n if decrypt_info['METHOD'] == 'AES-128':\n if 'IV' in decrypt_info:\n decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))\n if not re.match(r'^https?://', decrypt_info['URI']):\n decrypt_info['URI'] = compat_urlparse.urljoin(\n man_url, decrypt_info['URI'])\n if extra_query:\n decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)\n if decrypt_url != decrypt_info['URI']:\n decrypt_info['KEY'] = None\n elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):\n media_sequence = int(line[22:])\n elif line.startswith('#EXT-X-BYTERANGE'):\n splitted_byte_range = line[17:].split('@')\n sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']\n byte_range = {\n 'start': sub_range_start,\n 'end': sub_range_start + int(splitted_byte_range[0]),\n }\n elif is_ad_fragment_start(line):\n ad_frag_next = True\n elif is_ad_fragment_end(line):\n ad_frag_next = False\n\n self._finish_frag_download(ctx)\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 916, "project": "youtube_dl", "module": "youtube_dl.downloader.http", "class": "HttpFD", "method": "real_download", "focal_method_txt": " def real_download(self, filename, info_dict):\n url = info_dict['url']\n\n class DownloadContext(dict):\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n ctx = DownloadContext()\n ctx.filename = filename\n ctx.tmpfilename = self.temp_name(filename)\n ctx.stream = None\n\n # Do not include the Accept-Encoding header\n headers = {'Youtubedl-no-compression': 'True'}\n add_headers = info_dict.get('http_headers')\n if add_headers:\n headers.update(add_headers)\n\n is_test = self.params.get('test', False)\n chunk_size = self._TEST_FILE_SIZE if is_test else (\n info_dict.get('downloader_options', {}).get('http_chunk_size')\n or self.params.get('http_chunk_size') or 0)\n\n ctx.open_mode = 'wb'\n ctx.resume_len = 0\n ctx.data_len = None\n ctx.block_size = self.params.get('buffersize', 1024)\n ctx.start_time = time.time()\n ctx.chunk_size = None\n\n if self.params.get('continuedl', True):\n # Establish possible resume length\n if os.path.isfile(encodeFilename(ctx.tmpfilename)):\n ctx.resume_len = os.path.getsize(\n encodeFilename(ctx.tmpfilename))\n\n ctx.is_resume = ctx.resume_len > 0\n\n count = 0\n retries = self.params.get('retries', 0)\n\n class SucceedDownload(Exception):\n pass\n\n class RetryDownload(Exception):\n def __init__(self, source_error):\n self.source_error = source_error\n\n class NextFragment(Exception):\n pass\n\n def set_range(req, start, end):\n range_header = 'bytes=%d-' % start\n if end:\n range_header += compat_str(end)\n req.add_header('Range', range_header)\n\n def establish_connection():\n ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)\n if not is_test and chunk_size else chunk_size)\n if ctx.resume_len > 0:\n range_start = ctx.resume_len\n if ctx.is_resume:\n self.report_resuming_byte(ctx.resume_len)\n ctx.open_mode = 'ab'\n elif ctx.chunk_size > 0:\n range_start = 0\n else:\n range_start = None\n ctx.is_resume = False\n range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None\n if range_end and ctx.data_len is not None and range_end >= ctx.data_len:\n range_end = ctx.data_len - 1\n has_range = range_start is not None\n ctx.has_range = has_range\n request = sanitized_Request(url, None, headers)\n if has_range:\n set_range(request, range_start, range_end)\n # Establish connection\n try:\n try:\n ctx.data = self.ydl.urlopen(request)\n except (compat_urllib_error.URLError, ) as err:\n # reason may not be available, e.g. for urllib2.HTTPError on python 2.6\n reason = getattr(err, 'reason', None)\n if isinstance(reason, socket.timeout):\n raise RetryDownload(err)\n raise err\n # When trying to resume, Content-Range HTTP header of response has to be checked\n # to match the value of requested Range HTTP header. This is due to a webservers\n # that don't support resuming and serve a whole file with no Content-Range\n # set in response despite of requested Range (see\n # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)\n if has_range:\n content_range = ctx.data.headers.get('Content-Range')\n if content_range:\n content_range_m = re.search(r'bytes (\\d+)-(\\d+)?(?:/(\\d+))?', content_range)\n # Content-Range is present and matches requested Range, resume is possible\n if content_range_m:\n if range_start == int(content_range_m.group(1)):\n content_range_end = int_or_none(content_range_m.group(2))\n content_len = int_or_none(content_range_m.group(3))\n accept_content_len = (\n # Non-chunked download\n not ctx.chunk_size\n # Chunked download and requested piece or\n # its part is promised to be served\n or content_range_end == range_end\n or content_len < range_end)\n if accept_content_len:\n ctx.data_len = content_len\n return\n # Content-Range is either not present or invalid. Assuming remote webserver is\n # trying to send the whole file, resume is not possible, so wiping the local file\n # and performing entire redownload\n self.report_unable_to_resume()\n ctx.resume_len = 0\n ctx.open_mode = 'wb'\n ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))\n return\n except (compat_urllib_error.HTTPError, ) as err:\n if err.code == 416:\n # Unable to resume (requested range not satisfiable)\n try:\n # Open the connection again without the range header\n ctx.data = self.ydl.urlopen(\n sanitized_Request(url, None, headers))\n content_length = ctx.data.info()['Content-Length']\n except (compat_urllib_error.HTTPError, ) as err:\n if err.code < 500 or err.code >= 600:\n raise\n else:\n # Examine the reported length\n if (content_length is not None\n and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):\n # The file had already been fully downloaded.\n # Explanation to the above condition: in issue #175 it was revealed that\n # YouTube sometimes adds or removes a few bytes from the end of the file,\n # changing the file size slightly and causing problems for some users. So\n # I decided to implement a suggested change and consider the file\n # completely downloaded if the file size differs less than 100 bytes from\n # the one in the hard drive.\n self.report_file_already_downloaded(ctx.filename)\n self.try_rename(ctx.tmpfilename, ctx.filename)\n self._hook_progress({\n 'filename': ctx.filename,\n 'status': 'finished',\n 'downloaded_bytes': ctx.resume_len,\n 'total_bytes': ctx.resume_len,\n })\n raise SucceedDownload()\n else:\n # The length does not match, we start the download over\n self.report_unable_to_resume()\n ctx.resume_len = 0\n ctx.open_mode = 'wb'\n return\n elif err.code < 500 or err.code >= 600:\n # Unexpected HTTP error\n raise\n raise RetryDownload(err)\n except socket.error as err:\n if err.errno != errno.ECONNRESET:\n # Connection reset is no problem, just retry\n raise\n raise RetryDownload(err)\n\n def download():\n data_len = ctx.data.info().get('Content-length', None)\n\n # Range HTTP header may be ignored/unsupported by a webserver\n # (e.g. extractor/scivee.py, extractor/bambuser.py).\n # However, for a test we still would like to download just a piece of a file.\n # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control\n # block size when downloading a file.\n if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):\n data_len = self._TEST_FILE_SIZE\n\n if data_len is not None:\n data_len = int(data_len) + ctx.resume_len\n min_data_len = self.params.get('min_filesize')\n max_data_len = self.params.get('max_filesize')\n if min_data_len is not None and data_len < min_data_len:\n self.to_screen('\\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))\n return False\n if max_data_len is not None and data_len > max_data_len:\n self.to_screen('\\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))\n return False\n\n byte_counter = 0 + ctx.resume_len\n block_size = ctx.block_size\n start = time.time()\n\n # measure time over whole while-loop, so slow_down() and best_block_size() work together properly\n now = None # needed for slow_down() in the first loop run\n before = start # start measuring\n\n def retry(e):\n to_stdout = ctx.tmpfilename == '-'\n if ctx.stream is not None:\n if not to_stdout:\n ctx.stream.close()\n ctx.stream = None\n ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))\n raise RetryDownload(e)\n\n while True:\n try:\n # Download and write\n data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))\n # socket.timeout is a subclass of socket.error but may not have\n # errno set\n except socket.timeout as e:\n retry(e)\n except socket.error as e:\n # SSLError on python 2 (inherits socket.error) may have\n # no errno set but this error message\n if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out':\n retry(e)\n raise\n\n byte_counter += len(data_block)\n\n # exit loop when download is finished\n if len(data_block) == 0:\n break\n\n # Open destination file just in time\n if ctx.stream is None:\n try:\n ctx.stream, ctx.tmpfilename = sanitize_open(\n ctx.tmpfilename, ctx.open_mode)\n assert ctx.stream is not None\n ctx.filename = self.undo_temp_name(ctx.tmpfilename)\n self.report_destination(ctx.filename)\n except (OSError, IOError) as err:\n self.report_error('unable to open for writing: %s' % str(err))\n return False\n\n if self.params.get('xattr_set_filesize', False) and data_len is not None:\n try:\n write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))\n except (XAttrUnavailableError, XAttrMetadataError) as err:\n self.report_error('unable to set filesize xattr: %s' % str(err))\n\n try:\n ctx.stream.write(data_block)\n except (IOError, OSError) as err:\n self.to_stderr('\\n')\n self.report_error('unable to write data: %s' % str(err))\n return False\n\n # Apply rate limit\n self.slow_down(start, now, byte_counter - ctx.resume_len)\n\n # end measuring of one loop run\n now = time.time()\n after = now\n\n # Adjust block size\n if not self.params.get('noresizebuffer', False):\n block_size = self.best_block_size(after - before, len(data_block))\n\n before = after\n\n # Progress message\n speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)\n if ctx.data_len is None:\n eta = None\n else:\n eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)\n\n self._hook_progress({\n 'status': 'downloading',\n 'downloaded_bytes': byte_counter,\n 'total_bytes': ctx.data_len,\n 'tmpfilename': ctx.tmpfilename,\n 'filename': ctx.filename,\n 'eta': eta,\n 'speed': speed,\n 'elapsed': now - ctx.start_time,\n })\n\n if data_len is not None and byte_counter == data_len:\n break\n\n if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:\n ctx.resume_len = byte_counter\n # ctx.block_size = block_size\n raise NextFragment()\n\n if ctx.stream is None:\n self.to_stderr('\\n')\n self.report_error('Did not get any data blocks')\n return False\n if ctx.tmpfilename != '-':\n ctx.stream.close()\n\n if data_len is not None and byte_counter != data_len:\n err = ContentTooShortError(byte_counter, int(data_len))\n if count <= retries:\n retry(err)\n raise err\n\n self.try_rename(ctx.tmpfilename, ctx.filename)\n\n # Update file modification time\n if self.params.get('updatetime', True):\n info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))\n\n self._hook_progress({\n 'downloaded_bytes': byte_counter,\n 'total_bytes': byte_counter,\n 'filename': ctx.filename,\n 'status': 'finished',\n 'elapsed': time.time() - ctx.start_time,\n })\n\n return True\n\n while count <= retries:\n try:\n establish_connection()\n return download()\n except RetryDownload as e:\n count += 1\n if count <= retries:\n self.report_retry(e.source_error, count, retries)\n continue\n except NextFragment:\n continue\n except SucceedDownload:\n return True\n\n self.report_error('giving up after %s retries' % retries)\n return False", "focal_method_lines": [27, 363], "in_stack": false, "globals": [], "type_context": "import errno\nimport os\nimport socket\nimport time\nimport random\nimport re\nfrom .common import FileDownloader\nfrom ..compat import (\n compat_str,\n compat_urllib_error,\n)\nfrom ..utils import (\n ContentTooShortError,\n encodeFilename,\n int_or_none,\n sanitize_open,\n sanitized_Request,\n write_xattr,\n XAttrMetadataError,\n XAttrUnavailableError,\n)\n\n\n\nclass HttpFD(FileDownloader):\n\n def real_download(self, filename, info_dict):\n url = info_dict['url']\n\n class DownloadContext(dict):\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n ctx = DownloadContext()\n ctx.filename = filename\n ctx.tmpfilename = self.temp_name(filename)\n ctx.stream = None\n\n # Do not include the Accept-Encoding header\n headers = {'Youtubedl-no-compression': 'True'}\n add_headers = info_dict.get('http_headers')\n if add_headers:\n headers.update(add_headers)\n\n is_test = self.params.get('test', False)\n chunk_size = self._TEST_FILE_SIZE if is_test else (\n info_dict.get('downloader_options', {}).get('http_chunk_size')\n or self.params.get('http_chunk_size') or 0)\n\n ctx.open_mode = 'wb'\n ctx.resume_len = 0\n ctx.data_len = None\n ctx.block_size = self.params.get('buffersize', 1024)\n ctx.start_time = time.time()\n ctx.chunk_size = None\n\n if self.params.get('continuedl', True):\n # Establish possible resume length\n if os.path.isfile(encodeFilename(ctx.tmpfilename)):\n ctx.resume_len = os.path.getsize(\n encodeFilename(ctx.tmpfilename))\n\n ctx.is_resume = ctx.resume_len > 0\n\n count = 0\n retries = self.params.get('retries', 0)\n\n class SucceedDownload(Exception):\n pass\n\n class RetryDownload(Exception):\n def __init__(self, source_error):\n self.source_error = source_error\n\n class NextFragment(Exception):\n pass\n\n def set_range(req, start, end):\n range_header = 'bytes=%d-' % start\n if end:\n range_header += compat_str(end)\n req.add_header('Range', range_header)\n\n def establish_connection():\n ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)\n if not is_test and chunk_size else chunk_size)\n if ctx.resume_len > 0:\n range_start = ctx.resume_len\n if ctx.is_resume:\n self.report_resuming_byte(ctx.resume_len)\n ctx.open_mode = 'ab'\n elif ctx.chunk_size > 0:\n range_start = 0\n else:\n range_start = None\n ctx.is_resume = False\n range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None\n if range_end and ctx.data_len is not None and range_end >= ctx.data_len:\n range_end = ctx.data_len - 1\n has_range = range_start is not None\n ctx.has_range = has_range\n request = sanitized_Request(url, None, headers)\n if has_range:\n set_range(request, range_start, range_end)\n # Establish connection\n try:\n try:\n ctx.data = self.ydl.urlopen(request)\n except (compat_urllib_error.URLError, ) as err:\n # reason may not be available, e.g. for urllib2.HTTPError on python 2.6\n reason = getattr(err, 'reason', None)\n if isinstance(reason, socket.timeout):\n raise RetryDownload(err)\n raise err\n # When trying to resume, Content-Range HTTP header of response has to be checked\n # to match the value of requested Range HTTP header. This is due to a webservers\n # that don't support resuming and serve a whole file with no Content-Range\n # set in response despite of requested Range (see\n # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)\n if has_range:\n content_range = ctx.data.headers.get('Content-Range')\n if content_range:\n content_range_m = re.search(r'bytes (\\d+)-(\\d+)?(?:/(\\d+))?', content_range)\n # Content-Range is present and matches requested Range, resume is possible\n if content_range_m:\n if range_start == int(content_range_m.group(1)):\n content_range_end = int_or_none(content_range_m.group(2))\n content_len = int_or_none(content_range_m.group(3))\n accept_content_len = (\n # Non-chunked download\n not ctx.chunk_size\n # Chunked download and requested piece or\n # its part is promised to be served\n or content_range_end == range_end\n or content_len < range_end)\n if accept_content_len:\n ctx.data_len = content_len\n return\n # Content-Range is either not present or invalid. Assuming remote webserver is\n # trying to send the whole file, resume is not possible, so wiping the local file\n # and performing entire redownload\n self.report_unable_to_resume()\n ctx.resume_len = 0\n ctx.open_mode = 'wb'\n ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))\n return\n except (compat_urllib_error.HTTPError, ) as err:\n if err.code == 416:\n # Unable to resume (requested range not satisfiable)\n try:\n # Open the connection again without the range header\n ctx.data = self.ydl.urlopen(\n sanitized_Request(url, None, headers))\n content_length = ctx.data.info()['Content-Length']\n except (compat_urllib_error.HTTPError, ) as err:\n if err.code < 500 or err.code >= 600:\n raise\n else:\n # Examine the reported length\n if (content_length is not None\n and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):\n # The file had already been fully downloaded.\n # Explanation to the above condition: in issue #175 it was revealed that\n # YouTube sometimes adds or removes a few bytes from the end of the file,\n # changing the file size slightly and causing problems for some users. So\n # I decided to implement a suggested change and consider the file\n # completely downloaded if the file size differs less than 100 bytes from\n # the one in the hard drive.\n self.report_file_already_downloaded(ctx.filename)\n self.try_rename(ctx.tmpfilename, ctx.filename)\n self._hook_progress({\n 'filename': ctx.filename,\n 'status': 'finished',\n 'downloaded_bytes': ctx.resume_len,\n 'total_bytes': ctx.resume_len,\n })\n raise SucceedDownload()\n else:\n # The length does not match, we start the download over\n self.report_unable_to_resume()\n ctx.resume_len = 0\n ctx.open_mode = 'wb'\n return\n elif err.code < 500 or err.code >= 600:\n # Unexpected HTTP error\n raise\n raise RetryDownload(err)\n except socket.error as err:\n if err.errno != errno.ECONNRESET:\n # Connection reset is no problem, just retry\n raise\n raise RetryDownload(err)\n\n def download():\n data_len = ctx.data.info().get('Content-length', None)\n\n # Range HTTP header may be ignored/unsupported by a webserver\n # (e.g. extractor/scivee.py, extractor/bambuser.py).\n # However, for a test we still would like to download just a piece of a file.\n # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control\n # block size when downloading a file.\n if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):\n data_len = self._TEST_FILE_SIZE\n\n if data_len is not None:\n data_len = int(data_len) + ctx.resume_len\n min_data_len = self.params.get('min_filesize')\n max_data_len = self.params.get('max_filesize')\n if min_data_len is not None and data_len < min_data_len:\n self.to_screen('\\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))\n return False\n if max_data_len is not None and data_len > max_data_len:\n self.to_screen('\\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))\n return False\n\n byte_counter = 0 + ctx.resume_len\n block_size = ctx.block_size\n start = time.time()\n\n # measure time over whole while-loop, so slow_down() and best_block_size() work together properly\n now = None # needed for slow_down() in the first loop run\n before = start # start measuring\n\n def retry(e):\n to_stdout = ctx.tmpfilename == '-'\n if ctx.stream is not None:\n if not to_stdout:\n ctx.stream.close()\n ctx.stream = None\n ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))\n raise RetryDownload(e)\n\n while True:\n try:\n # Download and write\n data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))\n # socket.timeout is a subclass of socket.error but may not have\n # errno set\n except socket.timeout as e:\n retry(e)\n except socket.error as e:\n # SSLError on python 2 (inherits socket.error) may have\n # no errno set but this error message\n if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out':\n retry(e)\n raise\n\n byte_counter += len(data_block)\n\n # exit loop when download is finished\n if len(data_block) == 0:\n break\n\n # Open destination file just in time\n if ctx.stream is None:\n try:\n ctx.stream, ctx.tmpfilename = sanitize_open(\n ctx.tmpfilename, ctx.open_mode)\n assert ctx.stream is not None\n ctx.filename = self.undo_temp_name(ctx.tmpfilename)\n self.report_destination(ctx.filename)\n except (OSError, IOError) as err:\n self.report_error('unable to open for writing: %s' % str(err))\n return False\n\n if self.params.get('xattr_set_filesize', False) and data_len is not None:\n try:\n write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))\n except (XAttrUnavailableError, XAttrMetadataError) as err:\n self.report_error('unable to set filesize xattr: %s' % str(err))\n\n try:\n ctx.stream.write(data_block)\n except (IOError, OSError) as err:\n self.to_stderr('\\n')\n self.report_error('unable to write data: %s' % str(err))\n return False\n\n # Apply rate limit\n self.slow_down(start, now, byte_counter - ctx.resume_len)\n\n # end measuring of one loop run\n now = time.time()\n after = now\n\n # Adjust block size\n if not self.params.get('noresizebuffer', False):\n block_size = self.best_block_size(after - before, len(data_block))\n\n before = after\n\n # Progress message\n speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)\n if ctx.data_len is None:\n eta = None\n else:\n eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)\n\n self._hook_progress({\n 'status': 'downloading',\n 'downloaded_bytes': byte_counter,\n 'total_bytes': ctx.data_len,\n 'tmpfilename': ctx.tmpfilename,\n 'filename': ctx.filename,\n 'eta': eta,\n 'speed': speed,\n 'elapsed': now - ctx.start_time,\n })\n\n if data_len is not None and byte_counter == data_len:\n break\n\n if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:\n ctx.resume_len = byte_counter\n # ctx.block_size = block_size\n raise NextFragment()\n\n if ctx.stream is None:\n self.to_stderr('\\n')\n self.report_error('Did not get any data blocks')\n return False\n if ctx.tmpfilename != '-':\n ctx.stream.close()\n\n if data_len is not None and byte_counter != data_len:\n err = ContentTooShortError(byte_counter, int(data_len))\n if count <= retries:\n retry(err)\n raise err\n\n self.try_rename(ctx.tmpfilename, ctx.filename)\n\n # Update file modification time\n if self.params.get('updatetime', True):\n info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))\n\n self._hook_progress({\n 'downloaded_bytes': byte_counter,\n 'total_bytes': byte_counter,\n 'filename': ctx.filename,\n 'status': 'finished',\n 'elapsed': time.time() - ctx.start_time,\n })\n\n return True\n\n while count <= retries:\n try:\n establish_connection()\n return download()\n except RetryDownload as e:\n count += 1\n if count <= retries:\n self.report_retry(e.source_error, count, retries)\n continue\n except NextFragment:\n continue\n except SucceedDownload:\n return True\n\n self.report_error('giving up after %s retries' % retries)\n return False", "has_branch": true, "total_branches": 2} {"prompt_id": 917, "project": "youtube_dl", "module": "youtube_dl.downloader.ism", "class": "", "method": "write_piff_header", "focal_method_txt": "def write_piff_header(stream, params):\n track_id = params['track_id']\n fourcc = params['fourcc']\n duration = params['duration']\n timescale = params.get('timescale', 10000000)\n language = params.get('language', 'und')\n height = params.get('height', 0)\n width = params.get('width', 0)\n is_audio = width == 0 and height == 0\n creation_time = modification_time = int(time.time())\n\n ftyp_payload = b'isml' # major brand\n ftyp_payload += u32.pack(1) # minor version\n ftyp_payload += b'piff' + b'iso2' # compatible brands\n stream.write(box(b'ftyp', ftyp_payload)) # File Type Box\n\n mvhd_payload = u64.pack(creation_time)\n mvhd_payload += u64.pack(modification_time)\n mvhd_payload += u32.pack(timescale)\n mvhd_payload += u64.pack(duration)\n mvhd_payload += s1616.pack(1) # rate\n mvhd_payload += s88.pack(1) # volume\n mvhd_payload += u16.pack(0) # reserved\n mvhd_payload += u32.pack(0) * 2 # reserved\n mvhd_payload += unity_matrix\n mvhd_payload += u32.pack(0) * 6 # pre defined\n mvhd_payload += u32.pack(0xffffffff) # next track id\n moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box\n\n tkhd_payload = u64.pack(creation_time)\n tkhd_payload += u64.pack(modification_time)\n tkhd_payload += u32.pack(track_id) # track id\n tkhd_payload += u32.pack(0) # reserved\n tkhd_payload += u64.pack(duration)\n tkhd_payload += u32.pack(0) * 2 # reserved\n tkhd_payload += s16.pack(0) # layer\n tkhd_payload += s16.pack(0) # alternate group\n tkhd_payload += s88.pack(1 if is_audio else 0) # volume\n tkhd_payload += u16.pack(0) # reserved\n tkhd_payload += unity_matrix\n tkhd_payload += u1616.pack(width)\n tkhd_payload += u1616.pack(height)\n trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box\n\n mdhd_payload = u64.pack(creation_time)\n mdhd_payload += u64.pack(modification_time)\n mdhd_payload += u32.pack(timescale)\n mdhd_payload += u64.pack(duration)\n mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60))\n mdhd_payload += u16.pack(0) # pre defined\n mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box\n\n hdlr_payload = u32.pack(0) # pre defined\n hdlr_payload += b'soun' if is_audio else b'vide' # handler type\n hdlr_payload += u32.pack(0) * 3 # reserved\n hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\\0' # name\n mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box\n\n if is_audio:\n smhd_payload = s88.pack(0) # balance\n smhd_payload += u16.pack(0) # reserved\n media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header\n else:\n vmhd_payload = u16.pack(0) # graphics mode\n vmhd_payload += u16.pack(0) * 3 # opcolor\n media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header\n minf_payload = media_header_box\n\n dref_payload = u32.pack(1) # entry count\n dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box\n dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box\n minf_payload += box(b'dinf', dinf_payload) # Data Information Box\n\n stsd_payload = u32.pack(1) # entry count\n\n sample_entry_payload = u8.pack(0) * 6 # reserved\n sample_entry_payload += u16.pack(1) # data reference index\n if is_audio:\n sample_entry_payload += u32.pack(0) * 2 # reserved\n sample_entry_payload += u16.pack(params.get('channels', 2))\n sample_entry_payload += u16.pack(params.get('bits_per_sample', 16))\n sample_entry_payload += u16.pack(0) # pre defined\n sample_entry_payload += u16.pack(0) # reserved\n sample_entry_payload += u1616.pack(params['sampling_rate'])\n\n if fourcc == 'AACL':\n sample_entry_box = box(b'mp4a', sample_entry_payload)\n else:\n sample_entry_payload += u16.pack(0) # pre defined\n sample_entry_payload += u16.pack(0) # reserved\n sample_entry_payload += u32.pack(0) * 3 # pre defined\n sample_entry_payload += u16.pack(width)\n sample_entry_payload += u16.pack(height)\n sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi\n sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi\n sample_entry_payload += u32.pack(0) # reserved\n sample_entry_payload += u16.pack(1) # frame count\n sample_entry_payload += u8.pack(0) * 32 # compressor name\n sample_entry_payload += u16.pack(0x18) # depth\n sample_entry_payload += s16.pack(-1) # pre defined\n\n codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8'))\n if fourcc in ('H264', 'AVC1'):\n sps, pps = codec_private_data.split(u32.pack(1))[1:]\n avcc_payload = u8.pack(1) # configuration version\n avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication\n avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one\n avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001)\n avcc_payload += u16.pack(len(sps))\n avcc_payload += sps\n avcc_payload += u8.pack(1) # number of pps\n avcc_payload += u16.pack(len(pps))\n avcc_payload += pps\n sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record\n sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry\n stsd_payload += sample_entry_box\n\n stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box\n\n stts_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box\n\n stsc_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box\n\n stco_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box\n\n minf_payload += box(b'stbl', stbl_payload) # Sample Table Box\n\n mdia_payload += box(b'minf', minf_payload) # Media Information Box\n\n trak_payload += box(b'mdia', mdia_payload) # Media Box\n\n moov_payload += box(b'trak', trak_payload) # Track Box\n\n mehd_payload = u64.pack(duration)\n mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box\n\n trex_payload = u32.pack(track_id) # track id\n trex_payload += u32.pack(1) # default sample description index\n trex_payload += u32.pack(0) # default sample duration\n trex_payload += u32.pack(0) # default sample size\n trex_payload += u32.pack(0) # default sample flags\n mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box\n\n moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box\n stream.write(box(b'moov', moov_payload))", "focal_method_lines": [42, 189], "in_stack": false, "globals": ["u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED"], "type_context": "import time\nimport binascii\nimport io\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_Struct,\n compat_urllib_error,\n)\n\nu8 = compat_Struct('>B')\nu88 = compat_Struct('>Bx')\nu16 = compat_Struct('>H')\nu1616 = compat_Struct('>Hxx')\nu32 = compat_Struct('>I')\nu64 = compat_Struct('>Q')\ns88 = compat_Struct('>bx')\ns16 = compat_Struct('>h')\ns1616 = compat_Struct('>hxx')\ns32 = compat_Struct('>i')\nunity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000)\nTRACK_ENABLED = 0x1\nTRACK_IN_MOVIE = 0x2\nTRACK_IN_PREVIEW = 0x4\nSELF_CONTAINED = 0x1\n\ndef write_piff_header(stream, params):\n track_id = params['track_id']\n fourcc = params['fourcc']\n duration = params['duration']\n timescale = params.get('timescale', 10000000)\n language = params.get('language', 'und')\n height = params.get('height', 0)\n width = params.get('width', 0)\n is_audio = width == 0 and height == 0\n creation_time = modification_time = int(time.time())\n\n ftyp_payload = b'isml' # major brand\n ftyp_payload += u32.pack(1) # minor version\n ftyp_payload += b'piff' + b'iso2' # compatible brands\n stream.write(box(b'ftyp', ftyp_payload)) # File Type Box\n\n mvhd_payload = u64.pack(creation_time)\n mvhd_payload += u64.pack(modification_time)\n mvhd_payload += u32.pack(timescale)\n mvhd_payload += u64.pack(duration)\n mvhd_payload += s1616.pack(1) # rate\n mvhd_payload += s88.pack(1) # volume\n mvhd_payload += u16.pack(0) # reserved\n mvhd_payload += u32.pack(0) * 2 # reserved\n mvhd_payload += unity_matrix\n mvhd_payload += u32.pack(0) * 6 # pre defined\n mvhd_payload += u32.pack(0xffffffff) # next track id\n moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box\n\n tkhd_payload = u64.pack(creation_time)\n tkhd_payload += u64.pack(modification_time)\n tkhd_payload += u32.pack(track_id) # track id\n tkhd_payload += u32.pack(0) # reserved\n tkhd_payload += u64.pack(duration)\n tkhd_payload += u32.pack(0) * 2 # reserved\n tkhd_payload += s16.pack(0) # layer\n tkhd_payload += s16.pack(0) # alternate group\n tkhd_payload += s88.pack(1 if is_audio else 0) # volume\n tkhd_payload += u16.pack(0) # reserved\n tkhd_payload += unity_matrix\n tkhd_payload += u1616.pack(width)\n tkhd_payload += u1616.pack(height)\n trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box\n\n mdhd_payload = u64.pack(creation_time)\n mdhd_payload += u64.pack(modification_time)\n mdhd_payload += u32.pack(timescale)\n mdhd_payload += u64.pack(duration)\n mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60))\n mdhd_payload += u16.pack(0) # pre defined\n mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box\n\n hdlr_payload = u32.pack(0) # pre defined\n hdlr_payload += b'soun' if is_audio else b'vide' # handler type\n hdlr_payload += u32.pack(0) * 3 # reserved\n hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\\0' # name\n mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box\n\n if is_audio:\n smhd_payload = s88.pack(0) # balance\n smhd_payload += u16.pack(0) # reserved\n media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header\n else:\n vmhd_payload = u16.pack(0) # graphics mode\n vmhd_payload += u16.pack(0) * 3 # opcolor\n media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header\n minf_payload = media_header_box\n\n dref_payload = u32.pack(1) # entry count\n dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box\n dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box\n minf_payload += box(b'dinf', dinf_payload) # Data Information Box\n\n stsd_payload = u32.pack(1) # entry count\n\n sample_entry_payload = u8.pack(0) * 6 # reserved\n sample_entry_payload += u16.pack(1) # data reference index\n if is_audio:\n sample_entry_payload += u32.pack(0) * 2 # reserved\n sample_entry_payload += u16.pack(params.get('channels', 2))\n sample_entry_payload += u16.pack(params.get('bits_per_sample', 16))\n sample_entry_payload += u16.pack(0) # pre defined\n sample_entry_payload += u16.pack(0) # reserved\n sample_entry_payload += u1616.pack(params['sampling_rate'])\n\n if fourcc == 'AACL':\n sample_entry_box = box(b'mp4a', sample_entry_payload)\n else:\n sample_entry_payload += u16.pack(0) # pre defined\n sample_entry_payload += u16.pack(0) # reserved\n sample_entry_payload += u32.pack(0) * 3 # pre defined\n sample_entry_payload += u16.pack(width)\n sample_entry_payload += u16.pack(height)\n sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi\n sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi\n sample_entry_payload += u32.pack(0) # reserved\n sample_entry_payload += u16.pack(1) # frame count\n sample_entry_payload += u8.pack(0) * 32 # compressor name\n sample_entry_payload += u16.pack(0x18) # depth\n sample_entry_payload += s16.pack(-1) # pre defined\n\n codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8'))\n if fourcc in ('H264', 'AVC1'):\n sps, pps = codec_private_data.split(u32.pack(1))[1:]\n avcc_payload = u8.pack(1) # configuration version\n avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication\n avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one\n avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001)\n avcc_payload += u16.pack(len(sps))\n avcc_payload += sps\n avcc_payload += u8.pack(1) # number of pps\n avcc_payload += u16.pack(len(pps))\n avcc_payload += pps\n sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record\n sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry\n stsd_payload += sample_entry_box\n\n stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box\n\n stts_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box\n\n stsc_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box\n\n stco_payload = u32.pack(0) # entry count\n stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box\n\n minf_payload += box(b'stbl', stbl_payload) # Sample Table Box\n\n mdia_payload += box(b'minf', minf_payload) # Media Information Box\n\n trak_payload += box(b'mdia', mdia_payload) # Media Box\n\n moov_payload += box(b'trak', trak_payload) # Track Box\n\n mehd_payload = u64.pack(duration)\n mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box\n\n trex_payload = u32.pack(track_id) # track id\n trex_payload += u32.pack(1) # default sample description index\n trex_payload += u32.pack(0) # default sample duration\n trex_payload += u32.pack(0) # default sample size\n trex_payload += u32.pack(0) # default sample flags\n mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box\n\n moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box\n stream.write(box(b'moov', moov_payload))", "has_branch": true, "total_branches": 2} {"prompt_id": 918, "project": "youtube_dl", "module": "youtube_dl.downloader.ism", "class": "", "method": "extract_box_data", "focal_method_txt": "def extract_box_data(data, box_sequence):\n data_reader = io.BytesIO(data)\n while True:\n box_size = u32.unpack(data_reader.read(4))[0]\n box_type = data_reader.read(4)\n if box_type == box_sequence[0]:\n box_data = data_reader.read(box_size - 8)\n if len(box_sequence) == 1:\n return box_data\n return extract_box_data(box_data, box_sequence[1:])\n data_reader.seek(box_size - 8, 1)", "focal_method_lines": [192, 202], "in_stack": false, "globals": ["u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED"], "type_context": "import time\nimport binascii\nimport io\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_Struct,\n compat_urllib_error,\n)\n\nu8 = compat_Struct('>B')\nu88 = compat_Struct('>Bx')\nu16 = compat_Struct('>H')\nu1616 = compat_Struct('>Hxx')\nu32 = compat_Struct('>I')\nu64 = compat_Struct('>Q')\ns88 = compat_Struct('>bx')\ns16 = compat_Struct('>h')\ns1616 = compat_Struct('>hxx')\ns32 = compat_Struct('>i')\nunity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000)\nTRACK_ENABLED = 0x1\nTRACK_IN_MOVIE = 0x2\nTRACK_IN_PREVIEW = 0x4\nSELF_CONTAINED = 0x1\n\ndef extract_box_data(data, box_sequence):\n data_reader = io.BytesIO(data)\n while True:\n box_size = u32.unpack(data_reader.read(4))[0]\n box_type = data_reader.read(4)\n if box_type == box_sequence[0]:\n box_data = data_reader.read(box_size - 8)\n if len(box_sequence) == 1:\n return box_data\n return extract_box_data(box_data, box_sequence[1:])\n data_reader.seek(box_size - 8, 1)", "has_branch": true, "total_branches": 2} {"prompt_id": 919, "project": "youtube_dl", "module": "youtube_dl.downloader.ism", "class": "IsmFD", "method": "real_download", "focal_method_txt": " def real_download(self, filename, info_dict):\n segments = info_dict['fragments'][:1] if self.params.get(\n 'test', False) else info_dict['fragments']\n\n ctx = {\n 'filename': filename,\n 'total_frags': len(segments),\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n\n track_written = False\n frag_index = 0\n for i, segment in enumerate(segments):\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n count = 0\n while count <= fragment_retries:\n try:\n success, frag_content = self._download_fragment(ctx, segment['url'], info_dict)\n if not success:\n return False\n if not track_written:\n tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd'])\n info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0]\n write_piff_header(ctx['dest_stream'], info_dict['_download_params'])\n track_written = True\n self._append_fragment(ctx, frag_content)\n break\n except compat_urllib_error.HTTPError as err:\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n if count > fragment_retries:\n if skip_unavailable_fragments:\n self.report_skip_fragment(frag_index)\n continue\n self.report_error('giving up after %s fragment retries' % fragment_retries)\n return False\n\n self._finish_frag_download(ctx)\n\n return True", "focal_method_lines": [212, 258], "in_stack": false, "globals": ["u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED"], "type_context": "import time\nimport binascii\nimport io\nfrom .fragment import FragmentFD\nfrom ..compat import (\n compat_Struct,\n compat_urllib_error,\n)\n\nu8 = compat_Struct('>B')\nu88 = compat_Struct('>Bx')\nu16 = compat_Struct('>H')\nu1616 = compat_Struct('>Hxx')\nu32 = compat_Struct('>I')\nu64 = compat_Struct('>Q')\ns88 = compat_Struct('>bx')\ns16 = compat_Struct('>h')\ns1616 = compat_Struct('>hxx')\ns32 = compat_Struct('>i')\nunity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000)\nTRACK_ENABLED = 0x1\nTRACK_IN_MOVIE = 0x2\nTRACK_IN_PREVIEW = 0x4\nSELF_CONTAINED = 0x1\n\nclass IsmFD(FragmentFD):\n\n FD_NAME = 'ism'\n\n def real_download(self, filename, info_dict):\n segments = info_dict['fragments'][:1] if self.params.get(\n 'test', False) else info_dict['fragments']\n\n ctx = {\n 'filename': filename,\n 'total_frags': len(segments),\n }\n\n self._prepare_and_start_frag_download(ctx)\n\n fragment_retries = self.params.get('fragment_retries', 0)\n skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)\n\n track_written = False\n frag_index = 0\n for i, segment in enumerate(segments):\n frag_index += 1\n if frag_index <= ctx['fragment_index']:\n continue\n count = 0\n while count <= fragment_retries:\n try:\n success, frag_content = self._download_fragment(ctx, segment['url'], info_dict)\n if not success:\n return False\n if not track_written:\n tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd'])\n info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0]\n write_piff_header(ctx['dest_stream'], info_dict['_download_params'])\n track_written = True\n self._append_fragment(ctx, frag_content)\n break\n except compat_urllib_error.HTTPError as err:\n count += 1\n if count <= fragment_retries:\n self.report_retry_fragment(err, frag_index, count, fragment_retries)\n if count > fragment_retries:\n if skip_unavailable_fragments:\n self.report_skip_fragment(frag_index)\n continue\n self.report_error('giving up after %s fragment retries' % fragment_retries)\n return False\n\n self._finish_frag_download(ctx)\n\n return True", "has_branch": true, "total_branches": 2} {"prompt_id": 920, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "interpret_statement", "focal_method_txt": " def interpret_statement(self, stmt, local_vars, allow_recursion=100):\n if allow_recursion < 0:\n raise ExtractorError('Recursion limit reached')\n\n should_abort = False\n stmt = stmt.lstrip()\n stmt_m = re.match(r'var\\s', stmt)\n if stmt_m:\n expr = stmt[len(stmt_m.group(0)):]\n else:\n return_m = re.match(r'return(?:\\s+|$)', stmt)\n if return_m:\n expr = stmt[len(return_m.group(0)):]\n should_abort = True\n else:\n # Try interpreting it as an expression\n expr = stmt\n\n v = self.interpret_expression(expr, local_vars, allow_recursion)\n return v, should_abort", "focal_method_lines": [37, 56], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def interpret_statement(self, stmt, local_vars, allow_recursion=100):\n if allow_recursion < 0:\n raise ExtractorError('Recursion limit reached')\n\n should_abort = False\n stmt = stmt.lstrip()\n stmt_m = re.match(r'var\\s', stmt)\n if stmt_m:\n expr = stmt[len(stmt_m.group(0)):]\n else:\n return_m = re.match(r'return(?:\\s+|$)', stmt)\n if return_m:\n expr = stmt[len(return_m.group(0)):]\n should_abort = True\n else:\n # Try interpreting it as an expression\n expr = stmt\n\n v = self.interpret_expression(expr, local_vars, allow_recursion)\n return v, should_abort", "has_branch": true, "total_branches": 2} {"prompt_id": 921, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "interpret_expression", "focal_method_txt": " def interpret_expression(self, expr, local_vars, allow_recursion):\n expr = expr.strip()\n if expr == '': # Empty expression\n return None\n\n if expr.startswith('('):\n parens_count = 0\n for m in re.finditer(r'[()]', expr):\n if m.group(0) == '(':\n parens_count += 1\n else:\n parens_count -= 1\n if parens_count == 0:\n sub_expr = expr[1:m.start()]\n sub_result = self.interpret_expression(\n sub_expr, local_vars, allow_recursion)\n remaining_expr = expr[m.end():].strip()\n if not remaining_expr:\n return sub_result\n else:\n expr = json.dumps(sub_result) + remaining_expr\n break\n else:\n raise ExtractorError('Premature end of parens in %r' % expr)\n\n for op, opfunc in _ASSIGN_OPERATORS:\n m = re.match(r'''(?x)\n (?P%s)(?:\\[(?P[^\\]]+?)\\])?\n \\s*%s\n (?P.*)$''' % (_NAME_RE, re.escape(op)), expr)\n if not m:\n continue\n right_val = self.interpret_expression(\n m.group('expr'), local_vars, allow_recursion - 1)\n\n if m.groupdict().get('index'):\n lvar = local_vars[m.group('out')]\n idx = self.interpret_expression(\n m.group('index'), local_vars, allow_recursion)\n assert isinstance(idx, int)\n cur = lvar[idx]\n val = opfunc(cur, right_val)\n lvar[idx] = val\n return val\n else:\n cur = local_vars.get(m.group('out'))\n val = opfunc(cur, right_val)\n local_vars[m.group('out')] = val\n return val\n\n if expr.isdigit():\n return int(expr)\n\n var_m = re.match(\n r'(?!if|return|true|false)(?P%s)$' % _NAME_RE,\n expr)\n if var_m:\n return local_vars[var_m.group('name')]\n\n try:\n return json.loads(expr)\n except ValueError:\n pass\n\n m = re.match(\n r'(?P%s)\\[(?P.+)\\]$' % _NAME_RE, expr)\n if m:\n val = local_vars[m.group('in')]\n idx = self.interpret_expression(\n m.group('idx'), local_vars, allow_recursion - 1)\n return val[idx]\n\n m = re.match(\n r'(?P%s)(?:\\.(?P[^(]+)|\\[(?P[^]]+)\\])\\s*(?:\\(+(?P[^()]*)\\))?$' % _NAME_RE,\n expr)\n if m:\n variable = m.group('var')\n member = remove_quotes(m.group('member') or m.group('member2'))\n arg_str = m.group('args')\n\n if variable in local_vars:\n obj = local_vars[variable]\n else:\n if variable not in self._objects:\n self._objects[variable] = self.extract_object(variable)\n obj = self._objects[variable]\n\n if arg_str is None:\n # Member access\n if member == 'length':\n return len(obj)\n return obj[member]\n\n assert expr.endswith(')')\n # Function call\n if arg_str == '':\n argvals = tuple()\n else:\n argvals = tuple([\n self.interpret_expression(v, local_vars, allow_recursion)\n for v in arg_str.split(',')])\n\n if member == 'split':\n assert argvals == ('',)\n return list(obj)\n if member == 'join':\n assert len(argvals) == 1\n return argvals[0].join(obj)\n if member == 'reverse':\n assert len(argvals) == 0\n obj.reverse()\n return obj\n if member == 'slice':\n assert len(argvals) == 1\n return obj[argvals[0]:]\n if member == 'splice':\n assert isinstance(obj, list)\n index, howMany = argvals\n res = []\n for i in range(index, min(index + howMany, len(obj))):\n res.append(obj.pop(index))\n return res\n\n return obj[member](argvals)\n\n for op, opfunc in _OPERATORS:\n m = re.match(r'(?P.+?)%s(?P.+)' % re.escape(op), expr)\n if not m:\n continue\n x, abort = self.interpret_statement(\n m.group('x'), local_vars, allow_recursion - 1)\n if abort:\n raise ExtractorError(\n 'Premature left-side return of %s in %r' % (op, expr))\n y, abort = self.interpret_statement(\n m.group('y'), local_vars, allow_recursion - 1)\n if abort:\n raise ExtractorError(\n 'Premature right-side return of %s in %r' % (op, expr))\n return opfunc(x, y)\n\n m = re.match(\n r'^(?P%s)\\((?P[a-zA-Z0-9_$,]*)\\)$' % _NAME_RE, expr)\n if m:\n fname = m.group('func')\n argvals = tuple([\n int(v) if v.isdigit() else local_vars[v]\n for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple()\n if fname not in self._functions:\n self._functions[fname] = self.extract_function(fname)\n return self._functions[fname](argvals)\n\n raise ExtractorError('Unsupported JS expression %r' % expr)", "focal_method_lines": [58, 210], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def interpret_expression(self, expr, local_vars, allow_recursion):\n expr = expr.strip()\n if expr == '': # Empty expression\n return None\n\n if expr.startswith('('):\n parens_count = 0\n for m in re.finditer(r'[()]', expr):\n if m.group(0) == '(':\n parens_count += 1\n else:\n parens_count -= 1\n if parens_count == 0:\n sub_expr = expr[1:m.start()]\n sub_result = self.interpret_expression(\n sub_expr, local_vars, allow_recursion)\n remaining_expr = expr[m.end():].strip()\n if not remaining_expr:\n return sub_result\n else:\n expr = json.dumps(sub_result) + remaining_expr\n break\n else:\n raise ExtractorError('Premature end of parens in %r' % expr)\n\n for op, opfunc in _ASSIGN_OPERATORS:\n m = re.match(r'''(?x)\n (?P%s)(?:\\[(?P[^\\]]+?)\\])?\n \\s*%s\n (?P.*)$''' % (_NAME_RE, re.escape(op)), expr)\n if not m:\n continue\n right_val = self.interpret_expression(\n m.group('expr'), local_vars, allow_recursion - 1)\n\n if m.groupdict().get('index'):\n lvar = local_vars[m.group('out')]\n idx = self.interpret_expression(\n m.group('index'), local_vars, allow_recursion)\n assert isinstance(idx, int)\n cur = lvar[idx]\n val = opfunc(cur, right_val)\n lvar[idx] = val\n return val\n else:\n cur = local_vars.get(m.group('out'))\n val = opfunc(cur, right_val)\n local_vars[m.group('out')] = val\n return val\n\n if expr.isdigit():\n return int(expr)\n\n var_m = re.match(\n r'(?!if|return|true|false)(?P%s)$' % _NAME_RE,\n expr)\n if var_m:\n return local_vars[var_m.group('name')]\n\n try:\n return json.loads(expr)\n except ValueError:\n pass\n\n m = re.match(\n r'(?P%s)\\[(?P.+)\\]$' % _NAME_RE, expr)\n if m:\n val = local_vars[m.group('in')]\n idx = self.interpret_expression(\n m.group('idx'), local_vars, allow_recursion - 1)\n return val[idx]\n\n m = re.match(\n r'(?P%s)(?:\\.(?P[^(]+)|\\[(?P[^]]+)\\])\\s*(?:\\(+(?P[^()]*)\\))?$' % _NAME_RE,\n expr)\n if m:\n variable = m.group('var')\n member = remove_quotes(m.group('member') or m.group('member2'))\n arg_str = m.group('args')\n\n if variable in local_vars:\n obj = local_vars[variable]\n else:\n if variable not in self._objects:\n self._objects[variable] = self.extract_object(variable)\n obj = self._objects[variable]\n\n if arg_str is None:\n # Member access\n if member == 'length':\n return len(obj)\n return obj[member]\n\n assert expr.endswith(')')\n # Function call\n if arg_str == '':\n argvals = tuple()\n else:\n argvals = tuple([\n self.interpret_expression(v, local_vars, allow_recursion)\n for v in arg_str.split(',')])\n\n if member == 'split':\n assert argvals == ('',)\n return list(obj)\n if member == 'join':\n assert len(argvals) == 1\n return argvals[0].join(obj)\n if member == 'reverse':\n assert len(argvals) == 0\n obj.reverse()\n return obj\n if member == 'slice':\n assert len(argvals) == 1\n return obj[argvals[0]:]\n if member == 'splice':\n assert isinstance(obj, list)\n index, howMany = argvals\n res = []\n for i in range(index, min(index + howMany, len(obj))):\n res.append(obj.pop(index))\n return res\n\n return obj[member](argvals)\n\n for op, opfunc in _OPERATORS:\n m = re.match(r'(?P.+?)%s(?P.+)' % re.escape(op), expr)\n if not m:\n continue\n x, abort = self.interpret_statement(\n m.group('x'), local_vars, allow_recursion - 1)\n if abort:\n raise ExtractorError(\n 'Premature left-side return of %s in %r' % (op, expr))\n y, abort = self.interpret_statement(\n m.group('y'), local_vars, allow_recursion - 1)\n if abort:\n raise ExtractorError(\n 'Premature right-side return of %s in %r' % (op, expr))\n return opfunc(x, y)\n\n m = re.match(\n r'^(?P%s)\\((?P[a-zA-Z0-9_$,]*)\\)$' % _NAME_RE, expr)\n if m:\n fname = m.group('func')\n argvals = tuple([\n int(v) if v.isdigit() else local_vars[v]\n for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple()\n if fname not in self._functions:\n self._functions[fname] = self.extract_function(fname)\n return self._functions[fname](argvals)\n\n raise ExtractorError('Unsupported JS expression %r' % expr)", "has_branch": true, "total_branches": 2} {"prompt_id": 922, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "extract_object", "focal_method_txt": " def extract_object(self, objname):\n _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|\"[a-zA-Z$0-9]+\"|'[a-zA-Z$0-9]+')'''\n obj = {}\n obj_m = re.search(\n r'''(?x)\n (?(%s\\s*:\\s*function\\s*\\(.*?\\)\\s*{.*?}(?:,\\s*)?)*)\n }\\s*;\n ''' % (re.escape(objname), _FUNC_NAME_RE),\n self.code)\n fields = obj_m.group('fields')\n # Currently, it only supports function definitions\n fields_m = re.finditer(\n r'''(?x)\n (?P%s)\\s*:\\s*function\\s*\\((?P[a-z,]+)\\){(?P[^}]+)}\n ''' % _FUNC_NAME_RE,\n fields)\n for f in fields_m:\n argnames = f.group('args').split(',')\n obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))\n\n return obj", "focal_method_lines": [212, 233], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def extract_object(self, objname):\n _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|\"[a-zA-Z$0-9]+\"|'[a-zA-Z$0-9]+')'''\n obj = {}\n obj_m = re.search(\n r'''(?x)\n (?(%s\\s*:\\s*function\\s*\\(.*?\\)\\s*{.*?}(?:,\\s*)?)*)\n }\\s*;\n ''' % (re.escape(objname), _FUNC_NAME_RE),\n self.code)\n fields = obj_m.group('fields')\n # Currently, it only supports function definitions\n fields_m = re.finditer(\n r'''(?x)\n (?P%s)\\s*:\\s*function\\s*\\((?P[a-z,]+)\\){(?P[^}]+)}\n ''' % _FUNC_NAME_RE,\n fields)\n for f in fields_m:\n argnames = f.group('args').split(',')\n obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))\n\n return obj", "has_branch": true, "total_branches": 2} {"prompt_id": 923, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "extract_function", "focal_method_txt": " def extract_function(self, funcname):\n func_m = re.search(\n r'''(?x)\n (?:function\\s+%s|[{;,]\\s*%s\\s*=\\s*function|var\\s+%s\\s*=\\s*function)\\s*\n \\((?P[^)]*)\\)\\s*\n \\{(?P[^}]+)\\}''' % (\n re.escape(funcname), re.escape(funcname), re.escape(funcname)),\n self.code)\n if func_m is None:\n raise ExtractorError('Could not find JS function %r' % funcname)\n argnames = func_m.group('args').split(',')\n\n return self.build_function(argnames, func_m.group('code'))", "focal_method_lines": [235, 247], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def extract_function(self, funcname):\n func_m = re.search(\n r'''(?x)\n (?:function\\s+%s|[{;,]\\s*%s\\s*=\\s*function|var\\s+%s\\s*=\\s*function)\\s*\n \\((?P[^)]*)\\)\\s*\n \\{(?P[^}]+)\\}''' % (\n re.escape(funcname), re.escape(funcname), re.escape(funcname)),\n self.code)\n if func_m is None:\n raise ExtractorError('Could not find JS function %r' % funcname)\n argnames = func_m.group('args').split(',')\n\n return self.build_function(argnames, func_m.group('code'))", "has_branch": true, "total_branches": 2} {"prompt_id": 924, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "call_function", "focal_method_txt": " def call_function(self, funcname, *args):\n f = self.extract_function(funcname)\n return f(args)", "focal_method_lines": [249, 251], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def call_function(self, funcname, *args):\n f = self.extract_function(funcname)\n return f(args)", "has_branch": false, "total_branches": 0} {"prompt_id": 925, "project": "youtube_dl", "module": "youtube_dl.jsinterp", "class": "JSInterpreter", "method": "build_function", "focal_method_txt": " def build_function(self, argnames, code):\n def resf(args):\n local_vars = dict(zip(argnames, args))\n for stmt in code.split(';'):\n res, abort = self.interpret_statement(stmt, local_vars)\n if abort:\n break\n return res\n return resf", "focal_method_lines": [253, 261], "in_stack": false, "globals": ["_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE"], "type_context": "import json\nimport operator\nimport re\nfrom .utils import (\n ExtractorError,\n remove_quotes,\n)\n\n_OPERATORS = [\n ('|', operator.or_),\n ('^', operator.xor),\n ('&', operator.and_),\n ('>>', operator.rshift),\n ('<<', operator.lshift),\n ('-', operator.sub),\n ('+', operator.add),\n ('%', operator.mod),\n ('/', operator.truediv),\n ('*', operator.mul),\n]\n_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]\n_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'\n\nclass JSInterpreter(object):\n\n def __init__(self, code, objects=None):\n if objects is None:\n objects = {}\n self.code = code\n self._functions = {}\n self._objects = objects\n\n def build_function(self, argnames, code):\n def resf(args):\n local_vars = dict(zip(argnames, args))\n for stmt in code.split(';'):\n res, abort = self.interpret_statement(stmt, local_vars)\n if abort:\n break\n return res\n return resf", "has_branch": true, "total_branches": 2} {"prompt_id": 926, "project": "youtube_dl", "module": "youtube_dl.options", "class": "", "method": "parseOpts", "focal_method_txt": "def parseOpts(overrideArguments=None):\n def _readOptions(filename_bytes, default=[]):\n try:\n optionf = open(filename_bytes)\n except IOError:\n return default # silently skip if file is not present\n try:\n # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56\n contents = optionf.read()\n if sys.version_info < (3,):\n contents = contents.decode(preferredencoding())\n res = compat_shlex_split(contents, comments=True)\n finally:\n optionf.close()\n return res\n\n def _readUserConf():\n xdg_config_home = compat_getenv('XDG_CONFIG_HOME')\n if xdg_config_home:\n userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')\n if not os.path.isfile(userConfFile):\n userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')\n else:\n userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')\n if not os.path.isfile(userConfFile):\n userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')\n userConf = _readOptions(userConfFile, None)\n\n if userConf is None:\n appdata_dir = compat_getenv('appdata')\n if appdata_dir:\n userConf = _readOptions(\n os.path.join(appdata_dir, 'youtube-dl', 'config'),\n default=None)\n if userConf is None:\n userConf = _readOptions(\n os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),\n default=None)\n\n if userConf is None:\n userConf = _readOptions(\n os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),\n default=None)\n if userConf is None:\n userConf = _readOptions(\n os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),\n default=None)\n\n if userConf is None:\n userConf = []\n\n return userConf\n\n def _format_option_string(option):\n ''' ('-o', '--option') -> -o, --format METAVAR'''\n\n opts = []\n\n if option._short_opts:\n opts.append(option._short_opts[0])\n if option._long_opts:\n opts.append(option._long_opts[0])\n if len(opts) > 1:\n opts.insert(1, ', ')\n\n if option.takes_value():\n opts.append(' %s' % option.metavar)\n\n return ''.join(opts)\n\n def _comma_separated_values_options_callback(option, opt_str, value, parser):\n setattr(parser.values, option.dest, value.split(','))\n\n # No need to wrap help messages if we're on a wide console\n columns = compat_get_terminal_size().columns\n max_width = columns if columns else 80\n max_help_position = 80\n\n fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)\n fmt.format_option_strings = _format_option_string\n\n kw = {\n 'version': __version__,\n 'formatter': fmt,\n 'usage': '%prog [OPTIONS] URL [URL...]',\n 'conflict_handler': 'resolve',\n }\n\n parser = optparse.OptionParser(**compat_kwargs(kw))\n\n general = optparse.OptionGroup(parser, 'General Options')\n general.add_option(\n '-h', '--help',\n action='help',\n help='Print this help text and exit')\n general.add_option(\n '--version',\n action='version',\n help='Print program version and exit')\n general.add_option(\n '-U', '--update',\n action='store_true', dest='update_self',\n help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')\n general.add_option(\n '-i', '--ignore-errors',\n action='store_true', dest='ignoreerrors', default=False,\n help='Continue on download errors, for example to skip unavailable videos in a playlist')\n general.add_option(\n '--abort-on-error',\n action='store_false', dest='ignoreerrors',\n help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')\n general.add_option(\n '--dump-user-agent',\n action='store_true', dest='dump_user_agent', default=False,\n help='Display the current browser identification')\n general.add_option(\n '--list-extractors',\n action='store_true', dest='list_extractors', default=False,\n help='List all supported extractors')\n general.add_option(\n '--extractor-descriptions',\n action='store_true', dest='list_extractor_descriptions', default=False,\n help='Output descriptions of all supported extractors')\n general.add_option(\n '--force-generic-extractor',\n action='store_true', dest='force_generic_extractor', default=False,\n help='Force extraction to use the generic extractor')\n general.add_option(\n '--default-search',\n dest='default_search', metavar='PREFIX',\n help='Use this prefix for unqualified URLs. For example \"gvsearch2:\" downloads two videos from google videos for youtube-dl \"large apple\". Use the value \"auto\" to let youtube-dl guess (\"auto_warning\" to emit a warning when guessing). \"error\" just throws an error. The default value \"fixup_error\" repairs broken URLs, but emits an error if this is not possible instead of searching.')\n general.add_option(\n '--ignore-config',\n action='store_true',\n help='Do not read configuration files. '\n 'When given in the global configuration file /etc/youtube-dl.conf: '\n 'Do not read the user configuration in ~/.config/youtube-dl/config '\n '(%APPDATA%/youtube-dl/config.txt on Windows)')\n general.add_option(\n '--config-location',\n dest='config_location', metavar='PATH',\n help='Location of the configuration file; either the path to the config or its containing directory.')\n general.add_option(\n '--flat-playlist',\n action='store_const', dest='extract_flat', const='in_playlist',\n default=False,\n help='Do not extract the videos of a playlist, only list them.')\n general.add_option(\n '--mark-watched',\n action='store_true', dest='mark_watched', default=False,\n help='Mark videos watched (YouTube only)')\n general.add_option(\n '--no-mark-watched',\n action='store_false', dest='mark_watched', default=False,\n help='Do not mark videos watched (YouTube only)')\n general.add_option(\n '--no-color', '--no-colors',\n action='store_true', dest='no_color',\n default=False,\n help='Do not emit color codes in output')\n\n network = optparse.OptionGroup(parser, 'Network Options')\n network.add_option(\n '--proxy', dest='proxy',\n default=None, metavar='URL',\n help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable '\n 'SOCKS proxy, specify a proper scheme. For example '\n 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy \"\") '\n 'for direct connection')\n network.add_option(\n '--socket-timeout',\n dest='socket_timeout', type=float, default=None, metavar='SECONDS',\n help='Time to wait before giving up, in seconds')\n network.add_option(\n '--source-address',\n metavar='IP', dest='source_address', default=None,\n help='Client-side IP address to bind to',\n )\n network.add_option(\n '-4', '--force-ipv4',\n action='store_const', const='0.0.0.0', dest='source_address',\n help='Make all connections via IPv4',\n )\n network.add_option(\n '-6', '--force-ipv6',\n action='store_const', const='::', dest='source_address',\n help='Make all connections via IPv6',\n )\n\n geo = optparse.OptionGroup(parser, 'Geo Restriction')\n geo.add_option(\n '--geo-verification-proxy',\n dest='geo_verification_proxy', default=None, metavar='URL',\n help='Use this proxy to verify the IP address for some geo-restricted sites. '\n 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.')\n geo.add_option(\n '--cn-verification-proxy',\n dest='cn_verification_proxy', default=None, metavar='URL',\n help=optparse.SUPPRESS_HELP)\n geo.add_option(\n '--geo-bypass',\n action='store_true', dest='geo_bypass', default=True,\n help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')\n geo.add_option(\n '--no-geo-bypass',\n action='store_false', dest='geo_bypass', default=True,\n help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')\n geo.add_option(\n '--geo-bypass-country', metavar='CODE',\n dest='geo_bypass_country', default=None,\n help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')\n geo.add_option(\n '--geo-bypass-ip-block', metavar='IP_BLOCK',\n dest='geo_bypass_ip_block', default=None,\n help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')\n\n selection = optparse.OptionGroup(parser, 'Video Selection')\n selection.add_option(\n '--playlist-start',\n dest='playliststart', metavar='NUMBER', default=1, type=int,\n help='Playlist video to start at (default is %default)')\n selection.add_option(\n '--playlist-end',\n dest='playlistend', metavar='NUMBER', default=None, type=int,\n help='Playlist video to end at (default is last)')\n selection.add_option(\n '--playlist-items',\n dest='playlist_items', metavar='ITEM_SPEC', default=None,\n help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: \"--playlist-items 1,2,5,8\" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: \"--playlist-items 1-3,7,10-13\", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.')\n selection.add_option(\n '--match-title',\n dest='matchtitle', metavar='REGEX',\n help='Download only matching titles (regex or caseless sub-string)')\n selection.add_option(\n '--reject-title',\n dest='rejecttitle', metavar='REGEX',\n help='Skip download for matching titles (regex or caseless sub-string)')\n selection.add_option(\n '--max-downloads',\n dest='max_downloads', metavar='NUMBER', type=int, default=None,\n help='Abort after downloading NUMBER files')\n selection.add_option(\n '--min-filesize',\n metavar='SIZE', dest='min_filesize', default=None,\n help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')\n selection.add_option(\n '--max-filesize',\n metavar='SIZE', dest='max_filesize', default=None,\n help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')\n selection.add_option(\n '--date',\n metavar='DATE', dest='date', default=None,\n help='Download only videos uploaded in this date')\n selection.add_option(\n '--datebefore',\n metavar='DATE', dest='datebefore', default=None,\n help='Download only videos uploaded on or before this date (i.e. inclusive)')\n selection.add_option(\n '--dateafter',\n metavar='DATE', dest='dateafter', default=None,\n help='Download only videos uploaded on or after this date (i.e. inclusive)')\n selection.add_option(\n '--min-views',\n metavar='COUNT', dest='min_views', default=None, type=int,\n help='Do not download any videos with less than COUNT views')\n selection.add_option(\n '--max-views',\n metavar='COUNT', dest='max_views', default=None, type=int,\n help='Do not download any videos with more than COUNT views')\n selection.add_option(\n '--match-filter',\n metavar='FILTER', dest='match_filter', default=None,\n help=(\n 'Generic video filter. '\n 'Specify any key (see the \"OUTPUT TEMPLATE\" for a list of available keys) to '\n 'match if the key is present, '\n '!key to check if the key is not present, '\n 'key > NUMBER (like \"comment_count > 12\", also works with '\n '>=, <, <=, !=, =) to compare against a number, '\n 'key = \\'LITERAL\\' (like \"uploader = \\'Mike Smith\\'\", also works with !=) '\n 'to match against a string literal '\n 'and & to require multiple matches. '\n 'Values which are not known are excluded unless you '\n 'put a question mark (?) after the operator. '\n 'For example, to only match videos that have been liked more than '\n '100 times and disliked less than 50 times (or the dislike '\n 'functionality is not available at the given service), but who '\n 'also have a description, use --match-filter '\n '\"like_count > 100 & dislike_count .+?) - (?P.+)\"')\n postproc.add_option(\n '--xattrs',\n action='store_true', dest='xattrs', default=False,\n help='Write metadata to the video file\\'s xattrs (using dublin core and xdg standards)')\n postproc.add_option(\n '--fixup',\n metavar='POLICY', dest='fixup', default='detect_or_warn',\n help='Automatically correct known faults of the file. '\n 'One of never (do nothing), warn (only emit a warning), '\n 'detect_or_warn (the default; fix file if we can, warn otherwise)')\n postproc.add_option(\n '--prefer-avconv',\n action='store_false', dest='prefer_ffmpeg',\n help='Prefer avconv over ffmpeg for running the postprocessors')\n postproc.add_option(\n '--prefer-ffmpeg',\n action='store_true', dest='prefer_ffmpeg',\n help='Prefer ffmpeg over avconv for running the postprocessors (default)')\n postproc.add_option(\n '--ffmpeg-location', '--avconv-location', metavar='PATH',\n dest='ffmpeg_location',\n help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')\n postproc.add_option(\n '--exec',\n metavar='CMD', dest='exec_cmd',\n help='Execute a command on the file after downloading and post-processing, similar to find\\'s -exec syntax. Example: --exec \\'adb push {} /sdcard/Music/ && rm {}\\'')\n postproc.add_option(\n '--convert-subs', '--convert-subtitles',\n metavar='FORMAT', dest='convertsubtitles', default=None,\n help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')\n\n parser.add_option_group(general)\n parser.add_option_group(network)\n parser.add_option_group(geo)\n parser.add_option_group(selection)\n parser.add_option_group(downloader)\n parser.add_option_group(filesystem)\n parser.add_option_group(thumbnail)\n parser.add_option_group(verbosity)\n parser.add_option_group(workarounds)\n parser.add_option_group(video_format)\n parser.add_option_group(subtitles)\n parser.add_option_group(authentication)\n parser.add_option_group(adobe_pass)\n parser.add_option_group(postproc)\n\n if overrideArguments is not None:\n opts, args = parser.parse_args(overrideArguments)\n if opts.verbose:\n write_string('[debug] Override config: ' + repr(overrideArguments) + '\\n')\n else:\n def compat_conf(conf):\n if sys.version_info < (3,):\n return [a.decode(preferredencoding(), 'replace') for a in conf]\n return conf\n\n command_line_conf = compat_conf(sys.argv[1:])\n opts, args = parser.parse_args(command_line_conf)\n\n system_conf = user_conf = custom_conf = []\n\n if '--config-location' in command_line_conf:\n location = compat_expanduser(opts.config_location)\n if os.path.isdir(location):\n location = os.path.join(location, 'youtube-dl.conf')\n if not os.path.exists(location):\n parser.error('config-location %s does not exist.' % location)\n custom_conf = _readOptions(location)\n elif '--ignore-config' in command_line_conf:\n pass\n else:\n system_conf = _readOptions('/etc/youtube-dl.conf')\n if '--ignore-config' not in system_conf:\n user_conf = _readUserConf()\n\n argv = system_conf + user_conf + custom_conf + command_line_conf\n opts, args = parser.parse_args(argv)\n if opts.verbose:\n for conf_label, conf in (\n ('System config', system_conf),\n ('User config', user_conf),\n ('Custom config', custom_conf),\n ('Command-line args', command_line_conf)):\n write_string('[debug] %s: %s\\n' % (conf_label, repr(_hide_login_info(conf))))\n\n return parser, opts, args", "focal_method_lines": [40, 919], "in_stack": false, "globals": [], "type_context": "import os.path\nimport optparse\nimport re\nimport sys\nfrom .downloader.external import list_external_downloaders\nfrom .compat import (\n compat_expanduser,\n compat_get_terminal_size,\n compat_getenv,\n compat_kwargs,\n compat_shlex_split,\n)\nfrom .utils import (\n preferredencoding,\n write_string,\n)\nfrom .version import __version__\n\n\n\ndef parseOpts(overrideArguments=None):\n def _readOptions(filename_bytes, default=[]):\n try:\n optionf = open(filename_bytes)\n except IOError:\n return default # silently skip if file is not present\n try:\n # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56\n contents = optionf.read()\n if sys.version_info < (3,):\n contents = contents.decode(preferredencoding())\n res = compat_shlex_split(contents, comments=True)\n finally:\n optionf.close()\n return res\n\n def _readUserConf():\n xdg_config_home = compat_getenv('XDG_CONFIG_HOME')\n if xdg_config_home:\n userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')\n if not os.path.isfile(userConfFile):\n userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')\n else:\n userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')\n if not os.path.isfile(userConfFile):\n userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')\n userConf = _readOptions(userConfFile, None)\n\n if userConf is None:\n appdata_dir = compat_getenv('appdata')\n if appdata_dir:\n userConf = _readOptions(\n os.path.join(appdata_dir, 'youtube-dl', 'config'),\n default=None)\n if userConf is None:\n userConf = _readOptions(\n os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),\n default=None)\n\n if userConf is None:\n userConf = _readOptions(\n os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),\n default=None)\n if userConf is None:\n userConf = _readOptions(\n os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),\n default=None)\n\n if userConf is None:\n userConf = []\n\n return userConf\n\n def _format_option_string(option):\n ''' ('-o', '--option') -> -o, --format METAVAR'''\n\n opts = []\n\n if option._short_opts:\n opts.append(option._short_opts[0])\n if option._long_opts:\n opts.append(option._long_opts[0])\n if len(opts) > 1:\n opts.insert(1, ', ')\n\n if option.takes_value():\n opts.append(' %s' % option.metavar)\n\n return ''.join(opts)\n\n def _comma_separated_values_options_callback(option, opt_str, value, parser):\n setattr(parser.values, option.dest, value.split(','))\n\n # No need to wrap help messages if we're on a wide console\n columns = compat_get_terminal_size().columns\n max_width = columns if columns else 80\n max_help_position = 80\n\n fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)\n fmt.format_option_strings = _format_option_string\n\n kw = {\n 'version': __version__,\n 'formatter': fmt,\n 'usage': '%prog [OPTIONS] URL [URL...]',\n 'conflict_handler': 'resolve',\n }\n\n parser = optparse.OptionParser(**compat_kwargs(kw))\n\n general = optparse.OptionGroup(parser, 'General Options')\n general.add_option(\n '-h', '--help',\n action='help',\n help='Print this help text and exit')\n general.add_option(\n '--version',\n action='version',\n help='Print program version and exit')\n general.add_option(\n '-U', '--update',\n action='store_true', dest='update_self',\n help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')\n general.add_option(\n '-i', '--ignore-errors',\n action='store_true', dest='ignoreerrors', default=False,\n help='Continue on download errors, for example to skip unavailable videos in a playlist')\n general.add_option(\n '--abort-on-error',\n action='store_false', dest='ignoreerrors',\n help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')\n general.add_option(\n '--dump-user-agent',\n action='store_true', dest='dump_user_agent', default=False,\n help='Display the current browser identification')\n general.add_option(\n '--list-extractors',\n action='store_true', dest='list_extractors', default=False,\n help='List all supported extractors')\n general.add_option(\n '--extractor-descriptions',\n action='store_true', dest='list_extractor_descriptions', default=False,\n help='Output descriptions of all supported extractors')\n general.add_option(\n '--force-generic-extractor',\n action='store_true', dest='force_generic_extractor', default=False,\n help='Force extraction to use the generic extractor')\n general.add_option(\n '--default-search',\n dest='default_search', metavar='PREFIX',\n help='Use this prefix for unqualified URLs. For example \"gvsearch2:\" downloads two videos from google videos for youtube-dl \"large apple\". Use the value \"auto\" to let youtube-dl guess (\"auto_warning\" to emit a warning when guessing). \"error\" just throws an error. The default value \"fixup_error\" repairs broken URLs, but emits an error if this is not possible instead of searching.')\n general.add_option(\n '--ignore-config',\n action='store_true',\n help='Do not read configuration files. '\n 'When given in the global configuration file /etc/youtube-dl.conf: '\n 'Do not read the user configuration in ~/.config/youtube-dl/config '\n '(%APPDATA%/youtube-dl/config.txt on Windows)')\n general.add_option(\n '--config-location',\n dest='config_location', metavar='PATH',\n help='Location of the configuration file; either the path to the config or its containing directory.')\n general.add_option(\n '--flat-playlist',\n action='store_const', dest='extract_flat', const='in_playlist',\n default=False,\n help='Do not extract the videos of a playlist, only list them.')\n general.add_option(\n '--mark-watched',\n action='store_true', dest='mark_watched', default=False,\n help='Mark videos watched (YouTube only)')\n general.add_option(\n '--no-mark-watched',\n action='store_false', dest='mark_watched', default=False,\n help='Do not mark videos watched (YouTube only)')\n general.add_option(\n '--no-color', '--no-colors',\n action='store_true', dest='no_color',\n default=False,\n help='Do not emit color codes in output')\n\n network = optparse.OptionGroup(parser, 'Network Options')\n network.add_option(\n '--proxy', dest='proxy',\n default=None, metavar='URL',\n help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable '\n 'SOCKS proxy, specify a proper scheme. For example '\n 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy \"\") '\n 'for direct connection')\n network.add_option(\n '--socket-timeout',\n dest='socket_timeout', type=float, default=None, metavar='SECONDS',\n help='Time to wait before giving up, in seconds')\n network.add_option(\n '--source-address',\n metavar='IP', dest='source_address', default=None,\n help='Client-side IP address to bind to',\n )\n network.add_option(\n '-4', '--force-ipv4',\n action='store_const', const='0.0.0.0', dest='source_address',\n help='Make all connections via IPv4',\n )\n network.add_option(\n '-6', '--force-ipv6',\n action='store_const', const='::', dest='source_address',\n help='Make all connections via IPv6',\n )\n\n geo = optparse.OptionGroup(parser, 'Geo Restriction')\n geo.add_option(\n '--geo-verification-proxy',\n dest='geo_verification_proxy', default=None, metavar='URL',\n help='Use this proxy to verify the IP address for some geo-restricted sites. '\n 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.')\n geo.add_option(\n '--cn-verification-proxy',\n dest='cn_verification_proxy', default=None, metavar='URL',\n help=optparse.SUPPRESS_HELP)\n geo.add_option(\n '--geo-bypass',\n action='store_true', dest='geo_bypass', default=True,\n help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')\n geo.add_option(\n '--no-geo-bypass',\n action='store_false', dest='geo_bypass', default=True,\n help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')\n geo.add_option(\n '--geo-bypass-country', metavar='CODE',\n dest='geo_bypass_country', default=None,\n help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')\n geo.add_option(\n '--geo-bypass-ip-block', metavar='IP_BLOCK',\n dest='geo_bypass_ip_block', default=None,\n help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')\n\n selection = optparse.OptionGroup(parser, 'Video Selection')\n selection.add_option(\n '--playlist-start',\n dest='playliststart', metavar='NUMBER', default=1, type=int,\n help='Playlist video to start at (default is %default)')\n selection.add_option(\n '--playlist-end',\n dest='playlistend', metavar='NUMBER', default=None, type=int,\n help='Playlist video to end at (default is last)')\n selection.add_option(\n '--playlist-items',\n dest='playlist_items', metavar='ITEM_SPEC', default=None,\n help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: \"--playlist-items 1,2,5,8\" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: \"--playlist-items 1-3,7,10-13\", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.')\n selection.add_option(\n '--match-title',\n dest='matchtitle', metavar='REGEX',\n help='Download only matching titles (regex or caseless sub-string)')\n selection.add_option(\n '--reject-title',\n dest='rejecttitle', metavar='REGEX',\n help='Skip download for matching titles (regex or caseless sub-string)')\n selection.add_option(\n '--max-downloads',\n dest='max_downloads', metavar='NUMBER', type=int, default=None,\n help='Abort after downloading NUMBER files')\n selection.add_option(\n '--min-filesize',\n metavar='SIZE', dest='min_filesize', default=None,\n help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')\n selection.add_option(\n '--max-filesize',\n metavar='SIZE', dest='max_filesize', default=None,\n help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')\n selection.add_option(\n '--date',\n metavar='DATE', dest='date', default=None,\n help='Download only videos uploaded in this date')\n selection.add_option(\n '--datebefore',\n metavar='DATE', dest='datebefore', default=None,\n help='Download only videos uploaded on or before this date (i.e. inclusive)')\n selection.add_option(\n '--dateafter',\n metavar='DATE', dest='dateafter', default=None,\n help='Download only videos uploaded on or after this date (i.e. inclusive)')\n selection.add_option(\n '--min-views',\n metavar='COUNT', dest='min_views', default=None, type=int,\n help='Do not download any videos with less than COUNT views')\n selection.add_option(\n '--max-views',\n metavar='COUNT', dest='max_views', default=None, type=int,\n help='Do not download any videos with more than COUNT views')\n selection.add_option(\n '--match-filter',\n metavar='FILTER', dest='match_filter', default=None,\n help=(\n 'Generic video filter. '\n 'Specify any key (see the \"OUTPUT TEMPLATE\" for a list of available keys) to '\n 'match if the key is present, '\n '!key to check if the key is not present, '\n 'key > NUMBER (like \"comment_count > 12\", also works with '\n '>=, <, <=, !=, =) to compare against a number, '\n 'key = \\'LITERAL\\' (like \"uploader = \\'Mike Smith\\'\", also works with !=) '\n 'to match against a string literal '\n 'and & to require multiple matches. '\n 'Values which are not known are excluded unless you '\n 'put a question mark (?) after the operator. '\n 'For example, to only match videos that have been liked more than '\n '100 times and disliked less than 50 times (or the dislike '\n 'functionality is not available at the given service), but who '\n 'also have a description, use --match-filter '\n '\"like_count > 100 & dislike_count <? 50 & description\" .'\n ))\n selection.add_option(\n '--no-playlist',\n action='store_true', dest='noplaylist', default=False,\n help='Download only the video, if the URL refers to a video and a playlist.')\n selection.add_option(\n '--yes-playlist',\n action='store_false', dest='noplaylist', default=False,\n help='Download the playlist, if the URL refers to a video and a playlist.')\n selection.add_option(\n '--age-limit',\n metavar='YEARS', dest='age_limit', default=None, type=int,\n help='Download only videos suitable for the given age')\n selection.add_option(\n '--download-archive', metavar='FILE',\n dest='download_archive',\n help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')\n selection.add_option(\n '--include-ads',\n dest='include_ads', action='store_true',\n help='Download advertisements as well (experimental)')\n\n authentication = optparse.OptionGroup(parser, 'Authentication Options')\n authentication.add_option(\n '-u', '--username',\n dest='username', metavar='USERNAME',\n help='Login with this account ID')\n authentication.add_option(\n '-p', '--password',\n dest='password', metavar='PASSWORD',\n help='Account password. If this option is left out, youtube-dl will ask interactively.')\n authentication.add_option(\n '-2', '--twofactor',\n dest='twofactor', metavar='TWOFACTOR',\n help='Two-factor authentication code')\n authentication.add_option(\n '-n', '--netrc',\n action='store_true', dest='usenetrc', default=False,\n help='Use .netrc authentication data')\n authentication.add_option(\n '--video-password',\n dest='videopassword', metavar='PASSWORD',\n help='Video password (vimeo, youku)')\n\n adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')\n adobe_pass.add_option(\n '--ap-mso',\n dest='ap_mso', metavar='MSO',\n help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')\n adobe_pass.add_option(\n '--ap-username',\n dest='ap_username', metavar='USERNAME',\n help='Multiple-system operator account login')\n adobe_pass.add_option(\n '--ap-password',\n dest='ap_password', metavar='PASSWORD',\n help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.')\n adobe_pass.add_option(\n '--ap-list-mso',\n action='store_true', dest='ap_list_mso', default=False,\n help='List all supported multiple-system operators')\n\n video_format = optparse.OptionGroup(parser, 'Video Format Options')\n video_format.add_option(\n '-f', '--format',\n action='store', dest='format', metavar='FORMAT', default=None,\n help='Video format code, see the \"FORMAT SELECTION\" for all the info')\n video_format.add_option(\n '--all-formats',\n action='store_const', dest='format', const='all',\n help='Download all available video formats')\n video_format.add_option(\n '--prefer-free-formats',\n action='store_true', dest='prefer_free_formats', default=False,\n help='Prefer free video formats unless a specific one is requested')\n video_format.add_option(\n '-F', '--list-formats',\n action='store_true', dest='listformats',\n help='List all available formats of requested videos')\n video_format.add_option(\n '--youtube-include-dash-manifest',\n action='store_true', dest='youtube_include_dash_manifest', default=True,\n help=optparse.SUPPRESS_HELP)\n video_format.add_option(\n '--youtube-skip-dash-manifest',\n action='store_false', dest='youtube_include_dash_manifest',\n help='Do not download the DASH manifests and related data on YouTube videos')\n video_format.add_option(\n '--merge-output-format',\n action='store', dest='merge_output_format', metavar='FORMAT', default=None,\n help=(\n 'If a merge is required (e.g. bestvideo+bestaudio), '\n 'output to given container format. One of mkv, mp4, ogg, webm, flv. '\n 'Ignored if no merge is required'))\n\n subtitles = optparse.OptionGroup(parser, 'Subtitle Options')\n subtitles.add_option(\n '--write-sub', '--write-srt',\n action='store_true', dest='writesubtitles', default=False,\n help='Write subtitle file')\n subtitles.add_option(\n '--write-auto-sub', '--write-automatic-sub',\n action='store_true', dest='writeautomaticsub', default=False,\n help='Write automatically generated subtitle file (YouTube only)')\n subtitles.add_option(\n '--all-subs',\n action='store_true', dest='allsubtitles', default=False,\n help='Download all the available subtitles of the video')\n subtitles.add_option(\n '--list-subs',\n action='store_true', dest='listsubtitles', default=False,\n help='List all available subtitles for the video')\n subtitles.add_option(\n '--sub-format',\n action='store', dest='subtitlesformat', metavar='FORMAT', default='best',\n help='Subtitle format, accepts formats preference, for example: \"srt\" or \"ass/srt/best\"')\n subtitles.add_option(\n '--sub-lang', '--sub-langs', '--srt-lang',\n action='callback', dest='subtitleslangs', metavar='LANGS', type='str',\n default=[], callback=_comma_separated_values_options_callback,\n help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')\n\n downloader = optparse.OptionGroup(parser, 'Download Options')\n downloader.add_option(\n '-r', '--limit-rate', '--rate-limit',\n dest='ratelimit', metavar='RATE',\n help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')\n downloader.add_option(\n '-R', '--retries',\n dest='retries', metavar='RETRIES', default=10,\n help='Number of retries (default is %default), or \"infinite\".')\n downloader.add_option(\n '--fragment-retries',\n dest='fragment_retries', metavar='RETRIES', default=10,\n help='Number of retries for a fragment (default is %default), or \"infinite\" (DASH, hlsnative and ISM)')\n downloader.add_option(\n '--skip-unavailable-fragments',\n action='store_true', dest='skip_unavailable_fragments', default=True,\n help='Skip unavailable fragments (DASH, hlsnative and ISM)')\n downloader.add_option(\n '--abort-on-unavailable-fragment',\n action='store_false', dest='skip_unavailable_fragments',\n help='Abort downloading when some fragment is not available')\n downloader.add_option(\n '--keep-fragments',\n action='store_true', dest='keep_fragments', default=False,\n help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default')\n downloader.add_option(\n '--buffer-size',\n dest='buffersize', metavar='SIZE', default='1024',\n help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')\n downloader.add_option(\n '--no-resize-buffer',\n action='store_true', dest='noresizebuffer', default=False,\n help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')\n downloader.add_option(\n '--http-chunk-size',\n dest='http_chunk_size', metavar='SIZE', default=None,\n help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '\n 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)')\n downloader.add_option(\n '--test',\n action='store_true', dest='test', default=False,\n help=optparse.SUPPRESS_HELP)\n downloader.add_option(\n '--playlist-reverse',\n action='store_true',\n help='Download playlist videos in reverse order')\n downloader.add_option(\n '--playlist-random',\n action='store_true',\n help='Download playlist videos in random order')\n downloader.add_option(\n '--xattr-set-filesize',\n dest='xattr_set_filesize', action='store_true',\n help='Set file xattribute ytdl.filesize with expected file size')\n downloader.add_option(\n '--hls-prefer-native',\n dest='hls_prefer_native', action='store_true', default=None,\n help='Use the native HLS downloader instead of ffmpeg')\n downloader.add_option(\n '--hls-prefer-ffmpeg',\n dest='hls_prefer_native', action='store_false', default=None,\n help='Use ffmpeg instead of the native HLS downloader')\n downloader.add_option(\n '--hls-use-mpegts',\n dest='hls_use_mpegts', action='store_true',\n help='Use the mpegts container for HLS videos, allowing to play the '\n 'video while downloading (some players may not be able to play it)')\n downloader.add_option(\n '--external-downloader',\n dest='external_downloader', metavar='COMMAND',\n help='Use the specified external downloader. '\n 'Currently supports %s' % ','.join(list_external_downloaders()))\n downloader.add_option(\n '--external-downloader-args',\n dest='external_downloader_args', metavar='ARGS',\n help='Give these arguments to the external downloader')\n\n workarounds = optparse.OptionGroup(parser, 'Workarounds')\n workarounds.add_option(\n '--encoding',\n dest='encoding', metavar='ENCODING',\n help='Force the specified encoding (experimental)')\n workarounds.add_option(\n '--no-check-certificate',\n action='store_true', dest='no_check_certificate', default=False,\n help='Suppress HTTPS certificate validation')\n workarounds.add_option(\n '--prefer-insecure',\n '--prefer-unsecure', action='store_true', dest='prefer_insecure',\n help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')\n workarounds.add_option(\n '--user-agent',\n metavar='UA', dest='user_agent',\n help='Specify a custom user agent')\n workarounds.add_option(\n '--referer',\n metavar='URL', dest='referer', default=None,\n help='Specify a custom referer, use if the video access is restricted to one domain',\n )\n workarounds.add_option(\n '--add-header',\n metavar='FIELD:VALUE', dest='headers', action='append',\n help='Specify a custom HTTP header and its value, separated by a colon \\':\\'. You can use this option multiple times',\n )\n workarounds.add_option(\n '--bidi-workaround',\n dest='bidi_workaround', action='store_true',\n help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')\n workarounds.add_option(\n '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',\n dest='sleep_interval', type=float,\n help=(\n 'Number of seconds to sleep before each download when used alone '\n 'or a lower bound of a range for randomized sleep before each download '\n '(minimum possible number of seconds to sleep) when used along with '\n '--max-sleep-interval.'))\n workarounds.add_option(\n '--max-sleep-interval', metavar='SECONDS',\n dest='max_sleep_interval', type=float,\n help=(\n 'Upper bound of a range for randomized sleep before each download '\n '(maximum possible number of seconds to sleep). Must only be used '\n 'along with --min-sleep-interval.'))\n\n verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')\n verbosity.add_option(\n '-q', '--quiet',\n action='store_true', dest='quiet', default=False,\n help='Activate quiet mode')\n verbosity.add_option(\n '--no-warnings',\n dest='no_warnings', action='store_true', default=False,\n help='Ignore warnings')\n verbosity.add_option(\n '-s', '--simulate',\n action='store_true', dest='simulate', default=False,\n help='Do not download the video and do not write anything to disk')\n verbosity.add_option(\n '--skip-download',\n action='store_true', dest='skip_download', default=False,\n help='Do not download the video')\n verbosity.add_option(\n '-g', '--get-url',\n action='store_true', dest='geturl', default=False,\n help='Simulate, quiet but print URL')\n verbosity.add_option(\n '-e', '--get-title',\n action='store_true', dest='gettitle', default=False,\n help='Simulate, quiet but print title')\n verbosity.add_option(\n '--get-id',\n action='store_true', dest='getid', default=False,\n help='Simulate, quiet but print id')\n verbosity.add_option(\n '--get-thumbnail',\n action='store_true', dest='getthumbnail', default=False,\n help='Simulate, quiet but print thumbnail URL')\n verbosity.add_option(\n '--get-description',\n action='store_true', dest='getdescription', default=False,\n help='Simulate, quiet but print video description')\n verbosity.add_option(\n '--get-duration',\n action='store_true', dest='getduration', default=False,\n help='Simulate, quiet but print video length')\n verbosity.add_option(\n '--get-filename',\n action='store_true', dest='getfilename', default=False,\n help='Simulate, quiet but print output filename')\n verbosity.add_option(\n '--get-format',\n action='store_true', dest='getformat', default=False,\n help='Simulate, quiet but print output format')\n verbosity.add_option(\n '-j', '--dump-json',\n action='store_true', dest='dumpjson', default=False,\n help='Simulate, quiet but print JSON information. See the \"OUTPUT TEMPLATE\" for a description of available keys.')\n verbosity.add_option(\n '-J', '--dump-single-json',\n action='store_true', dest='dump_single_json', default=False,\n help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.')\n verbosity.add_option(\n '--print-json',\n action='store_true', dest='print_json', default=False,\n help='Be quiet and print the video information as JSON (video is still being downloaded).',\n )\n verbosity.add_option(\n '--newline',\n action='store_true', dest='progress_with_newline', default=False,\n help='Output progress bar as new lines')\n verbosity.add_option(\n '--no-progress',\n action='store_true', dest='noprogress', default=False,\n help='Do not print progress bar')\n verbosity.add_option(\n '--console-title',\n action='store_true', dest='consoletitle', default=False,\n help='Display progress in console titlebar')\n verbosity.add_option(\n '-v', '--verbose',\n action='store_true', dest='verbose', default=False,\n help='Print various debugging information')\n verbosity.add_option(\n '--dump-pages', '--dump-intermediate-pages',\n action='store_true', dest='dump_intermediate_pages', default=False,\n help='Print downloaded pages encoded using base64 to debug problems (very verbose)')\n verbosity.add_option(\n '--write-pages',\n action='store_true', dest='write_pages', default=False,\n help='Write downloaded intermediary pages to files in the current directory to debug problems')\n verbosity.add_option(\n '--youtube-print-sig-code',\n action='store_true', dest='youtube_print_sig_code', default=False,\n help=optparse.SUPPRESS_HELP)\n verbosity.add_option(\n '--print-traffic', '--dump-headers',\n dest='debug_printtraffic', action='store_true', default=False,\n help='Display sent and read HTTP traffic')\n verbosity.add_option(\n '-C', '--call-home',\n dest='call_home', action='store_true', default=False,\n help='Contact the youtube-dl server for debugging')\n verbosity.add_option(\n '--no-call-home',\n dest='call_home', action='store_false', default=False,\n help='Do NOT contact the youtube-dl server for debugging')\n\n filesystem = optparse.OptionGroup(parser, 'Filesystem Options')\n filesystem.add_option(\n '-a', '--batch-file',\n dest='batchfile', metavar='FILE',\n help=\"File containing URLs to download ('-' for stdin), one URL per line. \"\n \"Lines starting with '#', ';' or ']' are considered as comments and ignored.\")\n filesystem.add_option(\n '--id', default=False,\n action='store_true', dest='useid', help='Use only video ID in file name')\n filesystem.add_option(\n '-o', '--output',\n dest='outtmpl', metavar='TEMPLATE',\n help=('Output filename template, see the \"OUTPUT TEMPLATE\" for all the info'))\n filesystem.add_option(\n '--output-na-placeholder',\n dest='outtmpl_na_placeholder', metavar='PLACEHOLDER', default='NA',\n help=('Placeholder value for unavailable meta fields in output filename template (default is \"%default\")'))\n filesystem.add_option(\n '--autonumber-size',\n dest='autonumber_size', metavar='NUMBER', type=int,\n help=optparse.SUPPRESS_HELP)\n filesystem.add_option(\n '--autonumber-start',\n dest='autonumber_start', metavar='NUMBER', default=1, type=int,\n help='Specify the start value for %(autonumber)s (default is %default)')\n filesystem.add_option(\n '--restrict-filenames',\n action='store_true', dest='restrictfilenames', default=False,\n help='Restrict filenames to only ASCII characters, and avoid \"&\" and spaces in filenames')\n filesystem.add_option(\n '-A', '--auto-number',\n action='store_true', dest='autonumber', default=False,\n help=optparse.SUPPRESS_HELP)\n filesystem.add_option(\n '-t', '--title',\n action='store_true', dest='usetitle', default=False,\n help=optparse.SUPPRESS_HELP)\n filesystem.add_option(\n '-l', '--literal', default=False,\n action='store_true', dest='usetitle',\n help=optparse.SUPPRESS_HELP)\n filesystem.add_option(\n '-w', '--no-overwrites',\n action='store_true', dest='nooverwrites', default=False,\n help='Do not overwrite files')\n filesystem.add_option(\n '-c', '--continue',\n action='store_true', dest='continue_dl', default=True,\n help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')\n filesystem.add_option(\n '--no-continue',\n action='store_false', dest='continue_dl',\n help='Do not resume partially downloaded files (restart from beginning)')\n filesystem.add_option(\n '--no-part',\n action='store_true', dest='nopart', default=False,\n help='Do not use .part files - write directly into output file')\n filesystem.add_option(\n '--no-mtime',\n action='store_false', dest='updatetime', default=True,\n help='Do not use the Last-modified header to set the file modification time')\n filesystem.add_option(\n '--write-description',\n action='store_true', dest='writedescription', default=False,\n help='Write video description to a .description file')\n filesystem.add_option(\n '--write-info-json',\n action='store_true', dest='writeinfojson', default=False,\n help='Write video metadata to a .info.json file')\n filesystem.add_option(\n '--write-annotations',\n action='store_true', dest='writeannotations', default=False,\n help='Write video annotations to a .annotations.xml file')\n filesystem.add_option(\n '--load-info-json', '--load-info',\n dest='load_info_filename', metavar='FILE',\n help='JSON file containing the video information (created with the \"--write-info-json\" option)')\n filesystem.add_option(\n '--cookies',\n dest='cookiefile', metavar='FILE',\n help='File to read cookies from and dump cookie jar in')\n filesystem.add_option(\n '--cache-dir', dest='cachedir', default=None, metavar='DIR',\n help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.')\n filesystem.add_option(\n '--no-cache-dir', action='store_const', const=False, dest='cachedir',\n help='Disable filesystem caching')\n filesystem.add_option(\n '--rm-cache-dir',\n action='store_true', dest='rm_cachedir',\n help='Delete all filesystem cache files')\n\n thumbnail = optparse.OptionGroup(parser, 'Thumbnail Options')\n thumbnail.add_option(\n '--write-thumbnail',\n action='store_true', dest='writethumbnail', default=False,\n help='Write thumbnail image to disk')\n thumbnail.add_option(\n '--write-all-thumbnails',\n action='store_true', dest='write_all_thumbnails', default=False,\n help='Write all thumbnail image formats to disk')\n thumbnail.add_option(\n '--list-thumbnails',\n action='store_true', dest='list_thumbnails', default=False,\n help='Simulate and list all available thumbnail formats')\n\n postproc = optparse.OptionGroup(parser, 'Post-processing Options')\n postproc.add_option(\n '-x', '--extract-audio',\n action='store_true', dest='extractaudio', default=False,\n help='Convert video files to audio-only files (requires ffmpeg/avconv and ffprobe/avprobe)')\n postproc.add_option(\n '--audio-format', metavar='FORMAT', dest='audioformat', default='best',\n help='Specify audio format: \"best\", \"aac\", \"flac\", \"mp3\", \"m4a\", \"opus\", \"vorbis\", or \"wav\"; \"%default\" by default; No effect without -x')\n postproc.add_option(\n '--audio-quality', metavar='QUALITY',\n dest='audioquality', default='5',\n help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')\n postproc.add_option(\n '--recode-video',\n metavar='FORMAT', dest='recodevideo', default=None,\n help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')\n postproc.add_option(\n '--postprocessor-args',\n dest='postprocessor_args', metavar='ARGS',\n help='Give these arguments to the postprocessor')\n postproc.add_option(\n '-k', '--keep-video',\n action='store_true', dest='keepvideo', default=False,\n help='Keep the video file on disk after the post-processing; the video is erased by default')\n postproc.add_option(\n '--no-post-overwrites',\n action='store_true', dest='nopostoverwrites', default=False,\n help='Do not overwrite post-processed files; the post-processed files are overwritten by default')\n postproc.add_option(\n '--embed-subs',\n action='store_true', dest='embedsubtitles', default=False,\n help='Embed subtitles in the video (only for mp4, webm and mkv videos)')\n postproc.add_option(\n '--embed-thumbnail',\n action='store_true', dest='embedthumbnail', default=False,\n help='Embed thumbnail in the audio as cover art')\n postproc.add_option(\n '--add-metadata',\n action='store_true', dest='addmetadata', default=False,\n help='Write metadata to the video file')\n postproc.add_option(\n '--metadata-from-title',\n metavar='FORMAT', dest='metafromtitle',\n help='Parse additional metadata like song title / artist from the video title. '\n 'The format syntax is the same as --output. Regular expression with '\n 'named capture groups may also be used. '\n 'The parsed parameters replace existing values. '\n 'Example: --metadata-from-title \"%(artist)s - %(title)s\" matches a title like '\n '\"Coldplay - Paradise\". '\n 'Example (regex): --metadata-from-title \"(?P<artist>.+?) - (?P<title>.+)\"')\n postproc.add_option(\n '--xattrs',\n action='store_true', dest='xattrs', default=False,\n help='Write metadata to the video file\\'s xattrs (using dublin core and xdg standards)')\n postproc.add_option(\n '--fixup',\n metavar='POLICY', dest='fixup', default='detect_or_warn',\n help='Automatically correct known faults of the file. '\n 'One of never (do nothing), warn (only emit a warning), '\n 'detect_or_warn (the default; fix file if we can, warn otherwise)')\n postproc.add_option(\n '--prefer-avconv',\n action='store_false', dest='prefer_ffmpeg',\n help='Prefer avconv over ffmpeg for running the postprocessors')\n postproc.add_option(\n '--prefer-ffmpeg',\n action='store_true', dest='prefer_ffmpeg',\n help='Prefer ffmpeg over avconv for running the postprocessors (default)')\n postproc.add_option(\n '--ffmpeg-location', '--avconv-location', metavar='PATH',\n dest='ffmpeg_location',\n help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')\n postproc.add_option(\n '--exec',\n metavar='CMD', dest='exec_cmd',\n help='Execute a command on the file after downloading and post-processing, similar to find\\'s -exec syntax. Example: --exec \\'adb push {} /sdcard/Music/ && rm {}\\'')\n postproc.add_option(\n '--convert-subs', '--convert-subtitles',\n metavar='FORMAT', dest='convertsubtitles', default=None,\n help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')\n\n parser.add_option_group(general)\n parser.add_option_group(network)\n parser.add_option_group(geo)\n parser.add_option_group(selection)\n parser.add_option_group(downloader)\n parser.add_option_group(filesystem)\n parser.add_option_group(thumbnail)\n parser.add_option_group(verbosity)\n parser.add_option_group(workarounds)\n parser.add_option_group(video_format)\n parser.add_option_group(subtitles)\n parser.add_option_group(authentication)\n parser.add_option_group(adobe_pass)\n parser.add_option_group(postproc)\n\n if overrideArguments is not None:\n opts, args = parser.parse_args(overrideArguments)\n if opts.verbose:\n write_string('[debug] Override config: ' + repr(overrideArguments) + '\\n')\n else:\n def compat_conf(conf):\n if sys.version_info < (3,):\n return [a.decode(preferredencoding(), 'replace') for a in conf]\n return conf\n\n command_line_conf = compat_conf(sys.argv[1:])\n opts, args = parser.parse_args(command_line_conf)\n\n system_conf = user_conf = custom_conf = []\n\n if '--config-location' in command_line_conf:\n location = compat_expanduser(opts.config_location)\n if os.path.isdir(location):\n location = os.path.join(location, 'youtube-dl.conf')\n if not os.path.exists(location):\n parser.error('config-location %s does not exist.' % location)\n custom_conf = _readOptions(location)\n elif '--ignore-config' in command_line_conf:\n pass\n else:\n system_conf = _readOptions('/etc/youtube-dl.conf')\n if '--ignore-config' not in system_conf:\n user_conf = _readUserConf()\n\n argv = system_conf + user_conf + custom_conf + command_line_conf\n opts, args = parser.parse_args(argv)\n if opts.verbose:\n for conf_label, conf in (\n ('System config', system_conf),\n ('User config', user_conf),\n ('Custom config', custom_conf),\n ('Command-line args', command_line_conf)):\n write_string('[debug] %s: %s\\n' % (conf_label, repr(_hide_login_info(conf))))\n\n return parser, opts, args", "has_branch": true, "total_branches": 2} {"prompt_id": 927, "project": "youtube_dl", "module": "youtube_dl.postprocessor.common", "class": "PostProcessor", "method": "try_utime", "focal_method_txt": " def try_utime(self, path, atime, mtime, errnote='Cannot update utime of file'):\n try:\n os.utime(encodeFilename(path), (atime, mtime))\n except Exception:\n self._downloader.report_warning(errnote)", "focal_method_lines": [57, 61], "in_stack": false, "globals": [], "type_context": "import os\nfrom ..utils import (\n PostProcessingError,\n cli_configuration_args,\n encodeFilename,\n)\n\n\n\nclass PostProcessor(object):\n\n _downloader = None\n\n def __init__(self, downloader=None):\n self._downloader = downloader\n\n def try_utime(self, path, atime, mtime, errnote='Cannot update utime of file'):\n try:\n os.utime(encodeFilename(path), (atime, mtime))\n except Exception:\n self._downloader.report_warning(errnote)", "has_branch": false, "total_branches": 0} {"prompt_id": 928, "project": "youtube_dl", "module": "youtube_dl.postprocessor.metadatafromtitle", "class": "MetadataFromTitlePP", "method": "__init__", "focal_method_txt": " def __init__(self, downloader, titleformat):\n super(MetadataFromTitlePP, self).__init__(downloader)\n self._titleformat = titleformat\n self._titleregex = (self.format_to_regex(titleformat)\n if re.search(r'%\\(\\w+\\)s', titleformat)\n else titleformat)", "focal_method_lines": [8, 11], "in_stack": false, "globals": [], "type_context": "import re\nfrom .common import PostProcessor\n\n\n\nclass MetadataFromTitlePP(PostProcessor):\n\n def __init__(self, downloader, titleformat):\n super(MetadataFromTitlePP, self).__init__(downloader)\n self._titleformat = titleformat\n self._titleregex = (self.format_to_regex(titleformat)\n if re.search(r'%\\(\\w+\\)s', titleformat)\n else titleformat)", "has_branch": false, "total_branches": 0} {"prompt_id": 929, "project": "youtube_dl", "module": "youtube_dl.postprocessor.metadatafromtitle", "class": "MetadataFromTitlePP", "method": "format_to_regex", "focal_method_txt": " def format_to_regex(self, fmt):\n r\"\"\"\n Converts a string like\n '%(title)s - %(artist)s'\n to a regex like\n '(?P<title>.+)\\ \\-\\ (?P<artist>.+)'\n \"\"\"\n lastpos = 0\n regex = ''\n # replace %(..)s with regex group and escape other string parts\n for match in re.finditer(r'%\\((\\w+)\\)s', fmt):\n regex += re.escape(fmt[lastpos:match.start()])\n regex += r'(?P<' + match.group(1) + '>.+)'\n lastpos = match.end()\n if lastpos < len(fmt):\n regex += re.escape(fmt[lastpos:])\n return regex", "focal_method_lines": [15, 31], "in_stack": false, "globals": [], "type_context": "import re\nfrom .common import PostProcessor\n\n\n\nclass MetadataFromTitlePP(PostProcessor):\n\n def __init__(self, downloader, titleformat):\n super(MetadataFromTitlePP, self).__init__(downloader)\n self._titleformat = titleformat\n self._titleregex = (self.format_to_regex(titleformat)\n if re.search(r'%\\(\\w+\\)s', titleformat)\n else titleformat)\n\n def format_to_regex(self, fmt):\n r\"\"\"\n Converts a string like\n '%(title)s - %(artist)s'\n to a regex like\n '(?P<title>.+)\\ \\-\\ (?P<artist>.+)'\n \"\"\"\n lastpos = 0\n regex = ''\n # replace %(..)s with regex group and escape other string parts\n for match in re.finditer(r'%\\((\\w+)\\)s', fmt):\n regex += re.escape(fmt[lastpos:match.start()])\n regex += r'(?P<' + match.group(1) + '>.+)'\n lastpos = match.end()\n if lastpos < len(fmt):\n regex += re.escape(fmt[lastpos:])\n return regex", "has_branch": true, "total_branches": 2} {"prompt_id": 930, "project": "youtube_dl", "module": "youtube_dl.postprocessor.metadatafromtitle", "class": "MetadataFromTitlePP", "method": "run", "focal_method_txt": " def run(self, info):\n title = info['title']\n match = re.match(self._titleregex, title)\n if match is None:\n self._downloader.to_screen(\n '[fromtitle] Could not interpret title of video as \"%s\"'\n % self._titleformat)\n return [], info\n for attribute, value in match.groupdict().items():\n info[attribute] = value\n self._downloader.to_screen(\n '[fromtitle] parsed %s: %s'\n % (attribute, value if value is not None else 'NA'))\n\n return [], info", "focal_method_lines": [33, 47], "in_stack": false, "globals": [], "type_context": "import re\nfrom .common import PostProcessor\n\n\n\nclass MetadataFromTitlePP(PostProcessor):\n\n def __init__(self, downloader, titleformat):\n super(MetadataFromTitlePP, self).__init__(downloader)\n self._titleformat = titleformat\n self._titleregex = (self.format_to_regex(titleformat)\n if re.search(r'%\\(\\w+\\)s', titleformat)\n else titleformat)\n\n def run(self, info):\n title = info['title']\n match = re.match(self._titleregex, title)\n if match is None:\n self._downloader.to_screen(\n '[fromtitle] Could not interpret title of video as \"%s\"'\n % self._titleformat)\n return [], info\n for attribute, value in match.groupdict().items():\n info[attribute] = value\n self._downloader.to_screen(\n '[fromtitle] parsed %s: %s'\n % (attribute, value if value is not None else 'NA'))\n\n return [], info", "has_branch": true, "total_branches": 2} {"prompt_id": 931, "project": "youtube_dl", "module": "youtube_dl.postprocessor.xattrpp", "class": "XAttrMetadataPP", "method": "run", "focal_method_txt": " def run(self, info):\n \"\"\" Set extended attributes on downloaded file (if xattr support is found). \"\"\"\n\n # Write the metadata to the file's xattrs\n self._downloader.to_screen('[metadata] Writing metadata to file\\'s xattrs')\n\n filename = info['filepath']\n\n try:\n xattr_mapping = {\n 'user.xdg.referrer.url': 'webpage_url',\n # 'user.xdg.comment': 'description',\n 'user.dublincore.title': 'title',\n 'user.dublincore.date': 'upload_date',\n 'user.dublincore.description': 'description',\n 'user.dublincore.contributor': 'uploader',\n 'user.dublincore.format': 'format',\n }\n\n num_written = 0\n for xattrname, infoname in xattr_mapping.items():\n\n value = info.get(infoname)\n\n if value:\n if infoname == 'upload_date':\n value = hyphenate_date(value)\n\n byte_value = value.encode('utf-8')\n write_xattr(filename, xattrname, byte_value)\n num_written += 1\n\n return [], info\n\n except XAttrUnavailableError as e:\n self._downloader.report_error(str(e))\n return [], info\n\n except XAttrMetadataError as e:\n if e.reason == 'NO_SPACE':\n self._downloader.report_warning(\n 'There\\'s no disk space left, disk quota exceeded or filesystem xattr limit exceeded. '\n + (('Some ' if num_written else '') + 'extended attributes are not written.').capitalize())\n elif e.reason == 'VALUE_TOO_LONG':\n self._downloader.report_warning(\n 'Unable to write extended attributes due to too long values.')\n else:\n msg = 'This filesystem doesn\\'t support extended attributes. '\n if compat_os_name == 'nt':\n msg += 'You need to use NTFS.'\n else:\n msg += '(You may have to enable them in your /etc/fstab)'\n self._downloader.report_error(msg)\n return [], info", "focal_method_lines": [25, 78], "in_stack": false, "globals": [], "type_context": "from .common import PostProcessor\nfrom ..compat import compat_os_name\nfrom ..utils import (\n hyphenate_date,\n write_xattr,\n XAttrMetadataError,\n XAttrUnavailableError,\n)\n\n\n\nclass XAttrMetadataPP(PostProcessor):\n\n #\n # More info about extended attributes for media:\n # http://freedesktop.org/wiki/CommonExtendedAttributes/\n # http://www.freedesktop.org/wiki/PhreedomDraft/\n # http://dublincore.org/documents/usageguide/elements.shtml\n #\n # TODO:\n # * capture youtube keywords and put them in 'user.dublincore.subject' (comma-separated)\n # * figure out which xattrs can be used for 'duration', 'thumbnail', 'resolution'\n #\n\n def run(self, info):\n \"\"\" Set extended attributes on downloaded file (if xattr support is found). \"\"\"\n\n # Write the metadata to the file's xattrs\n self._downloader.to_screen('[metadata] Writing metadata to file\\'s xattrs')\n\n filename = info['filepath']\n\n try:\n xattr_mapping = {\n 'user.xdg.referrer.url': 'webpage_url',\n # 'user.xdg.comment': 'description',\n 'user.dublincore.title': 'title',\n 'user.dublincore.date': 'upload_date',\n 'user.dublincore.description': 'description',\n 'user.dublincore.contributor': 'uploader',\n 'user.dublincore.format': 'format',\n }\n\n num_written = 0\n for xattrname, infoname in xattr_mapping.items():\n\n value = info.get(infoname)\n\n if value:\n if infoname == 'upload_date':\n value = hyphenate_date(value)\n\n byte_value = value.encode('utf-8')\n write_xattr(filename, xattrname, byte_value)\n num_written += 1\n\n return [], info\n\n except XAttrUnavailableError as e:\n self._downloader.report_error(str(e))\n return [], info\n\n except XAttrMetadataError as e:\n if e.reason == 'NO_SPACE':\n self._downloader.report_warning(\n 'There\\'s no disk space left, disk quota exceeded or filesystem xattr limit exceeded. '\n + (('Some ' if num_written else '') + 'extended attributes are not written.').capitalize())\n elif e.reason == 'VALUE_TOO_LONG':\n self._downloader.report_warning(\n 'Unable to write extended attributes due to too long values.')\n else:\n msg = 'This filesystem doesn\\'t support extended attributes. '\n if compat_os_name == 'nt':\n msg += 'You need to use NTFS.'\n else:\n msg += '(You may have to enable them in your /etc/fstab)'\n self._downloader.report_error(msg)\n return [], info", "has_branch": true, "total_branches": 2} {"prompt_id": 932, "project": "youtube_dl", "module": "youtube_dl.socks", "class": "ProxyError", "method": "__init__", "focal_method_txt": " def __init__(self, code=None, msg=None):\n if code is not None and msg is None:\n msg = self.CODES.get(code) or 'unknown error'\n super(ProxyError, self).__init__(code, msg)", "focal_method_lines": [60, 63], "in_stack": false, "globals": ["__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy"], "type_context": "import collections\nimport socket\nfrom .compat import (\n compat_ord,\n compat_struct_pack,\n compat_struct_unpack,\n)\n\n__author__ = 'Timo Schmid <coding@timoschmid.de>'\nSOCKS4_VERSION = 4\nSOCKS4_REPLY_VERSION = 0x00\nSOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)\nSOCKS5_VERSION = 5\nSOCKS5_USER_AUTH_VERSION = 0x01\nSOCKS5_USER_AUTH_SUCCESS = 0x00\nProxy = collections.namedtuple('Proxy', (\n 'type', 'host', 'port', 'username', 'password', 'remote_dns'))\n\nclass ProxyError(socket.error):\n\n ERR_SUCCESS = 0x00\n\n def __init__(self, code=None, msg=None):\n if code is not None and msg is None:\n msg = self.CODES.get(code) or 'unknown error'\n super(ProxyError, self).__init__(code, msg)", "has_branch": true, "total_branches": 2} {"prompt_id": 933, "project": "youtube_dl", "module": "youtube_dl.socks", "class": "InvalidVersionError", "method": "__init__", "focal_method_txt": " def __init__(self, expected_version, got_version):\n msg = ('Invalid response version from server. Expected {0:02x} got '\n '{1:02x}'.format(expected_version, got_version))\n super(InvalidVersionError, self).__init__(0, msg)", "focal_method_lines": [67, 70], "in_stack": false, "globals": ["__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy"], "type_context": "import collections\nimport socket\nfrom .compat import (\n compat_ord,\n compat_struct_pack,\n compat_struct_unpack,\n)\n\n__author__ = 'Timo Schmid <coding@timoschmid.de>'\nSOCKS4_VERSION = 4\nSOCKS4_REPLY_VERSION = 0x00\nSOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)\nSOCKS5_VERSION = 5\nSOCKS5_USER_AUTH_VERSION = 0x01\nSOCKS5_USER_AUTH_SUCCESS = 0x00\nProxy = collections.namedtuple('Proxy', (\n 'type', 'host', 'port', 'username', 'password', 'remote_dns'))\n\nclass InvalidVersionError(ProxyError):\n\n def __init__(self, expected_version, got_version):\n msg = ('Invalid response version from server. Expected {0:02x} got '\n '{1:02x}'.format(expected_version, got_version))\n super(InvalidVersionError, self).__init__(0, msg)", "has_branch": false, "total_branches": 0} {"prompt_id": 934, "project": "youtube_dl", "module": "youtube_dl.socks", "class": "sockssocket", "method": "setproxy", "focal_method_txt": " def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None):\n assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5)\n\n self._proxy = Proxy(proxytype, addr, port, username, password, rdns)", "focal_method_lines": [115, 118], "in_stack": false, "globals": ["__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy"], "type_context": "import collections\nimport socket\nfrom .compat import (\n compat_ord,\n compat_struct_pack,\n compat_struct_unpack,\n)\n\n__author__ = 'Timo Schmid <coding@timoschmid.de>'\nSOCKS4_VERSION = 4\nSOCKS4_REPLY_VERSION = 0x00\nSOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)\nSOCKS5_VERSION = 5\nSOCKS5_USER_AUTH_VERSION = 0x01\nSOCKS5_USER_AUTH_SUCCESS = 0x00\nProxy = collections.namedtuple('Proxy', (\n 'type', 'host', 'port', 'username', 'password', 'remote_dns'))\n\nclass sockssocket(socket.socket):\n\n def __init__(self, *args, **kwargs):\n self._proxy = None\n super(sockssocket, self).__init__(*args, **kwargs)\n\n def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None):\n assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5)\n\n self._proxy = Proxy(proxytype, addr, port, username, password, rdns)", "has_branch": false, "total_branches": 0} {"prompt_id": 935, "project": "youtube_dl", "module": "youtube_dl.socks", "class": "sockssocket", "method": "recvall", "focal_method_txt": " def recvall(self, cnt):\n data = b''\n while len(data) < cnt:\n cur = self.recv(cnt - len(data))\n if not cur:\n raise EOFError('{0} bytes missing'.format(cnt - len(data)))\n data += cur\n return data", "focal_method_lines": [120, 127], "in_stack": false, "globals": ["__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy"], "type_context": "import collections\nimport socket\nfrom .compat import (\n compat_ord,\n compat_struct_pack,\n compat_struct_unpack,\n)\n\n__author__ = 'Timo Schmid <coding@timoschmid.de>'\nSOCKS4_VERSION = 4\nSOCKS4_REPLY_VERSION = 0x00\nSOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)\nSOCKS5_VERSION = 5\nSOCKS5_USER_AUTH_VERSION = 0x01\nSOCKS5_USER_AUTH_SUCCESS = 0x00\nProxy = collections.namedtuple('Proxy', (\n 'type', 'host', 'port', 'username', 'password', 'remote_dns'))\n\nclass sockssocket(socket.socket):\n\n def __init__(self, *args, **kwargs):\n self._proxy = None\n super(sockssocket, self).__init__(*args, **kwargs)\n\n def recvall(self, cnt):\n data = b''\n while len(data) < cnt:\n cur = self.recv(cnt - len(data))\n if not cur:\n raise EOFError('{0} bytes missing'.format(cnt - len(data)))\n data += cur\n return data", "has_branch": true, "total_branches": 2} {"prompt_id": 936, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "_ScopeDict", "method": "__repr__", "focal_method_txt": " def __repr__(self):\n return '%s__Scope(%s)' % (\n self.avm_class.name,\n super(_ScopeDict, self).__repr__())", "focal_method_lines": [59, 60], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass _ScopeDict(dict):\n\n def __init__(self, avm_class):\n super(_ScopeDict, self).__init__()\n self.avm_class = avm_class\n\n def __repr__(self):\n return '%s__Scope(%s)' % (\n self.avm_class.name,\n super(_ScopeDict, self).__repr__())", "has_branch": false, "total_branches": 0} {"prompt_id": 937, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "_AVMClass", "method": "register_methods", "focal_method_txt": " def register_methods(self, methods):\n self.method_names.update(methods.items())\n self.method_idxs.update(dict(\n (idx, name)\n for name, idx in methods.items()))", "focal_method_lines": [84, 86], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass _AVMClass(object):\n\n def __init__(self, name_idx, name, static_properties=None):\n self.name_idx = name_idx\n self.name = name\n self.method_names = {}\n self.method_idxs = {}\n self.methods = {}\n self.method_pyfunctions = {}\n self.static_properties = static_properties if static_properties else {}\n\n self.variables = _ScopeDict(self)\n self.constants = {}\n\n def register_methods(self, methods):\n self.method_names.update(methods.items())\n self.method_idxs.update(dict(\n (idx, name)\n for name, idx in methods.items()))", "has_branch": false, "total_branches": 0} {"prompt_id": 938, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "SWFInterpreter", "method": "__init__", "focal_method_txt": " def __init__(self, file_contents):\n self._patched_functions = {\n (TimerClass, 'addEventListener'): lambda params: undefined,\n }\n code_tag = next(tag\n for tag_code, tag in _extract_tags(file_contents)\n if tag_code == 82)\n p = code_tag.index(b'\\0', 4) + 1\n code_reader = io.BytesIO(code_tag[p:])\n\n # Parse ABC (AVM2 ByteCode)\n\n # Define a couple convenience methods\n u30 = lambda *args: _u30(*args, reader=code_reader)\n s32 = lambda *args: _s32(*args, reader=code_reader)\n u32 = lambda *args: _u32(*args, reader=code_reader)\n read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)\n read_byte = lambda *args: _read_byte(*args, reader=code_reader)\n\n # minor_version + major_version\n read_bytes(2 + 2)\n\n # Constant pool\n int_count = u30()\n self.constant_ints = [0]\n for _c in range(1, int_count):\n self.constant_ints.append(s32())\n self.constant_uints = [0]\n uint_count = u30()\n for _c in range(1, uint_count):\n self.constant_uints.append(u32())\n double_count = u30()\n read_bytes(max(0, (double_count - 1)) * 8)\n string_count = u30()\n self.constant_strings = ['']\n for _c in range(1, string_count):\n s = _read_string(code_reader)\n self.constant_strings.append(s)\n namespace_count = u30()\n for _c in range(1, namespace_count):\n read_bytes(1) # kind\n u30() # name\n ns_set_count = u30()\n for _c in range(1, ns_set_count):\n count = u30()\n for _c2 in range(count):\n u30()\n multiname_count = u30()\n MULTINAME_SIZES = {\n 0x07: 2, # QName\n 0x0d: 2, # QNameA\n 0x0f: 1, # RTQName\n 0x10: 1, # RTQNameA\n 0x11: 0, # RTQNameL\n 0x12: 0, # RTQNameLA\n 0x09: 2, # Multiname\n 0x0e: 2, # MultinameA\n 0x1b: 1, # MultinameL\n 0x1c: 1, # MultinameLA\n }\n self.multinames = ['']\n for _c in range(1, multiname_count):\n kind = u30()\n assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind\n if kind == 0x07:\n u30() # namespace_idx\n name_idx = u30()\n self.multinames.append(self.constant_strings[name_idx])\n elif kind == 0x09:\n name_idx = u30()\n u30()\n self.multinames.append(self.constant_strings[name_idx])\n else:\n self.multinames.append(_Multiname(kind))\n for _c2 in range(MULTINAME_SIZES[kind]):\n u30()\n\n # Methods\n method_count = u30()\n MethodInfo = collections.namedtuple(\n 'MethodInfo',\n ['NEED_ARGUMENTS', 'NEED_REST'])\n method_infos = []\n for method_id in range(method_count):\n param_count = u30()\n u30() # return type\n for _ in range(param_count):\n u30() # param type\n u30() # name index (always 0 for youtube)\n flags = read_byte()\n if flags & 0x08 != 0:\n # Options present\n option_count = u30()\n for c in range(option_count):\n u30() # val\n read_bytes(1) # kind\n if flags & 0x80 != 0:\n # Param names present\n for _ in range(param_count):\n u30() # param name\n mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)\n method_infos.append(mi)\n\n # Metadata\n metadata_count = u30()\n for _c in range(metadata_count):\n u30() # name\n item_count = u30()\n for _c2 in range(item_count):\n u30() # key\n u30() # value\n\n def parse_traits_info():\n trait_name_idx = u30()\n kind_full = read_byte()\n kind = kind_full & 0x0f\n attrs = kind_full >> 4\n methods = {}\n constants = None\n if kind == 0x00: # Slot\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n if vindex != 0:\n read_byte() # vkind\n elif kind == 0x06: # Const\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n vkind = 'any'\n if vindex != 0:\n vkind = read_byte()\n if vkind == 0x03: # Constant_Int\n value = self.constant_ints[vindex]\n elif vkind == 0x04: # Constant_UInt\n value = self.constant_uints[vindex]\n else:\n return {}, None # Ignore silently for now\n constants = {self.multinames[trait_name_idx]: value}\n elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter\n u30() # disp_id\n method_idx = u30()\n methods[self.multinames[trait_name_idx]] = method_idx\n elif kind == 0x04: # Class\n u30() # slot_id\n u30() # classi\n elif kind == 0x05: # Function\n u30() # slot_id\n function_idx = u30()\n methods[function_idx] = self.multinames[trait_name_idx]\n else:\n raise ExtractorError('Unsupported trait kind %d' % kind)\n\n if attrs & 0x4 != 0: # Metadata present\n metadata_count = u30()\n for _c3 in range(metadata_count):\n u30() # metadata index\n\n return methods, constants\n\n # Classes\n class_count = u30()\n classes = []\n for class_id in range(class_count):\n name_idx = u30()\n\n cname = self.multinames[name_idx]\n avm_class = _AVMClass(name_idx, cname)\n classes.append(avm_class)\n\n u30() # super_name idx\n flags = read_byte()\n if flags & 0x08 != 0: # Protected namespace is present\n u30() # protected_ns_idx\n intrf_count = u30()\n for _c2 in range(intrf_count):\n u30()\n u30() # iinit\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n assert len(classes) == class_count\n self._classes_by_name = dict((c.name, c) for c in classes)\n\n for avm_class in classes:\n avm_class.cinit_idx = u30()\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n # Scripts\n script_count = u30()\n for _c in range(script_count):\n u30() # init\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n # Method bodies\n method_body_count = u30()\n Method = collections.namedtuple('Method', ['code', 'local_count'])\n self._all_methods = []\n for _c in range(method_body_count):\n method_idx = u30()\n u30() # max_stack\n local_count = u30()\n u30() # init_scope_depth\n u30() # max_scope_depth\n code_length = u30()\n code = read_bytes(code_length)\n m = Method(code, local_count)\n self._all_methods.append(m)\n for avm_class in classes:\n if method_idx in avm_class.method_idxs:\n avm_class.methods[avm_class.method_idxs[method_idx]] = m\n exception_count = u30()\n for _c2 in range(exception_count):\n u30() # from\n u30() # to\n u30() # target\n u30() # exc_type\n u30() # var_name\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n assert p + code_reader.tell() == len(code_tag)", "focal_method_lines": [185, 418], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass _AVMClass(object):\n\n def __init__(self, name_idx, name, static_properties=None):\n self.name_idx = name_idx\n self.name = name\n self.method_names = {}\n self.method_idxs = {}\n self.methods = {}\n self.method_pyfunctions = {}\n self.static_properties = static_properties if static_properties else {}\n\n self.variables = _ScopeDict(self)\n self.constants = {}\n\nclass _Multiname(object):\n\n def __init__(self, kind):\n self.kind = kind\n\nclass SWFInterpreter(object):\n\n def __init__(self, file_contents):\n self._patched_functions = {\n (TimerClass, 'addEventListener'): lambda params: undefined,\n }\n code_tag = next(tag\n for tag_code, tag in _extract_tags(file_contents)\n if tag_code == 82)\n p = code_tag.index(b'\\0', 4) + 1\n code_reader = io.BytesIO(code_tag[p:])\n\n # Parse ABC (AVM2 ByteCode)\n\n # Define a couple convenience methods\n u30 = lambda *args: _u30(*args, reader=code_reader)\n s32 = lambda *args: _s32(*args, reader=code_reader)\n u32 = lambda *args: _u32(*args, reader=code_reader)\n read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)\n read_byte = lambda *args: _read_byte(*args, reader=code_reader)\n\n # minor_version + major_version\n read_bytes(2 + 2)\n\n # Constant pool\n int_count = u30()\n self.constant_ints = [0]\n for _c in range(1, int_count):\n self.constant_ints.append(s32())\n self.constant_uints = [0]\n uint_count = u30()\n for _c in range(1, uint_count):\n self.constant_uints.append(u32())\n double_count = u30()\n read_bytes(max(0, (double_count - 1)) * 8)\n string_count = u30()\n self.constant_strings = ['']\n for _c in range(1, string_count):\n s = _read_string(code_reader)\n self.constant_strings.append(s)\n namespace_count = u30()\n for _c in range(1, namespace_count):\n read_bytes(1) # kind\n u30() # name\n ns_set_count = u30()\n for _c in range(1, ns_set_count):\n count = u30()\n for _c2 in range(count):\n u30()\n multiname_count = u30()\n MULTINAME_SIZES = {\n 0x07: 2, # QName\n 0x0d: 2, # QNameA\n 0x0f: 1, # RTQName\n 0x10: 1, # RTQNameA\n 0x11: 0, # RTQNameL\n 0x12: 0, # RTQNameLA\n 0x09: 2, # Multiname\n 0x0e: 2, # MultinameA\n 0x1b: 1, # MultinameL\n 0x1c: 1, # MultinameLA\n }\n self.multinames = ['']\n for _c in range(1, multiname_count):\n kind = u30()\n assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind\n if kind == 0x07:\n u30() # namespace_idx\n name_idx = u30()\n self.multinames.append(self.constant_strings[name_idx])\n elif kind == 0x09:\n name_idx = u30()\n u30()\n self.multinames.append(self.constant_strings[name_idx])\n else:\n self.multinames.append(_Multiname(kind))\n for _c2 in range(MULTINAME_SIZES[kind]):\n u30()\n\n # Methods\n method_count = u30()\n MethodInfo = collections.namedtuple(\n 'MethodInfo',\n ['NEED_ARGUMENTS', 'NEED_REST'])\n method_infos = []\n for method_id in range(method_count):\n param_count = u30()\n u30() # return type\n for _ in range(param_count):\n u30() # param type\n u30() # name index (always 0 for youtube)\n flags = read_byte()\n if flags & 0x08 != 0:\n # Options present\n option_count = u30()\n for c in range(option_count):\n u30() # val\n read_bytes(1) # kind\n if flags & 0x80 != 0:\n # Param names present\n for _ in range(param_count):\n u30() # param name\n mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)\n method_infos.append(mi)\n\n # Metadata\n metadata_count = u30()\n for _c in range(metadata_count):\n u30() # name\n item_count = u30()\n for _c2 in range(item_count):\n u30() # key\n u30() # value\n\n def parse_traits_info():\n trait_name_idx = u30()\n kind_full = read_byte()\n kind = kind_full & 0x0f\n attrs = kind_full >> 4\n methods = {}\n constants = None\n if kind == 0x00: # Slot\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n if vindex != 0:\n read_byte() # vkind\n elif kind == 0x06: # Const\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n vkind = 'any'\n if vindex != 0:\n vkind = read_byte()\n if vkind == 0x03: # Constant_Int\n value = self.constant_ints[vindex]\n elif vkind == 0x04: # Constant_UInt\n value = self.constant_uints[vindex]\n else:\n return {}, None # Ignore silently for now\n constants = {self.multinames[trait_name_idx]: value}\n elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter\n u30() # disp_id\n method_idx = u30()\n methods[self.multinames[trait_name_idx]] = method_idx\n elif kind == 0x04: # Class\n u30() # slot_id\n u30() # classi\n elif kind == 0x05: # Function\n u30() # slot_id\n function_idx = u30()\n methods[function_idx] = self.multinames[trait_name_idx]\n else:\n raise ExtractorError('Unsupported trait kind %d' % kind)\n\n if attrs & 0x4 != 0: # Metadata present\n metadata_count = u30()\n for _c3 in range(metadata_count):\n u30() # metadata index\n\n return methods, constants\n\n # Classes\n class_count = u30()\n classes = []\n for class_id in range(class_count):\n name_idx = u30()\n\n cname = self.multinames[name_idx]\n avm_class = _AVMClass(name_idx, cname)\n classes.append(avm_class)\n\n u30() # super_name idx\n flags = read_byte()\n if flags & 0x08 != 0: # Protected namespace is present\n u30() # protected_ns_idx\n intrf_count = u30()\n for _c2 in range(intrf_count):\n u30()\n u30() # iinit\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n assert len(classes) == class_count\n self._classes_by_name = dict((c.name, c) for c in classes)\n\n for avm_class in classes:\n avm_class.cinit_idx = u30()\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n # Scripts\n script_count = u30()\n for _c in range(script_count):\n u30() # init\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n # Method bodies\n method_body_count = u30()\n Method = collections.namedtuple('Method', ['code', 'local_count'])\n self._all_methods = []\n for _c in range(method_body_count):\n method_idx = u30()\n u30() # max_stack\n local_count = u30()\n u30() # init_scope_depth\n u30() # max_scope_depth\n code_length = u30()\n code = read_bytes(code_length)\n m = Method(code, local_count)\n self._all_methods.append(m)\n for avm_class in classes:\n if method_idx in avm_class.method_idxs:\n avm_class.methods[avm_class.method_idxs[method_idx]] = m\n exception_count = u30()\n for _c2 in range(exception_count):\n u30() # from\n u30() # to\n u30() # target\n u30() # exc_type\n u30() # var_name\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n assert p + code_reader.tell() == len(code_tag)", "has_branch": true, "total_branches": 2} {"prompt_id": 939, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "SWFInterpreter", "method": "patch_function", "focal_method_txt": " def patch_function(self, avm_class, func_name, f):\n self._patched_functions[(avm_class, func_name)] = f", "focal_method_lines": [420, 421], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass SWFInterpreter(object):\n\n def __init__(self, file_contents):\n self._patched_functions = {\n (TimerClass, 'addEventListener'): lambda params: undefined,\n }\n code_tag = next(tag\n for tag_code, tag in _extract_tags(file_contents)\n if tag_code == 82)\n p = code_tag.index(b'\\0', 4) + 1\n code_reader = io.BytesIO(code_tag[p:])\n\n # Parse ABC (AVM2 ByteCode)\n\n # Define a couple convenience methods\n u30 = lambda *args: _u30(*args, reader=code_reader)\n s32 = lambda *args: _s32(*args, reader=code_reader)\n u32 = lambda *args: _u32(*args, reader=code_reader)\n read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)\n read_byte = lambda *args: _read_byte(*args, reader=code_reader)\n\n # minor_version + major_version\n read_bytes(2 + 2)\n\n # Constant pool\n int_count = u30()\n self.constant_ints = [0]\n for _c in range(1, int_count):\n self.constant_ints.append(s32())\n self.constant_uints = [0]\n uint_count = u30()\n for _c in range(1, uint_count):\n self.constant_uints.append(u32())\n double_count = u30()\n read_bytes(max(0, (double_count - 1)) * 8)\n string_count = u30()\n self.constant_strings = ['']\n for _c in range(1, string_count):\n s = _read_string(code_reader)\n self.constant_strings.append(s)\n namespace_count = u30()\n for _c in range(1, namespace_count):\n read_bytes(1) # kind\n u30() # name\n ns_set_count = u30()\n for _c in range(1, ns_set_count):\n count = u30()\n for _c2 in range(count):\n u30()\n multiname_count = u30()\n MULTINAME_SIZES = {\n 0x07: 2, # QName\n 0x0d: 2, # QNameA\n 0x0f: 1, # RTQName\n 0x10: 1, # RTQNameA\n 0x11: 0, # RTQNameL\n 0x12: 0, # RTQNameLA\n 0x09: 2, # Multiname\n 0x0e: 2, # MultinameA\n 0x1b: 1, # MultinameL\n 0x1c: 1, # MultinameLA\n }\n self.multinames = ['']\n for _c in range(1, multiname_count):\n kind = u30()\n assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind\n if kind == 0x07:\n u30() # namespace_idx\n name_idx = u30()\n self.multinames.append(self.constant_strings[name_idx])\n elif kind == 0x09:\n name_idx = u30()\n u30()\n self.multinames.append(self.constant_strings[name_idx])\n else:\n self.multinames.append(_Multiname(kind))\n for _c2 in range(MULTINAME_SIZES[kind]):\n u30()\n\n # Methods\n method_count = u30()\n MethodInfo = collections.namedtuple(\n 'MethodInfo',\n ['NEED_ARGUMENTS', 'NEED_REST'])\n method_infos = []\n for method_id in range(method_count):\n param_count = u30()\n u30() # return type\n for _ in range(param_count):\n u30() # param type\n u30() # name index (always 0 for youtube)\n flags = read_byte()\n if flags & 0x08 != 0:\n # Options present\n option_count = u30()\n for c in range(option_count):\n u30() # val\n read_bytes(1) # kind\n if flags & 0x80 != 0:\n # Param names present\n for _ in range(param_count):\n u30() # param name\n mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)\n method_infos.append(mi)\n\n # Metadata\n metadata_count = u30()\n for _c in range(metadata_count):\n u30() # name\n item_count = u30()\n for _c2 in range(item_count):\n u30() # key\n u30() # value\n\n def parse_traits_info():\n trait_name_idx = u30()\n kind_full = read_byte()\n kind = kind_full & 0x0f\n attrs = kind_full >> 4\n methods = {}\n constants = None\n if kind == 0x00: # Slot\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n if vindex != 0:\n read_byte() # vkind\n elif kind == 0x06: # Const\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n vkind = 'any'\n if vindex != 0:\n vkind = read_byte()\n if vkind == 0x03: # Constant_Int\n value = self.constant_ints[vindex]\n elif vkind == 0x04: # Constant_UInt\n value = self.constant_uints[vindex]\n else:\n return {}, None # Ignore silently for now\n constants = {self.multinames[trait_name_idx]: value}\n elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter\n u30() # disp_id\n method_idx = u30()\n methods[self.multinames[trait_name_idx]] = method_idx\n elif kind == 0x04: # Class\n u30() # slot_id\n u30() # classi\n elif kind == 0x05: # Function\n u30() # slot_id\n function_idx = u30()\n methods[function_idx] = self.multinames[trait_name_idx]\n else:\n raise ExtractorError('Unsupported trait kind %d' % kind)\n\n if attrs & 0x4 != 0: # Metadata present\n metadata_count = u30()\n for _c3 in range(metadata_count):\n u30() # metadata index\n\n return methods, constants\n\n # Classes\n class_count = u30()\n classes = []\n for class_id in range(class_count):\n name_idx = u30()\n\n cname = self.multinames[name_idx]\n avm_class = _AVMClass(name_idx, cname)\n classes.append(avm_class)\n\n u30() # super_name idx\n flags = read_byte()\n if flags & 0x08 != 0: # Protected namespace is present\n u30() # protected_ns_idx\n intrf_count = u30()\n for _c2 in range(intrf_count):\n u30()\n u30() # iinit\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n assert len(classes) == class_count\n self._classes_by_name = dict((c.name, c) for c in classes)\n\n for avm_class in classes:\n avm_class.cinit_idx = u30()\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n # Scripts\n script_count = u30()\n for _c in range(script_count):\n u30() # init\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n # Method bodies\n method_body_count = u30()\n Method = collections.namedtuple('Method', ['code', 'local_count'])\n self._all_methods = []\n for _c in range(method_body_count):\n method_idx = u30()\n u30() # max_stack\n local_count = u30()\n u30() # init_scope_depth\n u30() # max_scope_depth\n code_length = u30()\n code = read_bytes(code_length)\n m = Method(code, local_count)\n self._all_methods.append(m)\n for avm_class in classes:\n if method_idx in avm_class.method_idxs:\n avm_class.methods[avm_class.method_idxs[method_idx]] = m\n exception_count = u30()\n for _c2 in range(exception_count):\n u30() # from\n u30() # to\n u30() # target\n u30() # exc_type\n u30() # var_name\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n assert p + code_reader.tell() == len(code_tag)\n\n def patch_function(self, avm_class, func_name, f):\n self._patched_functions[(avm_class, func_name)] = f", "has_branch": false, "total_branches": 0} {"prompt_id": 940, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "SWFInterpreter", "method": "extract_class", "focal_method_txt": " def extract_class(self, class_name, call_cinit=True):\n try:\n res = self._classes_by_name[class_name]\n except KeyError:\n raise ExtractorError('Class %r not found' % class_name)\n\n if call_cinit and hasattr(res, 'cinit_idx'):\n res.register_methods({'$cinit': res.cinit_idx})\n res.methods['$cinit'] = self._all_methods[res.cinit_idx]\n cinit = self.extract_function(res, '$cinit')\n cinit([])\n\n return res", "focal_method_lines": [423, 435], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass SWFInterpreter(object):\n\n def __init__(self, file_contents):\n self._patched_functions = {\n (TimerClass, 'addEventListener'): lambda params: undefined,\n }\n code_tag = next(tag\n for tag_code, tag in _extract_tags(file_contents)\n if tag_code == 82)\n p = code_tag.index(b'\\0', 4) + 1\n code_reader = io.BytesIO(code_tag[p:])\n\n # Parse ABC (AVM2 ByteCode)\n\n # Define a couple convenience methods\n u30 = lambda *args: _u30(*args, reader=code_reader)\n s32 = lambda *args: _s32(*args, reader=code_reader)\n u32 = lambda *args: _u32(*args, reader=code_reader)\n read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)\n read_byte = lambda *args: _read_byte(*args, reader=code_reader)\n\n # minor_version + major_version\n read_bytes(2 + 2)\n\n # Constant pool\n int_count = u30()\n self.constant_ints = [0]\n for _c in range(1, int_count):\n self.constant_ints.append(s32())\n self.constant_uints = [0]\n uint_count = u30()\n for _c in range(1, uint_count):\n self.constant_uints.append(u32())\n double_count = u30()\n read_bytes(max(0, (double_count - 1)) * 8)\n string_count = u30()\n self.constant_strings = ['']\n for _c in range(1, string_count):\n s = _read_string(code_reader)\n self.constant_strings.append(s)\n namespace_count = u30()\n for _c in range(1, namespace_count):\n read_bytes(1) # kind\n u30() # name\n ns_set_count = u30()\n for _c in range(1, ns_set_count):\n count = u30()\n for _c2 in range(count):\n u30()\n multiname_count = u30()\n MULTINAME_SIZES = {\n 0x07: 2, # QName\n 0x0d: 2, # QNameA\n 0x0f: 1, # RTQName\n 0x10: 1, # RTQNameA\n 0x11: 0, # RTQNameL\n 0x12: 0, # RTQNameLA\n 0x09: 2, # Multiname\n 0x0e: 2, # MultinameA\n 0x1b: 1, # MultinameL\n 0x1c: 1, # MultinameLA\n }\n self.multinames = ['']\n for _c in range(1, multiname_count):\n kind = u30()\n assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind\n if kind == 0x07:\n u30() # namespace_idx\n name_idx = u30()\n self.multinames.append(self.constant_strings[name_idx])\n elif kind == 0x09:\n name_idx = u30()\n u30()\n self.multinames.append(self.constant_strings[name_idx])\n else:\n self.multinames.append(_Multiname(kind))\n for _c2 in range(MULTINAME_SIZES[kind]):\n u30()\n\n # Methods\n method_count = u30()\n MethodInfo = collections.namedtuple(\n 'MethodInfo',\n ['NEED_ARGUMENTS', 'NEED_REST'])\n method_infos = []\n for method_id in range(method_count):\n param_count = u30()\n u30() # return type\n for _ in range(param_count):\n u30() # param type\n u30() # name index (always 0 for youtube)\n flags = read_byte()\n if flags & 0x08 != 0:\n # Options present\n option_count = u30()\n for c in range(option_count):\n u30() # val\n read_bytes(1) # kind\n if flags & 0x80 != 0:\n # Param names present\n for _ in range(param_count):\n u30() # param name\n mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)\n method_infos.append(mi)\n\n # Metadata\n metadata_count = u30()\n for _c in range(metadata_count):\n u30() # name\n item_count = u30()\n for _c2 in range(item_count):\n u30() # key\n u30() # value\n\n def parse_traits_info():\n trait_name_idx = u30()\n kind_full = read_byte()\n kind = kind_full & 0x0f\n attrs = kind_full >> 4\n methods = {}\n constants = None\n if kind == 0x00: # Slot\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n if vindex != 0:\n read_byte() # vkind\n elif kind == 0x06: # Const\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n vkind = 'any'\n if vindex != 0:\n vkind = read_byte()\n if vkind == 0x03: # Constant_Int\n value = self.constant_ints[vindex]\n elif vkind == 0x04: # Constant_UInt\n value = self.constant_uints[vindex]\n else:\n return {}, None # Ignore silently for now\n constants = {self.multinames[trait_name_idx]: value}\n elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter\n u30() # disp_id\n method_idx = u30()\n methods[self.multinames[trait_name_idx]] = method_idx\n elif kind == 0x04: # Class\n u30() # slot_id\n u30() # classi\n elif kind == 0x05: # Function\n u30() # slot_id\n function_idx = u30()\n methods[function_idx] = self.multinames[trait_name_idx]\n else:\n raise ExtractorError('Unsupported trait kind %d' % kind)\n\n if attrs & 0x4 != 0: # Metadata present\n metadata_count = u30()\n for _c3 in range(metadata_count):\n u30() # metadata index\n\n return methods, constants\n\n # Classes\n class_count = u30()\n classes = []\n for class_id in range(class_count):\n name_idx = u30()\n\n cname = self.multinames[name_idx]\n avm_class = _AVMClass(name_idx, cname)\n classes.append(avm_class)\n\n u30() # super_name idx\n flags = read_byte()\n if flags & 0x08 != 0: # Protected namespace is present\n u30() # protected_ns_idx\n intrf_count = u30()\n for _c2 in range(intrf_count):\n u30()\n u30() # iinit\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n assert len(classes) == class_count\n self._classes_by_name = dict((c.name, c) for c in classes)\n\n for avm_class in classes:\n avm_class.cinit_idx = u30()\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n # Scripts\n script_count = u30()\n for _c in range(script_count):\n u30() # init\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n # Method bodies\n method_body_count = u30()\n Method = collections.namedtuple('Method', ['code', 'local_count'])\n self._all_methods = []\n for _c in range(method_body_count):\n method_idx = u30()\n u30() # max_stack\n local_count = u30()\n u30() # init_scope_depth\n u30() # max_scope_depth\n code_length = u30()\n code = read_bytes(code_length)\n m = Method(code, local_count)\n self._all_methods.append(m)\n for avm_class in classes:\n if method_idx in avm_class.method_idxs:\n avm_class.methods[avm_class.method_idxs[method_idx]] = m\n exception_count = u30()\n for _c2 in range(exception_count):\n u30() # from\n u30() # to\n u30() # target\n u30() # exc_type\n u30() # var_name\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n assert p + code_reader.tell() == len(code_tag)\n\n def extract_class(self, class_name, call_cinit=True):\n try:\n res = self._classes_by_name[class_name]\n except KeyError:\n raise ExtractorError('Class %r not found' % class_name)\n\n if call_cinit and hasattr(res, 'cinit_idx'):\n res.register_methods({'$cinit': res.cinit_idx})\n res.methods['$cinit'] = self._all_methods[res.cinit_idx]\n cinit = self.extract_function(res, '$cinit')\n cinit([])\n\n return res", "has_branch": true, "total_branches": 2} {"prompt_id": 941, "project": "youtube_dl", "module": "youtube_dl.swfinterp", "class": "SWFInterpreter", "method": "extract_function", "focal_method_txt": " def extract_function(self, avm_class, func_name):\n p = self._patched_functions.get((avm_class, func_name))\n if p:\n return p\n if func_name in avm_class.method_pyfunctions:\n return avm_class.method_pyfunctions[func_name]\n if func_name in self._classes_by_name:\n return self._classes_by_name[func_name].make_object()\n if func_name not in avm_class.methods:\n raise ExtractorError('Cannot find function %s.%s' % (\n avm_class.name, func_name))\n m = avm_class.methods[func_name]\n\n def resfunc(args):\n # Helper functions\n coder = io.BytesIO(m.code)\n s24 = lambda: _s24(coder)\n u30 = lambda: _u30(coder)\n\n registers = [avm_class.variables] + list(args) + [None] * m.local_count\n stack = []\n scopes = collections.deque([\n self._classes_by_name, avm_class.constants, avm_class.variables])\n while True:\n opcode = _read_byte(coder)\n if opcode == 9: # label\n pass # Spec says: \"Do nothing.\"\n elif opcode == 16: # jump\n offset = s24()\n coder.seek(coder.tell() + offset)\n elif opcode == 17: # iftrue\n offset = s24()\n value = stack.pop()\n if value:\n coder.seek(coder.tell() + offset)\n elif opcode == 18: # iffalse\n offset = s24()\n value = stack.pop()\n if not value:\n coder.seek(coder.tell() + offset)\n elif opcode == 19: # ifeq\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value2 == value1:\n coder.seek(coder.tell() + offset)\n elif opcode == 20: # ifne\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value2 != value1:\n coder.seek(coder.tell() + offset)\n elif opcode == 21: # iflt\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value1 < value2:\n coder.seek(coder.tell() + offset)\n elif opcode == 32: # pushnull\n stack.append(None)\n elif opcode == 33: # pushundefined\n stack.append(undefined)\n elif opcode == 36: # pushbyte\n v = _read_byte(coder)\n stack.append(v)\n elif opcode == 37: # pushshort\n v = u30()\n stack.append(v)\n elif opcode == 38: # pushtrue\n stack.append(True)\n elif opcode == 39: # pushfalse\n stack.append(False)\n elif opcode == 40: # pushnan\n stack.append(float('NaN'))\n elif opcode == 42: # dup\n value = stack[-1]\n stack.append(value)\n elif opcode == 44: # pushstring\n idx = u30()\n stack.append(self.constant_strings[idx])\n elif opcode == 48: # pushscope\n new_scope = stack.pop()\n scopes.append(new_scope)\n elif opcode == 66: # construct\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n res = obj.avm_class.make_object()\n stack.append(res)\n elif opcode == 70: # callproperty\n index = u30()\n mname = self.multinames[index]\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n\n if obj == StringClass:\n if mname == 'String':\n assert len(args) == 1\n assert isinstance(args[0], (\n int, compat_str, _Undefined))\n if args[0] == undefined:\n res = 'undefined'\n else:\n res = compat_str(args[0])\n stack.append(res)\n continue\n else:\n raise NotImplementedError(\n 'Function String.%s is not yet implemented'\n % mname)\n elif isinstance(obj, _AVMClass_Object):\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n stack.append(res)\n continue\n elif isinstance(obj, _AVMClass):\n func = self.extract_function(obj, mname)\n res = func(args)\n stack.append(res)\n continue\n elif isinstance(obj, _ScopeDict):\n if mname in obj.avm_class.method_names:\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n else:\n res = obj[mname]\n stack.append(res)\n continue\n elif isinstance(obj, compat_str):\n if mname == 'split':\n assert len(args) == 1\n assert isinstance(args[0], compat_str)\n if args[0] == '':\n res = list(obj)\n else:\n res = obj.split(args[0])\n stack.append(res)\n continue\n elif mname == 'charCodeAt':\n assert len(args) <= 1\n idx = 0 if len(args) == 0 else args[0]\n assert isinstance(idx, int)\n res = ord(obj[idx])\n stack.append(res)\n continue\n elif isinstance(obj, list):\n if mname == 'slice':\n assert len(args) == 1\n assert isinstance(args[0], int)\n res = obj[args[0]:]\n stack.append(res)\n continue\n elif mname == 'join':\n assert len(args) == 1\n assert isinstance(args[0], compat_str)\n res = args[0].join(obj)\n stack.append(res)\n continue\n raise NotImplementedError(\n 'Unsupported property %r on %r'\n % (mname, obj))\n elif opcode == 71: # returnvoid\n res = undefined\n return res\n elif opcode == 72: # returnvalue\n res = stack.pop()\n return res\n elif opcode == 73: # constructsuper\n # Not yet implemented, just hope it works without it\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n elif opcode == 74: # constructproperty\n index = u30()\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n\n mname = self.multinames[index]\n assert isinstance(obj, _AVMClass)\n\n # We do not actually call the constructor for now;\n # we just pretend it does nothing\n stack.append(obj.make_object())\n elif opcode == 79: # callpropvoid\n index = u30()\n mname = self.multinames[index]\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n if isinstance(obj, _AVMClass_Object):\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n assert res is undefined\n continue\n if isinstance(obj, _ScopeDict):\n assert mname in obj.avm_class.method_names\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n assert res is undefined\n continue\n if mname == 'reverse':\n assert isinstance(obj, list)\n obj.reverse()\n else:\n raise NotImplementedError(\n 'Unsupported (void) property %r on %r'\n % (mname, obj))\n elif opcode == 86: # newarray\n arg_count = u30()\n arr = []\n for i in range(arg_count):\n arr.append(stack.pop())\n arr = arr[::-1]\n stack.append(arr)\n elif opcode == 93: # findpropstrict\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n res = s\n break\n else:\n res = scopes[0]\n if mname not in res and mname in _builtin_classes:\n stack.append(_builtin_classes[mname])\n else:\n stack.append(res[mname])\n elif opcode == 94: # findproperty\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n res = s\n break\n else:\n res = avm_class.variables\n stack.append(res)\n elif opcode == 96: # getlex\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n scope = s\n break\n else:\n scope = avm_class.variables\n\n if mname in scope:\n res = scope[mname]\n elif mname in _builtin_classes:\n res = _builtin_classes[mname]\n else:\n # Assume uninitialized\n # TODO warn here\n res = undefined\n stack.append(res)\n elif opcode == 97: # setproperty\n index = u30()\n value = stack.pop()\n idx = self.multinames[index]\n if isinstance(idx, _Multiname):\n idx = stack.pop()\n obj = stack.pop()\n obj[idx] = value\n elif opcode == 98: # getlocal\n index = u30()\n stack.append(registers[index])\n elif opcode == 99: # setlocal\n index = u30()\n value = stack.pop()\n registers[index] = value\n elif opcode == 102: # getproperty\n index = u30()\n pname = self.multinames[index]\n if pname == 'length':\n obj = stack.pop()\n assert isinstance(obj, (compat_str, list))\n stack.append(len(obj))\n elif isinstance(pname, compat_str): # Member access\n obj = stack.pop()\n if isinstance(obj, _AVMClass):\n res = obj.static_properties[pname]\n stack.append(res)\n continue\n\n assert isinstance(obj, (dict, _ScopeDict)),\\\n 'Accessing member %r on %r' % (pname, obj)\n res = obj.get(pname, undefined)\n stack.append(res)\n else: # Assume attribute access\n idx = stack.pop()\n assert isinstance(idx, int)\n obj = stack.pop()\n assert isinstance(obj, list)\n stack.append(obj[idx])\n elif opcode == 104: # initproperty\n index = u30()\n value = stack.pop()\n idx = self.multinames[index]\n if isinstance(idx, _Multiname):\n idx = stack.pop()\n obj = stack.pop()\n obj[idx] = value\n elif opcode == 115: # convert_\n value = stack.pop()\n intvalue = int(value)\n stack.append(intvalue)\n elif opcode == 128: # coerce\n u30()\n elif opcode == 130: # coerce_a\n value = stack.pop()\n # um, yes, it's any value\n stack.append(value)\n elif opcode == 133: # coerce_s\n assert isinstance(stack[-1], (type(None), compat_str))\n elif opcode == 147: # decrement\n value = stack.pop()\n assert isinstance(value, int)\n stack.append(value - 1)\n elif opcode == 149: # typeof\n value = stack.pop()\n return {\n _Undefined: 'undefined',\n compat_str: 'String',\n int: 'Number',\n float: 'Number',\n }[type(value)]\n elif opcode == 160: # add\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 + value2\n stack.append(res)\n elif opcode == 161: # subtract\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 - value2\n stack.append(res)\n elif opcode == 162: # multiply\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 * value2\n stack.append(res)\n elif opcode == 164: # modulo\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 % value2\n stack.append(res)\n elif opcode == 168: # bitand\n value2 = stack.pop()\n value1 = stack.pop()\n assert isinstance(value1, int)\n assert isinstance(value2, int)\n res = value1 & value2\n stack.append(res)\n elif opcode == 171: # equals\n value2 = stack.pop()\n value1 = stack.pop()\n result = value1 == value2\n stack.append(result)\n elif opcode == 175: # greaterequals\n value2 = stack.pop()\n value1 = stack.pop()\n result = value1 >= value2\n stack.append(result)\n elif opcode == 192: # increment_i\n value = stack.pop()\n assert isinstance(value, int)\n stack.append(value + 1)\n elif opcode == 208: # getlocal_0\n stack.append(registers[0])\n elif opcode == 209: # getlocal_1\n stack.append(registers[1])\n elif opcode == 210: # getlocal_2\n stack.append(registers[2])\n elif opcode == 211: # getlocal_3\n stack.append(registers[3])\n elif opcode == 212: # setlocal_0\n registers[0] = stack.pop()\n elif opcode == 213: # setlocal_1\n registers[1] = stack.pop()\n elif opcode == 214: # setlocal_2\n registers[2] = stack.pop()\n elif opcode == 215: # setlocal_3\n registers[3] = stack.pop()\n else:\n raise NotImplementedError(\n 'Unsupported opcode %d' % opcode)\n\n avm_class.method_pyfunctions[func_name] = resfunc\n return resfunc", "focal_method_lines": [437, 833], "in_stack": false, "globals": ["_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined"], "type_context": "import collections\nimport io\nimport zlib\nfrom .compat import (\n compat_str,\n compat_struct_unpack,\n)\nfrom .utils import (\n ExtractorError,\n)\n\n_u32 = _read_int\nStringClass = _AVMClass('(no name idx)', 'String')\nByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')\nTimerClass = _AVMClass('(no name idx)', 'Timer')\nTimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})\n_builtin_classes = {\n StringClass.name: StringClass,\n ByteArrayClass.name: ByteArrayClass,\n TimerClass.name: TimerClass,\n TimerEventClass.name: TimerEventClass,\n}\nundefined = _Undefined()\n\nclass _AVMClass_Object(object):\n\n def __init__(self, avm_class):\n self.avm_class = avm_class\n\nclass _ScopeDict(dict):\n\n def __init__(self, avm_class):\n super(_ScopeDict, self).__init__()\n self.avm_class = avm_class\n\nclass _AVMClass(object):\n\n def __init__(self, name_idx, name, static_properties=None):\n self.name_idx = name_idx\n self.name = name\n self.method_names = {}\n self.method_idxs = {}\n self.methods = {}\n self.method_pyfunctions = {}\n self.static_properties = static_properties if static_properties else {}\n\n self.variables = _ScopeDict(self)\n self.constants = {}\n\nclass _Multiname(object):\n\n def __init__(self, kind):\n self.kind = kind\n\nclass SWFInterpreter(object):\n\n def __init__(self, file_contents):\n self._patched_functions = {\n (TimerClass, 'addEventListener'): lambda params: undefined,\n }\n code_tag = next(tag\n for tag_code, tag in _extract_tags(file_contents)\n if tag_code == 82)\n p = code_tag.index(b'\\0', 4) + 1\n code_reader = io.BytesIO(code_tag[p:])\n\n # Parse ABC (AVM2 ByteCode)\n\n # Define a couple convenience methods\n u30 = lambda *args: _u30(*args, reader=code_reader)\n s32 = lambda *args: _s32(*args, reader=code_reader)\n u32 = lambda *args: _u32(*args, reader=code_reader)\n read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)\n read_byte = lambda *args: _read_byte(*args, reader=code_reader)\n\n # minor_version + major_version\n read_bytes(2 + 2)\n\n # Constant pool\n int_count = u30()\n self.constant_ints = [0]\n for _c in range(1, int_count):\n self.constant_ints.append(s32())\n self.constant_uints = [0]\n uint_count = u30()\n for _c in range(1, uint_count):\n self.constant_uints.append(u32())\n double_count = u30()\n read_bytes(max(0, (double_count - 1)) * 8)\n string_count = u30()\n self.constant_strings = ['']\n for _c in range(1, string_count):\n s = _read_string(code_reader)\n self.constant_strings.append(s)\n namespace_count = u30()\n for _c in range(1, namespace_count):\n read_bytes(1) # kind\n u30() # name\n ns_set_count = u30()\n for _c in range(1, ns_set_count):\n count = u30()\n for _c2 in range(count):\n u30()\n multiname_count = u30()\n MULTINAME_SIZES = {\n 0x07: 2, # QName\n 0x0d: 2, # QNameA\n 0x0f: 1, # RTQName\n 0x10: 1, # RTQNameA\n 0x11: 0, # RTQNameL\n 0x12: 0, # RTQNameLA\n 0x09: 2, # Multiname\n 0x0e: 2, # MultinameA\n 0x1b: 1, # MultinameL\n 0x1c: 1, # MultinameLA\n }\n self.multinames = ['']\n for _c in range(1, multiname_count):\n kind = u30()\n assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind\n if kind == 0x07:\n u30() # namespace_idx\n name_idx = u30()\n self.multinames.append(self.constant_strings[name_idx])\n elif kind == 0x09:\n name_idx = u30()\n u30()\n self.multinames.append(self.constant_strings[name_idx])\n else:\n self.multinames.append(_Multiname(kind))\n for _c2 in range(MULTINAME_SIZES[kind]):\n u30()\n\n # Methods\n method_count = u30()\n MethodInfo = collections.namedtuple(\n 'MethodInfo',\n ['NEED_ARGUMENTS', 'NEED_REST'])\n method_infos = []\n for method_id in range(method_count):\n param_count = u30()\n u30() # return type\n for _ in range(param_count):\n u30() # param type\n u30() # name index (always 0 for youtube)\n flags = read_byte()\n if flags & 0x08 != 0:\n # Options present\n option_count = u30()\n for c in range(option_count):\n u30() # val\n read_bytes(1) # kind\n if flags & 0x80 != 0:\n # Param names present\n for _ in range(param_count):\n u30() # param name\n mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)\n method_infos.append(mi)\n\n # Metadata\n metadata_count = u30()\n for _c in range(metadata_count):\n u30() # name\n item_count = u30()\n for _c2 in range(item_count):\n u30() # key\n u30() # value\n\n def parse_traits_info():\n trait_name_idx = u30()\n kind_full = read_byte()\n kind = kind_full & 0x0f\n attrs = kind_full >> 4\n methods = {}\n constants = None\n if kind == 0x00: # Slot\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n if vindex != 0:\n read_byte() # vkind\n elif kind == 0x06: # Const\n u30() # Slot id\n u30() # type_name_idx\n vindex = u30()\n vkind = 'any'\n if vindex != 0:\n vkind = read_byte()\n if vkind == 0x03: # Constant_Int\n value = self.constant_ints[vindex]\n elif vkind == 0x04: # Constant_UInt\n value = self.constant_uints[vindex]\n else:\n return {}, None # Ignore silently for now\n constants = {self.multinames[trait_name_idx]: value}\n elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter\n u30() # disp_id\n method_idx = u30()\n methods[self.multinames[trait_name_idx]] = method_idx\n elif kind == 0x04: # Class\n u30() # slot_id\n u30() # classi\n elif kind == 0x05: # Function\n u30() # slot_id\n function_idx = u30()\n methods[function_idx] = self.multinames[trait_name_idx]\n else:\n raise ExtractorError('Unsupported trait kind %d' % kind)\n\n if attrs & 0x4 != 0: # Metadata present\n metadata_count = u30()\n for _c3 in range(metadata_count):\n u30() # metadata index\n\n return methods, constants\n\n # Classes\n class_count = u30()\n classes = []\n for class_id in range(class_count):\n name_idx = u30()\n\n cname = self.multinames[name_idx]\n avm_class = _AVMClass(name_idx, cname)\n classes.append(avm_class)\n\n u30() # super_name idx\n flags = read_byte()\n if flags & 0x08 != 0: # Protected namespace is present\n u30() # protected_ns_idx\n intrf_count = u30()\n for _c2 in range(intrf_count):\n u30()\n u30() # iinit\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n assert len(classes) == class_count\n self._classes_by_name = dict((c.name, c) for c in classes)\n\n for avm_class in classes:\n avm_class.cinit_idx = u30()\n trait_count = u30()\n for _c2 in range(trait_count):\n trait_methods, trait_constants = parse_traits_info()\n avm_class.register_methods(trait_methods)\n if trait_constants:\n avm_class.constants.update(trait_constants)\n\n # Scripts\n script_count = u30()\n for _c in range(script_count):\n u30() # init\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n # Method bodies\n method_body_count = u30()\n Method = collections.namedtuple('Method', ['code', 'local_count'])\n self._all_methods = []\n for _c in range(method_body_count):\n method_idx = u30()\n u30() # max_stack\n local_count = u30()\n u30() # init_scope_depth\n u30() # max_scope_depth\n code_length = u30()\n code = read_bytes(code_length)\n m = Method(code, local_count)\n self._all_methods.append(m)\n for avm_class in classes:\n if method_idx in avm_class.method_idxs:\n avm_class.methods[avm_class.method_idxs[method_idx]] = m\n exception_count = u30()\n for _c2 in range(exception_count):\n u30() # from\n u30() # to\n u30() # target\n u30() # exc_type\n u30() # var_name\n trait_count = u30()\n for _c2 in range(trait_count):\n parse_traits_info()\n\n assert p + code_reader.tell() == len(code_tag)\n\n def extract_function(self, avm_class, func_name):\n p = self._patched_functions.get((avm_class, func_name))\n if p:\n return p\n if func_name in avm_class.method_pyfunctions:\n return avm_class.method_pyfunctions[func_name]\n if func_name in self._classes_by_name:\n return self._classes_by_name[func_name].make_object()\n if func_name not in avm_class.methods:\n raise ExtractorError('Cannot find function %s.%s' % (\n avm_class.name, func_name))\n m = avm_class.methods[func_name]\n\n def resfunc(args):\n # Helper functions\n coder = io.BytesIO(m.code)\n s24 = lambda: _s24(coder)\n u30 = lambda: _u30(coder)\n\n registers = [avm_class.variables] + list(args) + [None] * m.local_count\n stack = []\n scopes = collections.deque([\n self._classes_by_name, avm_class.constants, avm_class.variables])\n while True:\n opcode = _read_byte(coder)\n if opcode == 9: # label\n pass # Spec says: \"Do nothing.\"\n elif opcode == 16: # jump\n offset = s24()\n coder.seek(coder.tell() + offset)\n elif opcode == 17: # iftrue\n offset = s24()\n value = stack.pop()\n if value:\n coder.seek(coder.tell() + offset)\n elif opcode == 18: # iffalse\n offset = s24()\n value = stack.pop()\n if not value:\n coder.seek(coder.tell() + offset)\n elif opcode == 19: # ifeq\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value2 == value1:\n coder.seek(coder.tell() + offset)\n elif opcode == 20: # ifne\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value2 != value1:\n coder.seek(coder.tell() + offset)\n elif opcode == 21: # iflt\n offset = s24()\n value2 = stack.pop()\n value1 = stack.pop()\n if value1 < value2:\n coder.seek(coder.tell() + offset)\n elif opcode == 32: # pushnull\n stack.append(None)\n elif opcode == 33: # pushundefined\n stack.append(undefined)\n elif opcode == 36: # pushbyte\n v = _read_byte(coder)\n stack.append(v)\n elif opcode == 37: # pushshort\n v = u30()\n stack.append(v)\n elif opcode == 38: # pushtrue\n stack.append(True)\n elif opcode == 39: # pushfalse\n stack.append(False)\n elif opcode == 40: # pushnan\n stack.append(float('NaN'))\n elif opcode == 42: # dup\n value = stack[-1]\n stack.append(value)\n elif opcode == 44: # pushstring\n idx = u30()\n stack.append(self.constant_strings[idx])\n elif opcode == 48: # pushscope\n new_scope = stack.pop()\n scopes.append(new_scope)\n elif opcode == 66: # construct\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n res = obj.avm_class.make_object()\n stack.append(res)\n elif opcode == 70: # callproperty\n index = u30()\n mname = self.multinames[index]\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n\n if obj == StringClass:\n if mname == 'String':\n assert len(args) == 1\n assert isinstance(args[0], (\n int, compat_str, _Undefined))\n if args[0] == undefined:\n res = 'undefined'\n else:\n res = compat_str(args[0])\n stack.append(res)\n continue\n else:\n raise NotImplementedError(\n 'Function String.%s is not yet implemented'\n % mname)\n elif isinstance(obj, _AVMClass_Object):\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n stack.append(res)\n continue\n elif isinstance(obj, _AVMClass):\n func = self.extract_function(obj, mname)\n res = func(args)\n stack.append(res)\n continue\n elif isinstance(obj, _ScopeDict):\n if mname in obj.avm_class.method_names:\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n else:\n res = obj[mname]\n stack.append(res)\n continue\n elif isinstance(obj, compat_str):\n if mname == 'split':\n assert len(args) == 1\n assert isinstance(args[0], compat_str)\n if args[0] == '':\n res = list(obj)\n else:\n res = obj.split(args[0])\n stack.append(res)\n continue\n elif mname == 'charCodeAt':\n assert len(args) <= 1\n idx = 0 if len(args) == 0 else args[0]\n assert isinstance(idx, int)\n res = ord(obj[idx])\n stack.append(res)\n continue\n elif isinstance(obj, list):\n if mname == 'slice':\n assert len(args) == 1\n assert isinstance(args[0], int)\n res = obj[args[0]:]\n stack.append(res)\n continue\n elif mname == 'join':\n assert len(args) == 1\n assert isinstance(args[0], compat_str)\n res = args[0].join(obj)\n stack.append(res)\n continue\n raise NotImplementedError(\n 'Unsupported property %r on %r'\n % (mname, obj))\n elif opcode == 71: # returnvoid\n res = undefined\n return res\n elif opcode == 72: # returnvalue\n res = stack.pop()\n return res\n elif opcode == 73: # constructsuper\n # Not yet implemented, just hope it works without it\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n elif opcode == 74: # constructproperty\n index = u30()\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n\n mname = self.multinames[index]\n assert isinstance(obj, _AVMClass)\n\n # We do not actually call the constructor for now;\n # we just pretend it does nothing\n stack.append(obj.make_object())\n elif opcode == 79: # callpropvoid\n index = u30()\n mname = self.multinames[index]\n arg_count = u30()\n args = list(reversed(\n [stack.pop() for _ in range(arg_count)]))\n obj = stack.pop()\n if isinstance(obj, _AVMClass_Object):\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n assert res is undefined\n continue\n if isinstance(obj, _ScopeDict):\n assert mname in obj.avm_class.method_names\n func = self.extract_function(obj.avm_class, mname)\n res = func(args)\n assert res is undefined\n continue\n if mname == 'reverse':\n assert isinstance(obj, list)\n obj.reverse()\n else:\n raise NotImplementedError(\n 'Unsupported (void) property %r on %r'\n % (mname, obj))\n elif opcode == 86: # newarray\n arg_count = u30()\n arr = []\n for i in range(arg_count):\n arr.append(stack.pop())\n arr = arr[::-1]\n stack.append(arr)\n elif opcode == 93: # findpropstrict\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n res = s\n break\n else:\n res = scopes[0]\n if mname not in res and mname in _builtin_classes:\n stack.append(_builtin_classes[mname])\n else:\n stack.append(res[mname])\n elif opcode == 94: # findproperty\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n res = s\n break\n else:\n res = avm_class.variables\n stack.append(res)\n elif opcode == 96: # getlex\n index = u30()\n mname = self.multinames[index]\n for s in reversed(scopes):\n if mname in s:\n scope = s\n break\n else:\n scope = avm_class.variables\n\n if mname in scope:\n res = scope[mname]\n elif mname in _builtin_classes:\n res = _builtin_classes[mname]\n else:\n # Assume uninitialized\n # TODO warn here\n res = undefined\n stack.append(res)\n elif opcode == 97: # setproperty\n index = u30()\n value = stack.pop()\n idx = self.multinames[index]\n if isinstance(idx, _Multiname):\n idx = stack.pop()\n obj = stack.pop()\n obj[idx] = value\n elif opcode == 98: # getlocal\n index = u30()\n stack.append(registers[index])\n elif opcode == 99: # setlocal\n index = u30()\n value = stack.pop()\n registers[index] = value\n elif opcode == 102: # getproperty\n index = u30()\n pname = self.multinames[index]\n if pname == 'length':\n obj = stack.pop()\n assert isinstance(obj, (compat_str, list))\n stack.append(len(obj))\n elif isinstance(pname, compat_str): # Member access\n obj = stack.pop()\n if isinstance(obj, _AVMClass):\n res = obj.static_properties[pname]\n stack.append(res)\n continue\n\n assert isinstance(obj, (dict, _ScopeDict)),\\\n 'Accessing member %r on %r' % (pname, obj)\n res = obj.get(pname, undefined)\n stack.append(res)\n else: # Assume attribute access\n idx = stack.pop()\n assert isinstance(idx, int)\n obj = stack.pop()\n assert isinstance(obj, list)\n stack.append(obj[idx])\n elif opcode == 104: # initproperty\n index = u30()\n value = stack.pop()\n idx = self.multinames[index]\n if isinstance(idx, _Multiname):\n idx = stack.pop()\n obj = stack.pop()\n obj[idx] = value\n elif opcode == 115: # convert_\n value = stack.pop()\n intvalue = int(value)\n stack.append(intvalue)\n elif opcode == 128: # coerce\n u30()\n elif opcode == 130: # coerce_a\n value = stack.pop()\n # um, yes, it's any value\n stack.append(value)\n elif opcode == 133: # coerce_s\n assert isinstance(stack[-1], (type(None), compat_str))\n elif opcode == 147: # decrement\n value = stack.pop()\n assert isinstance(value, int)\n stack.append(value - 1)\n elif opcode == 149: # typeof\n value = stack.pop()\n return {\n _Undefined: 'undefined',\n compat_str: 'String',\n int: 'Number',\n float: 'Number',\n }[type(value)]\n elif opcode == 160: # add\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 + value2\n stack.append(res)\n elif opcode == 161: # subtract\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 - value2\n stack.append(res)\n elif opcode == 162: # multiply\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 * value2\n stack.append(res)\n elif opcode == 164: # modulo\n value2 = stack.pop()\n value1 = stack.pop()\n res = value1 % value2\n stack.append(res)\n elif opcode == 168: # bitand\n value2 = stack.pop()\n value1 = stack.pop()\n assert isinstance(value1, int)\n assert isinstance(value2, int)\n res = value1 & value2\n stack.append(res)\n elif opcode == 171: # equals\n value2 = stack.pop()\n value1 = stack.pop()\n result = value1 == value2\n stack.append(result)\n elif opcode == 175: # greaterequals\n value2 = stack.pop()\n value1 = stack.pop()\n result = value1 >= value2\n stack.append(result)\n elif opcode == 192: # increment_i\n value = stack.pop()\n assert isinstance(value, int)\n stack.append(value + 1)\n elif opcode == 208: # getlocal_0\n stack.append(registers[0])\n elif opcode == 209: # getlocal_1\n stack.append(registers[1])\n elif opcode == 210: # getlocal_2\n stack.append(registers[2])\n elif opcode == 211: # getlocal_3\n stack.append(registers[3])\n elif opcode == 212: # setlocal_0\n registers[0] = stack.pop()\n elif opcode == 213: # setlocal_1\n registers[1] = stack.pop()\n elif opcode == 214: # setlocal_2\n registers[2] = stack.pop()\n elif opcode == 215: # setlocal_3\n registers[3] = stack.pop()\n else:\n raise NotImplementedError(\n 'Unsupported opcode %d' % opcode)\n\n avm_class.method_pyfunctions[func_name] = resfunc\n return resfunc", "has_branch": true, "total_branches": 2}